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/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> EnablePPCPCRelTLS( 125 "enable-ppc-pcrel-tls", 126 cl::desc("enable the use of PC relative memops in TLS instructions on PPC"), 127 cl::Hidden); 128 129 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 // FIXME: Remove this once the bug has been fixed! 139 extern cl::opt<bool> ANDIGlueBug; 140 141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 142 const PPCSubtarget &STI) 143 : TargetLowering(TM), Subtarget(STI) { 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 if (Subtarget.isISA3_0()) { 175 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 177 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 178 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 179 } else { 180 // No extending loads from f16 or HW conversions back and forth. 181 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 184 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 185 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 186 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 187 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 188 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 189 } 190 191 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 192 193 // PowerPC has pre-inc load and store's. 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 204 if (!Subtarget.hasSPE()) { 205 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 206 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 209 } 210 211 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 212 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 213 for (MVT VT : ScalarIntVTs) { 214 setOperationAction(ISD::ADDC, VT, Legal); 215 setOperationAction(ISD::ADDE, VT, Legal); 216 setOperationAction(ISD::SUBC, VT, Legal); 217 setOperationAction(ISD::SUBE, VT, Legal); 218 } 219 220 if (Subtarget.useCRBits()) { 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 222 223 if (isPPC64 || Subtarget.hasFPCVT()) { 224 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 } else { 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 232 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 233 } 234 235 // PowerPC does not support direct load/store of condition registers. 236 setOperationAction(ISD::LOAD, MVT::i1, Custom); 237 setOperationAction(ISD::STORE, MVT::i1, Custom); 238 239 // FIXME: Remove this once the ANDI glue bug is fixed: 240 if (ANDIGlueBug) 241 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 242 243 for (MVT VT : MVT::integer_valuetypes()) { 244 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 245 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 246 setTruncStoreAction(VT, MVT::i1, Expand); 247 } 248 249 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 250 } 251 252 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 253 // PPC (the libcall is not available). 254 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 255 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 256 257 // We do not currently implement these libm ops for PowerPC. 258 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 259 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 260 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 261 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 262 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 263 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 264 265 // PowerPC has no SREM/UREM instructions unless we are on P9 266 // On P9 we may use a hardware instruction to compute the remainder. 267 // When the result of both the remainder and the division is required it is 268 // more efficient to compute the remainder from the result of the division 269 // rather than use the remainder instruction. The instructions are legalized 270 // directly because the DivRemPairsPass performs the transformation at the IR 271 // level. 272 if (Subtarget.isISA3_0()) { 273 setOperationAction(ISD::SREM, MVT::i32, Legal); 274 setOperationAction(ISD::UREM, MVT::i32, Legal); 275 setOperationAction(ISD::SREM, MVT::i64, Legal); 276 setOperationAction(ISD::UREM, MVT::i64, Legal); 277 } else { 278 setOperationAction(ISD::SREM, MVT::i32, Expand); 279 setOperationAction(ISD::UREM, MVT::i32, Expand); 280 setOperationAction(ISD::SREM, MVT::i64, Expand); 281 setOperationAction(ISD::UREM, MVT::i64, Expand); 282 } 283 284 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 285 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 286 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 287 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 288 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 289 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 290 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 291 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 292 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 293 294 // Handle constrained floating-point operations of scalar. 295 // TODO: Handle SPE specific operation. 296 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 297 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 298 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 299 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 300 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 301 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 302 303 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 304 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 305 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 306 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 307 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 308 if (Subtarget.hasVSX()) 309 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 310 311 if (Subtarget.hasFSQRT()) { 312 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 313 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 314 } 315 316 if (Subtarget.hasFPRND()) { 317 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 318 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 319 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 320 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 321 322 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 323 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 324 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 325 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 326 } 327 328 // We don't support sin/cos/sqrt/fmod/pow 329 setOperationAction(ISD::FSIN , MVT::f64, Expand); 330 setOperationAction(ISD::FCOS , MVT::f64, Expand); 331 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 332 setOperationAction(ISD::FREM , MVT::f64, Expand); 333 setOperationAction(ISD::FPOW , MVT::f64, Expand); 334 setOperationAction(ISD::FSIN , MVT::f32, Expand); 335 setOperationAction(ISD::FCOS , MVT::f32, Expand); 336 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 337 setOperationAction(ISD::FREM , MVT::f32, Expand); 338 setOperationAction(ISD::FPOW , MVT::f32, Expand); 339 if (Subtarget.hasSPE()) { 340 setOperationAction(ISD::FMA , MVT::f64, Expand); 341 setOperationAction(ISD::FMA , MVT::f32, Expand); 342 } else { 343 setOperationAction(ISD::FMA , MVT::f64, Legal); 344 setOperationAction(ISD::FMA , MVT::f32, Legal); 345 } 346 347 if (Subtarget.hasSPE()) 348 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 349 350 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 351 352 // If we're enabling GP optimizations, use hardware square root 353 if (!Subtarget.hasFSQRT() && 354 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 355 Subtarget.hasFRE())) 356 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 357 358 if (!Subtarget.hasFSQRT() && 359 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 360 Subtarget.hasFRES())) 361 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 362 363 if (Subtarget.hasFCPSGN()) { 364 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 365 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 366 } else { 367 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 368 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 369 } 370 371 if (Subtarget.hasFPRND()) { 372 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 373 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 374 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 375 setOperationAction(ISD::FROUND, MVT::f64, Legal); 376 377 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 378 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 379 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 380 setOperationAction(ISD::FROUND, MVT::f32, Legal); 381 } 382 383 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 384 // to speed up scalar BSWAP64. 385 // CTPOP or CTTZ were introduced in P8/P9 respectively 386 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 387 if (Subtarget.hasP9Vector()) 388 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 389 else 390 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 391 if (Subtarget.isISA3_0()) { 392 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 393 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 394 } else { 395 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 396 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 397 } 398 399 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 400 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 401 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 402 } else { 403 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 404 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 405 } 406 407 // PowerPC does not have ROTR 408 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 409 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 410 411 if (!Subtarget.useCRBits()) { 412 // PowerPC does not have Select 413 setOperationAction(ISD::SELECT, MVT::i32, Expand); 414 setOperationAction(ISD::SELECT, MVT::i64, Expand); 415 setOperationAction(ISD::SELECT, MVT::f32, Expand); 416 setOperationAction(ISD::SELECT, MVT::f64, Expand); 417 } 418 419 // PowerPC wants to turn select_cc of FP into fsel when possible. 420 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 421 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 422 423 // PowerPC wants to optimize integer setcc a bit 424 if (!Subtarget.useCRBits()) 425 setOperationAction(ISD::SETCC, MVT::i32, Custom); 426 427 if (Subtarget.hasFPU()) { 428 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 429 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 431 432 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 433 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 435 } 436 437 // PowerPC does not have BRCOND which requires SetCC 438 if (!Subtarget.useCRBits()) 439 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 440 441 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 442 443 if (Subtarget.hasSPE()) { 444 // SPE has built-in conversions 445 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 446 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 447 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 448 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 449 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 450 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 451 } else { 452 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 453 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 454 455 // PowerPC does not have [U|S]INT_TO_FP 456 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 457 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 458 } 459 460 if (Subtarget.hasDirectMove() && isPPC64) { 461 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 462 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 463 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 464 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 465 if (TM.Options.UnsafeFPMath) { 466 setOperationAction(ISD::LRINT, MVT::f64, Legal); 467 setOperationAction(ISD::LRINT, MVT::f32, Legal); 468 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 469 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 470 setOperationAction(ISD::LROUND, MVT::f64, Legal); 471 setOperationAction(ISD::LROUND, MVT::f32, Legal); 472 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 473 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 474 } 475 } else { 476 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 477 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 478 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 479 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 480 } 481 482 // We cannot sextinreg(i1). Expand to shifts. 483 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 484 485 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 486 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 487 // support continuation, user-level threading, and etc.. As a result, no 488 // other SjLj exception interfaces are implemented and please don't build 489 // your own exception handling based on them. 490 // LLVM/Clang supports zero-cost DWARF exception handling. 491 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 492 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 493 494 // We want to legalize GlobalAddress and ConstantPool nodes into the 495 // appropriate instructions to materialize the address. 496 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 497 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 498 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 499 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 500 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 501 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 502 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 503 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 504 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 505 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 506 507 // TRAP is legal. 508 setOperationAction(ISD::TRAP, MVT::Other, Legal); 509 510 // TRAMPOLINE is custom lowered. 511 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 512 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 513 514 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 515 setOperationAction(ISD::VASTART , MVT::Other, Custom); 516 517 if (Subtarget.is64BitELFABI()) { 518 // VAARG always uses double-word chunks, so promote anything smaller. 519 setOperationAction(ISD::VAARG, MVT::i1, Promote); 520 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 521 setOperationAction(ISD::VAARG, MVT::i8, Promote); 522 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 523 setOperationAction(ISD::VAARG, MVT::i16, Promote); 524 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 525 setOperationAction(ISD::VAARG, MVT::i32, Promote); 526 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 527 setOperationAction(ISD::VAARG, MVT::Other, Expand); 528 } else if (Subtarget.is32BitELFABI()) { 529 // VAARG is custom lowered with the 32-bit SVR4 ABI. 530 setOperationAction(ISD::VAARG, MVT::Other, Custom); 531 setOperationAction(ISD::VAARG, MVT::i64, Custom); 532 } else 533 setOperationAction(ISD::VAARG, MVT::Other, Expand); 534 535 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 536 if (Subtarget.is32BitELFABI()) 537 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 538 else 539 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 540 541 // Use the default implementation. 542 setOperationAction(ISD::VAEND , MVT::Other, Expand); 543 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 544 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 545 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 546 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 547 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 548 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 549 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 550 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 551 552 // We want to custom lower some of our intrinsics. 553 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 554 555 // To handle counter-based loop conditions. 556 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 557 558 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 559 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 560 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 561 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 562 563 // Comparisons that require checking two conditions. 564 if (Subtarget.hasSPE()) { 565 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 566 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 567 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 568 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 569 } 570 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 571 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 572 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 573 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 574 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 575 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 576 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 577 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 578 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 579 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 580 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 581 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 582 583 if (Subtarget.has64BitSupport()) { 584 // They also have instructions for converting between i64 and fp. 585 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 586 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 587 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 588 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 589 // This is just the low 32 bits of a (signed) fp->i64 conversion. 590 // We cannot do this with Promote because i64 is not a legal type. 591 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 592 593 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 594 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 595 } else { 596 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 597 if (Subtarget.hasSPE()) { 598 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 599 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 600 } else 601 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 602 } 603 604 // With the instructions enabled under FPCVT, we can do everything. 605 if (Subtarget.hasFPCVT()) { 606 if (Subtarget.has64BitSupport()) { 607 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 608 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 609 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 610 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 611 } 612 613 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 614 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 615 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 616 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 617 } 618 619 if (Subtarget.use64BitRegs()) { 620 // 64-bit PowerPC implementations can support i64 types directly 621 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 622 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 623 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 624 // 64-bit PowerPC wants to expand i128 shifts itself. 625 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 626 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 627 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 628 } else { 629 // 32-bit PowerPC wants to expand i64 shifts itself. 630 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 631 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 632 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 633 } 634 635 // PowerPC has better expansions for funnel shifts than the generic 636 // TargetLowering::expandFunnelShift. 637 if (Subtarget.has64BitSupport()) { 638 setOperationAction(ISD::FSHL, MVT::i64, Custom); 639 setOperationAction(ISD::FSHR, MVT::i64, Custom); 640 } 641 setOperationAction(ISD::FSHL, MVT::i32, Custom); 642 setOperationAction(ISD::FSHR, MVT::i32, Custom); 643 644 if (Subtarget.hasVSX()) { 645 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 646 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 647 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 648 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 649 } 650 651 if (Subtarget.hasAltivec()) { 652 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 653 setOperationAction(ISD::SADDSAT, VT, Legal); 654 setOperationAction(ISD::SSUBSAT, VT, Legal); 655 setOperationAction(ISD::UADDSAT, VT, Legal); 656 setOperationAction(ISD::USUBSAT, VT, Legal); 657 } 658 // First set operation action for all vector types to expand. Then we 659 // will selectively turn on ones that can be effectively codegen'd. 660 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 661 // add/sub are legal for all supported vector VT's. 662 setOperationAction(ISD::ADD, VT, Legal); 663 setOperationAction(ISD::SUB, VT, Legal); 664 665 // For v2i64, these are only valid with P8Vector. This is corrected after 666 // the loop. 667 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 668 setOperationAction(ISD::SMAX, VT, Legal); 669 setOperationAction(ISD::SMIN, VT, Legal); 670 setOperationAction(ISD::UMAX, VT, Legal); 671 setOperationAction(ISD::UMIN, VT, Legal); 672 } 673 else { 674 setOperationAction(ISD::SMAX, VT, Expand); 675 setOperationAction(ISD::SMIN, VT, Expand); 676 setOperationAction(ISD::UMAX, VT, Expand); 677 setOperationAction(ISD::UMIN, VT, Expand); 678 } 679 680 if (Subtarget.hasVSX()) { 681 setOperationAction(ISD::FMAXNUM, VT, Legal); 682 setOperationAction(ISD::FMINNUM, VT, Legal); 683 } 684 685 // Vector instructions introduced in P8 686 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 687 setOperationAction(ISD::CTPOP, VT, Legal); 688 setOperationAction(ISD::CTLZ, VT, Legal); 689 } 690 else { 691 setOperationAction(ISD::CTPOP, VT, Expand); 692 setOperationAction(ISD::CTLZ, VT, Expand); 693 } 694 695 // Vector instructions introduced in P9 696 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 697 setOperationAction(ISD::CTTZ, VT, Legal); 698 else 699 setOperationAction(ISD::CTTZ, VT, Expand); 700 701 // We promote all shuffles to v16i8. 702 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 703 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 704 705 // We promote all non-typed operations to v4i32. 706 setOperationAction(ISD::AND , VT, Promote); 707 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 708 setOperationAction(ISD::OR , VT, Promote); 709 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 710 setOperationAction(ISD::XOR , VT, Promote); 711 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 712 setOperationAction(ISD::LOAD , VT, Promote); 713 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 714 setOperationAction(ISD::SELECT, VT, Promote); 715 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 716 setOperationAction(ISD::VSELECT, VT, Legal); 717 setOperationAction(ISD::SELECT_CC, VT, Promote); 718 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 719 setOperationAction(ISD::STORE, VT, Promote); 720 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 721 722 // No other operations are legal. 723 setOperationAction(ISD::MUL , VT, Expand); 724 setOperationAction(ISD::SDIV, VT, Expand); 725 setOperationAction(ISD::SREM, VT, Expand); 726 setOperationAction(ISD::UDIV, VT, Expand); 727 setOperationAction(ISD::UREM, VT, Expand); 728 setOperationAction(ISD::FDIV, VT, Expand); 729 setOperationAction(ISD::FREM, VT, Expand); 730 setOperationAction(ISD::FNEG, VT, Expand); 731 setOperationAction(ISD::FSQRT, VT, Expand); 732 setOperationAction(ISD::FLOG, VT, Expand); 733 setOperationAction(ISD::FLOG10, VT, Expand); 734 setOperationAction(ISD::FLOG2, VT, Expand); 735 setOperationAction(ISD::FEXP, VT, Expand); 736 setOperationAction(ISD::FEXP2, VT, Expand); 737 setOperationAction(ISD::FSIN, VT, Expand); 738 setOperationAction(ISD::FCOS, VT, Expand); 739 setOperationAction(ISD::FABS, VT, Expand); 740 setOperationAction(ISD::FFLOOR, VT, Expand); 741 setOperationAction(ISD::FCEIL, VT, Expand); 742 setOperationAction(ISD::FTRUNC, VT, Expand); 743 setOperationAction(ISD::FRINT, VT, Expand); 744 setOperationAction(ISD::FNEARBYINT, VT, Expand); 745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 747 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 748 setOperationAction(ISD::MULHU, VT, Expand); 749 setOperationAction(ISD::MULHS, VT, Expand); 750 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 751 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 752 setOperationAction(ISD::UDIVREM, VT, Expand); 753 setOperationAction(ISD::SDIVREM, VT, Expand); 754 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 755 setOperationAction(ISD::FPOW, VT, Expand); 756 setOperationAction(ISD::BSWAP, VT, Expand); 757 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 758 setOperationAction(ISD::ROTL, VT, Expand); 759 setOperationAction(ISD::ROTR, VT, Expand); 760 761 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 762 setTruncStoreAction(VT, InnerVT, Expand); 763 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 764 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 765 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 766 } 767 } 768 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 769 if (!Subtarget.hasP8Vector()) { 770 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 771 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 772 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 773 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 774 } 775 776 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 777 setOperationAction(ISD::ABS, VT, Custom); 778 779 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 780 // with merges, splats, etc. 781 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 782 783 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 784 // are cheap, so handle them before they get expanded to scalar. 785 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 786 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 787 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 788 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 789 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 790 791 setOperationAction(ISD::AND , MVT::v4i32, Legal); 792 setOperationAction(ISD::OR , MVT::v4i32, Legal); 793 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 794 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 795 setOperationAction(ISD::SELECT, MVT::v4i32, 796 Subtarget.useCRBits() ? Legal : Expand); 797 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 798 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 799 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 800 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 801 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 802 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 803 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 804 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 805 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 806 807 // Without hasP8Altivec set, v2i64 SMAX isn't available. 808 // But ABS custom lowering requires SMAX support. 809 if (!Subtarget.hasP8Altivec()) 810 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 811 812 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 813 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 814 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 815 if (Subtarget.hasAltivec()) 816 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 817 setOperationAction(ISD::ROTL, VT, Legal); 818 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 819 if (Subtarget.hasP8Altivec()) 820 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 821 822 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 823 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 824 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 825 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 826 827 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 828 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 829 830 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 831 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 832 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 833 } 834 835 if (Subtarget.hasP8Altivec()) 836 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 837 else 838 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 839 840 if (Subtarget.isISA3_1()) { 841 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 842 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 843 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 844 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 845 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 846 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 847 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 848 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 849 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 850 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 851 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 852 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 853 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 854 } 855 856 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 857 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 858 859 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 860 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 861 862 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 863 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 864 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 865 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 866 867 // Altivec does not contain unordered floating-point compare instructions 868 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 869 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 870 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 871 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 872 873 if (Subtarget.hasVSX()) { 874 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 876 if (Subtarget.hasP8Vector()) { 877 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 878 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 879 } 880 if (Subtarget.hasDirectMove() && isPPC64) { 881 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 882 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 883 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 884 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 885 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 886 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 889 } 890 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 891 892 // The nearbyint variants are not allowed to raise the inexact exception 893 // so we can only code-gen them with unsafe math. 894 if (TM.Options.UnsafeFPMath) { 895 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 896 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 897 } 898 899 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 900 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 901 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 902 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 903 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 904 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 905 setOperationAction(ISD::FROUND, MVT::f64, Legal); 906 setOperationAction(ISD::FRINT, MVT::f64, Legal); 907 908 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 909 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 910 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 911 setOperationAction(ISD::FROUND, MVT::f32, Legal); 912 setOperationAction(ISD::FRINT, MVT::f32, Legal); 913 914 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 915 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 916 917 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 918 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 919 920 // Share the Altivec comparison restrictions. 921 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 922 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 923 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 924 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 925 926 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 927 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 928 929 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 930 931 if (Subtarget.hasP8Vector()) 932 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 933 934 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 935 936 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 937 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 938 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 939 940 if (Subtarget.hasP8Altivec()) { 941 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 942 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 943 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 944 945 // 128 bit shifts can be accomplished via 3 instructions for SHL and 946 // SRL, but not for SRA because of the instructions available: 947 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 948 // doing 949 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 950 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 951 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 952 953 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 954 } 955 else { 956 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 957 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 958 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 959 960 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 961 962 // VSX v2i64 only supports non-arithmetic operations. 963 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 964 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 965 } 966 967 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 968 969 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 970 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 971 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 972 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 973 974 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 975 976 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 977 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 978 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 979 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 980 981 // Custom handling for partial vectors of integers converted to 982 // floating point. We already have optimal handling for v2i32 through 983 // the DAG combine, so those aren't necessary. 984 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 985 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 986 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 987 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 988 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 989 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 990 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 991 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 992 993 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 994 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 995 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 996 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 997 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 998 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 999 1000 if (Subtarget.hasDirectMove()) 1001 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1002 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1003 1004 // Handle constrained floating-point operations of vector. 1005 // The predictor is `hasVSX` because altivec instruction has 1006 // no exception but VSX vector instruction has. 1007 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1008 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1009 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1010 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1011 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1012 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1013 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1014 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1015 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 1016 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1017 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1018 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1019 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1020 1021 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1022 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1023 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1024 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1025 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1026 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1027 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1028 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1029 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 1030 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1031 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1032 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1033 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1034 1035 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1036 } 1037 1038 if (Subtarget.hasP8Altivec()) { 1039 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1040 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1041 } 1042 1043 if (Subtarget.hasP9Vector()) { 1044 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1045 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1046 1047 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1048 // SRL, but not for SRA because of the instructions available: 1049 // VS{RL} and VS{RL}O. 1050 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1051 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1052 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1053 1054 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1055 setOperationAction(ISD::FADD, MVT::f128, Legal); 1056 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1057 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1058 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1059 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1060 // No extending loads to f128 on PPC. 1061 for (MVT FPT : MVT::fp_valuetypes()) 1062 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1063 setOperationAction(ISD::FMA, MVT::f128, Legal); 1064 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1065 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1066 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1067 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1068 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1069 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1070 1071 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1072 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1073 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1074 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1075 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1076 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1077 1078 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1079 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1080 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1081 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1082 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1083 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1084 // No implementation for these ops for PowerPC. 1085 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1086 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1087 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1088 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1089 setOperationAction(ISD::FREM, MVT::f128, Expand); 1090 1091 // Handle constrained floating-point operations of fp128 1092 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1093 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1094 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1095 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1096 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1097 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1098 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1099 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1100 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1101 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1102 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1103 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1104 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1105 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1106 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1107 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1108 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1109 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1110 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1111 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1112 } 1113 1114 if (Subtarget.hasP9Altivec()) { 1115 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1116 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1117 1118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1125 } 1126 } 1127 1128 if (Subtarget.has64BitSupport()) 1129 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1130 1131 if (Subtarget.isISA3_1()) 1132 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1133 1134 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1135 1136 if (!isPPC64) { 1137 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1138 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1139 } 1140 1141 setBooleanContents(ZeroOrOneBooleanContent); 1142 1143 if (Subtarget.hasAltivec()) { 1144 // Altivec instructions set fields to all zeros or all ones. 1145 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1146 } 1147 1148 if (!isPPC64) { 1149 // These libcalls are not available in 32-bit. 1150 setLibcallName(RTLIB::SHL_I128, nullptr); 1151 setLibcallName(RTLIB::SRL_I128, nullptr); 1152 setLibcallName(RTLIB::SRA_I128, nullptr); 1153 } 1154 1155 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1156 1157 // We have target-specific dag combine patterns for the following nodes: 1158 setTargetDAGCombine(ISD::ADD); 1159 setTargetDAGCombine(ISD::SHL); 1160 setTargetDAGCombine(ISD::SRA); 1161 setTargetDAGCombine(ISD::SRL); 1162 setTargetDAGCombine(ISD::MUL); 1163 setTargetDAGCombine(ISD::FMA); 1164 setTargetDAGCombine(ISD::SINT_TO_FP); 1165 setTargetDAGCombine(ISD::BUILD_VECTOR); 1166 if (Subtarget.hasFPCVT()) 1167 setTargetDAGCombine(ISD::UINT_TO_FP); 1168 setTargetDAGCombine(ISD::LOAD); 1169 setTargetDAGCombine(ISD::STORE); 1170 setTargetDAGCombine(ISD::BR_CC); 1171 if (Subtarget.useCRBits()) 1172 setTargetDAGCombine(ISD::BRCOND); 1173 setTargetDAGCombine(ISD::BSWAP); 1174 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1175 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1176 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1177 1178 setTargetDAGCombine(ISD::SIGN_EXTEND); 1179 setTargetDAGCombine(ISD::ZERO_EXTEND); 1180 setTargetDAGCombine(ISD::ANY_EXTEND); 1181 1182 setTargetDAGCombine(ISD::TRUNCATE); 1183 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1184 1185 1186 if (Subtarget.useCRBits()) { 1187 setTargetDAGCombine(ISD::TRUNCATE); 1188 setTargetDAGCombine(ISD::SETCC); 1189 setTargetDAGCombine(ISD::SELECT_CC); 1190 } 1191 1192 // Use reciprocal estimates. 1193 if (TM.Options.UnsafeFPMath) { 1194 setTargetDAGCombine(ISD::FDIV); 1195 setTargetDAGCombine(ISD::FSQRT); 1196 } 1197 1198 if (Subtarget.hasP9Altivec()) { 1199 setTargetDAGCombine(ISD::ABS); 1200 setTargetDAGCombine(ISD::VSELECT); 1201 } 1202 1203 setLibcallName(RTLIB::LOG_F128, "logf128"); 1204 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1205 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1206 setLibcallName(RTLIB::EXP_F128, "expf128"); 1207 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1208 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1209 setLibcallName(RTLIB::COS_F128, "cosf128"); 1210 setLibcallName(RTLIB::POW_F128, "powf128"); 1211 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1212 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1213 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1214 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1215 1216 // With 32 condition bits, we don't need to sink (and duplicate) compares 1217 // aggressively in CodeGenPrep. 1218 if (Subtarget.useCRBits()) { 1219 setHasMultipleConditionRegisters(); 1220 setJumpIsExpensive(); 1221 } 1222 1223 setMinFunctionAlignment(Align(4)); 1224 1225 switch (Subtarget.getCPUDirective()) { 1226 default: break; 1227 case PPC::DIR_970: 1228 case PPC::DIR_A2: 1229 case PPC::DIR_E500: 1230 case PPC::DIR_E500mc: 1231 case PPC::DIR_E5500: 1232 case PPC::DIR_PWR4: 1233 case PPC::DIR_PWR5: 1234 case PPC::DIR_PWR5X: 1235 case PPC::DIR_PWR6: 1236 case PPC::DIR_PWR6X: 1237 case PPC::DIR_PWR7: 1238 case PPC::DIR_PWR8: 1239 case PPC::DIR_PWR9: 1240 case PPC::DIR_PWR10: 1241 case PPC::DIR_PWR_FUTURE: 1242 setPrefLoopAlignment(Align(16)); 1243 setPrefFunctionAlignment(Align(16)); 1244 break; 1245 } 1246 1247 if (Subtarget.enableMachineScheduler()) 1248 setSchedulingPreference(Sched::Source); 1249 else 1250 setSchedulingPreference(Sched::Hybrid); 1251 1252 computeRegisterProperties(STI.getRegisterInfo()); 1253 1254 // The Freescale cores do better with aggressive inlining of memcpy and 1255 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1256 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1257 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1258 MaxStoresPerMemset = 32; 1259 MaxStoresPerMemsetOptSize = 16; 1260 MaxStoresPerMemcpy = 32; 1261 MaxStoresPerMemcpyOptSize = 8; 1262 MaxStoresPerMemmove = 32; 1263 MaxStoresPerMemmoveOptSize = 8; 1264 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1265 // The A2 also benefits from (very) aggressive inlining of memcpy and 1266 // friends. The overhead of a the function call, even when warm, can be 1267 // over one hundred cycles. 1268 MaxStoresPerMemset = 128; 1269 MaxStoresPerMemcpy = 128; 1270 MaxStoresPerMemmove = 128; 1271 MaxLoadsPerMemcmp = 128; 1272 } else { 1273 MaxLoadsPerMemcmp = 8; 1274 MaxLoadsPerMemcmpOptSize = 4; 1275 } 1276 1277 // Let the subtarget (CPU) decide if a predictable select is more expensive 1278 // than the corresponding branch. This information is used in CGP to decide 1279 // when to convert selects into branches. 1280 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1281 } 1282 1283 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1284 /// the desired ByVal argument alignment. 1285 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1286 if (MaxAlign == MaxMaxAlign) 1287 return; 1288 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1289 if (MaxMaxAlign >= 32 && 1290 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1291 MaxAlign = Align(32); 1292 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1293 MaxAlign < 16) 1294 MaxAlign = Align(16); 1295 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1296 Align EltAlign; 1297 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1298 if (EltAlign > MaxAlign) 1299 MaxAlign = EltAlign; 1300 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1301 for (auto *EltTy : STy->elements()) { 1302 Align EltAlign; 1303 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1304 if (EltAlign > MaxAlign) 1305 MaxAlign = EltAlign; 1306 if (MaxAlign == MaxMaxAlign) 1307 break; 1308 } 1309 } 1310 } 1311 1312 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1313 /// function arguments in the caller parameter area. 1314 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1315 const DataLayout &DL) const { 1316 // 16byte and wider vectors are passed on 16byte boundary. 1317 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1318 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1319 if (Subtarget.hasAltivec()) 1320 getMaxByValAlign(Ty, Alignment, Align(16)); 1321 return Alignment.value(); 1322 } 1323 1324 bool PPCTargetLowering::useSoftFloat() const { 1325 return Subtarget.useSoftFloat(); 1326 } 1327 1328 bool PPCTargetLowering::hasSPE() const { 1329 return Subtarget.hasSPE(); 1330 } 1331 1332 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1333 return VT.isScalarInteger(); 1334 } 1335 1336 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1337 /// type is cheaper than a multiply followed by a shift. 1338 /// This is true for words and doublewords on 64-bit PowerPC. 1339 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1340 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1341 isOperationLegal(ISD::MULHU, Type))) 1342 return true; 1343 return TargetLowering::isMulhCheaperThanMulShift(Type); 1344 } 1345 1346 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1347 switch ((PPCISD::NodeType)Opcode) { 1348 case PPCISD::FIRST_NUMBER: break; 1349 case PPCISD::FSEL: return "PPCISD::FSEL"; 1350 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1351 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1352 case PPCISD::FCFID: return "PPCISD::FCFID"; 1353 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1354 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1355 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1356 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1357 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1358 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1359 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1360 case PPCISD::FP_TO_UINT_IN_VSR: 1361 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1362 case PPCISD::FP_TO_SINT_IN_VSR: 1363 return "PPCISD::FP_TO_SINT_IN_VSR"; 1364 case PPCISD::FRE: return "PPCISD::FRE"; 1365 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1366 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1367 case PPCISD::VPERM: return "PPCISD::VPERM"; 1368 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1369 case PPCISD::XXSPLTI_SP_TO_DP: 1370 return "PPCISD::XXSPLTI_SP_TO_DP"; 1371 case PPCISD::XXSPLTI32DX: 1372 return "PPCISD::XXSPLTI32DX"; 1373 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1374 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1375 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1376 case PPCISD::CMPB: return "PPCISD::CMPB"; 1377 case PPCISD::Hi: return "PPCISD::Hi"; 1378 case PPCISD::Lo: return "PPCISD::Lo"; 1379 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1380 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1381 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1382 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1383 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1384 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1385 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1386 case PPCISD::SRL: return "PPCISD::SRL"; 1387 case PPCISD::SRA: return "PPCISD::SRA"; 1388 case PPCISD::SHL: return "PPCISD::SHL"; 1389 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1390 case PPCISD::CALL: return "PPCISD::CALL"; 1391 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1392 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1393 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1394 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1395 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1396 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1397 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1398 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1399 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1400 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1401 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1402 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1403 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1404 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1405 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1406 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1407 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1408 case PPCISD::ANDI_rec_1_EQ_BIT: 1409 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1410 case PPCISD::ANDI_rec_1_GT_BIT: 1411 return "PPCISD::ANDI_rec_1_GT_BIT"; 1412 case PPCISD::VCMP: return "PPCISD::VCMP"; 1413 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1414 case PPCISD::LBRX: return "PPCISD::LBRX"; 1415 case PPCISD::STBRX: return "PPCISD::STBRX"; 1416 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1417 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1418 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1419 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1420 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1421 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1422 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1423 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1424 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1425 case PPCISD::ST_VSR_SCAL_INT: 1426 return "PPCISD::ST_VSR_SCAL_INT"; 1427 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1428 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1429 case PPCISD::BDZ: return "PPCISD::BDZ"; 1430 case PPCISD::MFFS: return "PPCISD::MFFS"; 1431 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1432 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1433 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1434 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1435 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1436 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1437 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1438 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1439 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1440 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1441 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1442 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1443 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1444 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1445 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1446 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1447 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1448 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1449 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1450 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1451 case PPCISD::SC: return "PPCISD::SC"; 1452 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1453 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1454 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1455 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1456 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1457 case PPCISD::VABSD: return "PPCISD::VABSD"; 1458 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1459 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1460 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1461 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1462 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1463 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1464 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1465 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1466 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1467 } 1468 return nullptr; 1469 } 1470 1471 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1472 EVT VT) const { 1473 if (!VT.isVector()) 1474 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1475 1476 return VT.changeVectorElementTypeToInteger(); 1477 } 1478 1479 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1480 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1481 return true; 1482 } 1483 1484 //===----------------------------------------------------------------------===// 1485 // Node matching predicates, for use by the tblgen matching code. 1486 //===----------------------------------------------------------------------===// 1487 1488 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1489 static bool isFloatingPointZero(SDValue Op) { 1490 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1491 return CFP->getValueAPF().isZero(); 1492 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1493 // Maybe this has already been legalized into the constant pool? 1494 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1495 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1496 return CFP->getValueAPF().isZero(); 1497 } 1498 return false; 1499 } 1500 1501 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1502 /// true if Op is undef or if it matches the specified value. 1503 static bool isConstantOrUndef(int Op, int Val) { 1504 return Op < 0 || Op == Val; 1505 } 1506 1507 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1508 /// VPKUHUM instruction. 1509 /// The ShuffleKind distinguishes between big-endian operations with 1510 /// two different inputs (0), either-endian operations with two identical 1511 /// inputs (1), and little-endian operations with two different inputs (2). 1512 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1513 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1514 SelectionDAG &DAG) { 1515 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1516 if (ShuffleKind == 0) { 1517 if (IsLE) 1518 return false; 1519 for (unsigned i = 0; i != 16; ++i) 1520 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1521 return false; 1522 } else if (ShuffleKind == 2) { 1523 if (!IsLE) 1524 return false; 1525 for (unsigned i = 0; i != 16; ++i) 1526 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1527 return false; 1528 } else if (ShuffleKind == 1) { 1529 unsigned j = IsLE ? 0 : 1; 1530 for (unsigned i = 0; i != 8; ++i) 1531 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1532 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1533 return false; 1534 } 1535 return true; 1536 } 1537 1538 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1539 /// VPKUWUM instruction. 1540 /// The ShuffleKind distinguishes between big-endian operations with 1541 /// two different inputs (0), either-endian operations with two identical 1542 /// inputs (1), and little-endian operations with two different inputs (2). 1543 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1544 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1545 SelectionDAG &DAG) { 1546 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1547 if (ShuffleKind == 0) { 1548 if (IsLE) 1549 return false; 1550 for (unsigned i = 0; i != 16; i += 2) 1551 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1552 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1553 return false; 1554 } else if (ShuffleKind == 2) { 1555 if (!IsLE) 1556 return false; 1557 for (unsigned i = 0; i != 16; i += 2) 1558 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1559 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1560 return false; 1561 } else if (ShuffleKind == 1) { 1562 unsigned j = IsLE ? 0 : 2; 1563 for (unsigned i = 0; i != 8; i += 2) 1564 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1565 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1566 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1567 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1568 return false; 1569 } 1570 return true; 1571 } 1572 1573 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1574 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1575 /// current subtarget. 1576 /// 1577 /// The ShuffleKind distinguishes between big-endian operations with 1578 /// two different inputs (0), either-endian operations with two identical 1579 /// inputs (1), and little-endian operations with two different inputs (2). 1580 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1581 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1582 SelectionDAG &DAG) { 1583 const PPCSubtarget& Subtarget = 1584 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1585 if (!Subtarget.hasP8Vector()) 1586 return false; 1587 1588 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1589 if (ShuffleKind == 0) { 1590 if (IsLE) 1591 return false; 1592 for (unsigned i = 0; i != 16; i += 4) 1593 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1594 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1595 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1596 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1597 return false; 1598 } else if (ShuffleKind == 2) { 1599 if (!IsLE) 1600 return false; 1601 for (unsigned i = 0; i != 16; i += 4) 1602 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1603 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1604 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1605 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1606 return false; 1607 } else if (ShuffleKind == 1) { 1608 unsigned j = IsLE ? 0 : 4; 1609 for (unsigned i = 0; i != 8; i += 4) 1610 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1611 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1612 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1613 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1614 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1615 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1616 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1617 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1618 return false; 1619 } 1620 return true; 1621 } 1622 1623 /// isVMerge - Common function, used to match vmrg* shuffles. 1624 /// 1625 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1626 unsigned LHSStart, unsigned RHSStart) { 1627 if (N->getValueType(0) != MVT::v16i8) 1628 return false; 1629 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1630 "Unsupported merge size!"); 1631 1632 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1633 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1634 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1635 LHSStart+j+i*UnitSize) || 1636 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1637 RHSStart+j+i*UnitSize)) 1638 return false; 1639 } 1640 return true; 1641 } 1642 1643 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1644 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1645 /// The ShuffleKind distinguishes between big-endian merges with two 1646 /// different inputs (0), either-endian merges with two identical inputs (1), 1647 /// and little-endian merges with two different inputs (2). For the latter, 1648 /// the input operands are swapped (see PPCInstrAltivec.td). 1649 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1650 unsigned ShuffleKind, SelectionDAG &DAG) { 1651 if (DAG.getDataLayout().isLittleEndian()) { 1652 if (ShuffleKind == 1) // unary 1653 return isVMerge(N, UnitSize, 0, 0); 1654 else if (ShuffleKind == 2) // swapped 1655 return isVMerge(N, UnitSize, 0, 16); 1656 else 1657 return false; 1658 } else { 1659 if (ShuffleKind == 1) // unary 1660 return isVMerge(N, UnitSize, 8, 8); 1661 else if (ShuffleKind == 0) // normal 1662 return isVMerge(N, UnitSize, 8, 24); 1663 else 1664 return false; 1665 } 1666 } 1667 1668 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1669 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1670 /// The ShuffleKind distinguishes between big-endian merges with two 1671 /// different inputs (0), either-endian merges with two identical inputs (1), 1672 /// and little-endian merges with two different inputs (2). For the latter, 1673 /// the input operands are swapped (see PPCInstrAltivec.td). 1674 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1675 unsigned ShuffleKind, SelectionDAG &DAG) { 1676 if (DAG.getDataLayout().isLittleEndian()) { 1677 if (ShuffleKind == 1) // unary 1678 return isVMerge(N, UnitSize, 8, 8); 1679 else if (ShuffleKind == 2) // swapped 1680 return isVMerge(N, UnitSize, 8, 24); 1681 else 1682 return false; 1683 } else { 1684 if (ShuffleKind == 1) // unary 1685 return isVMerge(N, UnitSize, 0, 0); 1686 else if (ShuffleKind == 0) // normal 1687 return isVMerge(N, UnitSize, 0, 16); 1688 else 1689 return false; 1690 } 1691 } 1692 1693 /** 1694 * Common function used to match vmrgew and vmrgow shuffles 1695 * 1696 * The indexOffset determines whether to look for even or odd words in 1697 * the shuffle mask. This is based on the of the endianness of the target 1698 * machine. 1699 * - Little Endian: 1700 * - Use offset of 0 to check for odd elements 1701 * - Use offset of 4 to check for even elements 1702 * - Big Endian: 1703 * - Use offset of 0 to check for even elements 1704 * - Use offset of 4 to check for odd elements 1705 * A detailed description of the vector element ordering for little endian and 1706 * big endian can be found at 1707 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1708 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1709 * compiler differences mean to you 1710 * 1711 * The mask to the shuffle vector instruction specifies the indices of the 1712 * elements from the two input vectors to place in the result. The elements are 1713 * numbered in array-access order, starting with the first vector. These vectors 1714 * are always of type v16i8, thus each vector will contain 16 elements of size 1715 * 8. More info on the shuffle vector can be found in the 1716 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1717 * Language Reference. 1718 * 1719 * The RHSStartValue indicates whether the same input vectors are used (unary) 1720 * or two different input vectors are used, based on the following: 1721 * - If the instruction uses the same vector for both inputs, the range of the 1722 * indices will be 0 to 15. In this case, the RHSStart value passed should 1723 * be 0. 1724 * - If the instruction has two different vectors then the range of the 1725 * indices will be 0 to 31. In this case, the RHSStart value passed should 1726 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1727 * to 31 specify elements in the second vector). 1728 * 1729 * \param[in] N The shuffle vector SD Node to analyze 1730 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1731 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1732 * vector to the shuffle_vector instruction 1733 * \return true iff this shuffle vector represents an even or odd word merge 1734 */ 1735 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1736 unsigned RHSStartValue) { 1737 if (N->getValueType(0) != MVT::v16i8) 1738 return false; 1739 1740 for (unsigned i = 0; i < 2; ++i) 1741 for (unsigned j = 0; j < 4; ++j) 1742 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1743 i*RHSStartValue+j+IndexOffset) || 1744 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1745 i*RHSStartValue+j+IndexOffset+8)) 1746 return false; 1747 return true; 1748 } 1749 1750 /** 1751 * Determine if the specified shuffle mask is suitable for the vmrgew or 1752 * vmrgow instructions. 1753 * 1754 * \param[in] N The shuffle vector SD Node to analyze 1755 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1756 * \param[in] ShuffleKind Identify the type of merge: 1757 * - 0 = big-endian merge with two different inputs; 1758 * - 1 = either-endian merge with two identical inputs; 1759 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1760 * little-endian merges). 1761 * \param[in] DAG The current SelectionDAG 1762 * \return true iff this shuffle mask 1763 */ 1764 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1765 unsigned ShuffleKind, SelectionDAG &DAG) { 1766 if (DAG.getDataLayout().isLittleEndian()) { 1767 unsigned indexOffset = CheckEven ? 4 : 0; 1768 if (ShuffleKind == 1) // Unary 1769 return isVMerge(N, indexOffset, 0); 1770 else if (ShuffleKind == 2) // swapped 1771 return isVMerge(N, indexOffset, 16); 1772 else 1773 return false; 1774 } 1775 else { 1776 unsigned indexOffset = CheckEven ? 0 : 4; 1777 if (ShuffleKind == 1) // Unary 1778 return isVMerge(N, indexOffset, 0); 1779 else if (ShuffleKind == 0) // Normal 1780 return isVMerge(N, indexOffset, 16); 1781 else 1782 return false; 1783 } 1784 return false; 1785 } 1786 1787 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1788 /// amount, otherwise return -1. 1789 /// The ShuffleKind distinguishes between big-endian operations with two 1790 /// different inputs (0), either-endian operations with two identical inputs 1791 /// (1), and little-endian operations with two different inputs (2). For the 1792 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1793 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1794 SelectionDAG &DAG) { 1795 if (N->getValueType(0) != MVT::v16i8) 1796 return -1; 1797 1798 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1799 1800 // Find the first non-undef value in the shuffle mask. 1801 unsigned i; 1802 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1803 /*search*/; 1804 1805 if (i == 16) return -1; // all undef. 1806 1807 // Otherwise, check to see if the rest of the elements are consecutively 1808 // numbered from this value. 1809 unsigned ShiftAmt = SVOp->getMaskElt(i); 1810 if (ShiftAmt < i) return -1; 1811 1812 ShiftAmt -= i; 1813 bool isLE = DAG.getDataLayout().isLittleEndian(); 1814 1815 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1816 // Check the rest of the elements to see if they are consecutive. 1817 for (++i; i != 16; ++i) 1818 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1819 return -1; 1820 } else if (ShuffleKind == 1) { 1821 // Check the rest of the elements to see if they are consecutive. 1822 for (++i; i != 16; ++i) 1823 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1824 return -1; 1825 } else 1826 return -1; 1827 1828 if (isLE) 1829 ShiftAmt = 16 - ShiftAmt; 1830 1831 return ShiftAmt; 1832 } 1833 1834 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1835 /// specifies a splat of a single element that is suitable for input to 1836 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1837 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1838 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1839 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1840 1841 // The consecutive indices need to specify an element, not part of two 1842 // different elements. So abandon ship early if this isn't the case. 1843 if (N->getMaskElt(0) % EltSize != 0) 1844 return false; 1845 1846 // This is a splat operation if each element of the permute is the same, and 1847 // if the value doesn't reference the second vector. 1848 unsigned ElementBase = N->getMaskElt(0); 1849 1850 // FIXME: Handle UNDEF elements too! 1851 if (ElementBase >= 16) 1852 return false; 1853 1854 // Check that the indices are consecutive, in the case of a multi-byte element 1855 // splatted with a v16i8 mask. 1856 for (unsigned i = 1; i != EltSize; ++i) 1857 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1858 return false; 1859 1860 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1861 if (N->getMaskElt(i) < 0) continue; 1862 for (unsigned j = 0; j != EltSize; ++j) 1863 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1864 return false; 1865 } 1866 return true; 1867 } 1868 1869 /// Check that the mask is shuffling N byte elements. Within each N byte 1870 /// element of the mask, the indices could be either in increasing or 1871 /// decreasing order as long as they are consecutive. 1872 /// \param[in] N the shuffle vector SD Node to analyze 1873 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1874 /// Word/DoubleWord/QuadWord). 1875 /// \param[in] StepLen the delta indices number among the N byte element, if 1876 /// the mask is in increasing/decreasing order then it is 1/-1. 1877 /// \return true iff the mask is shuffling N byte elements. 1878 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1879 int StepLen) { 1880 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1881 "Unexpected element width."); 1882 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1883 1884 unsigned NumOfElem = 16 / Width; 1885 unsigned MaskVal[16]; // Width is never greater than 16 1886 for (unsigned i = 0; i < NumOfElem; ++i) { 1887 MaskVal[0] = N->getMaskElt(i * Width); 1888 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1889 return false; 1890 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1891 return false; 1892 } 1893 1894 for (unsigned int j = 1; j < Width; ++j) { 1895 MaskVal[j] = N->getMaskElt(i * Width + j); 1896 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1897 return false; 1898 } 1899 } 1900 } 1901 1902 return true; 1903 } 1904 1905 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1906 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1907 if (!isNByteElemShuffleMask(N, 4, 1)) 1908 return false; 1909 1910 // Now we look at mask elements 0,4,8,12 1911 unsigned M0 = N->getMaskElt(0) / 4; 1912 unsigned M1 = N->getMaskElt(4) / 4; 1913 unsigned M2 = N->getMaskElt(8) / 4; 1914 unsigned M3 = N->getMaskElt(12) / 4; 1915 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1916 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1917 1918 // Below, let H and L be arbitrary elements of the shuffle mask 1919 // where H is in the range [4,7] and L is in the range [0,3]. 1920 // H, 1, 2, 3 or L, 5, 6, 7 1921 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1922 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1923 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1924 InsertAtByte = IsLE ? 12 : 0; 1925 Swap = M0 < 4; 1926 return true; 1927 } 1928 // 0, H, 2, 3 or 4, L, 6, 7 1929 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1930 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1931 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1932 InsertAtByte = IsLE ? 8 : 4; 1933 Swap = M1 < 4; 1934 return true; 1935 } 1936 // 0, 1, H, 3 or 4, 5, L, 7 1937 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1938 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1939 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1940 InsertAtByte = IsLE ? 4 : 8; 1941 Swap = M2 < 4; 1942 return true; 1943 } 1944 // 0, 1, 2, H or 4, 5, 6, L 1945 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1946 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1947 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1948 InsertAtByte = IsLE ? 0 : 12; 1949 Swap = M3 < 4; 1950 return true; 1951 } 1952 1953 // If both vector operands for the shuffle are the same vector, the mask will 1954 // contain only elements from the first one and the second one will be undef. 1955 if (N->getOperand(1).isUndef()) { 1956 ShiftElts = 0; 1957 Swap = true; 1958 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1959 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1960 InsertAtByte = IsLE ? 12 : 0; 1961 return true; 1962 } 1963 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1964 InsertAtByte = IsLE ? 8 : 4; 1965 return true; 1966 } 1967 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1968 InsertAtByte = IsLE ? 4 : 8; 1969 return true; 1970 } 1971 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1972 InsertAtByte = IsLE ? 0 : 12; 1973 return true; 1974 } 1975 } 1976 1977 return false; 1978 } 1979 1980 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1981 bool &Swap, bool IsLE) { 1982 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1983 // Ensure each byte index of the word is consecutive. 1984 if (!isNByteElemShuffleMask(N, 4, 1)) 1985 return false; 1986 1987 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1988 unsigned M0 = N->getMaskElt(0) / 4; 1989 unsigned M1 = N->getMaskElt(4) / 4; 1990 unsigned M2 = N->getMaskElt(8) / 4; 1991 unsigned M3 = N->getMaskElt(12) / 4; 1992 1993 // If both vector operands for the shuffle are the same vector, the mask will 1994 // contain only elements from the first one and the second one will be undef. 1995 if (N->getOperand(1).isUndef()) { 1996 assert(M0 < 4 && "Indexing into an undef vector?"); 1997 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1998 return false; 1999 2000 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2001 Swap = false; 2002 return true; 2003 } 2004 2005 // Ensure each word index of the ShuffleVector Mask is consecutive. 2006 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2007 return false; 2008 2009 if (IsLE) { 2010 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2011 // Input vectors don't need to be swapped if the leading element 2012 // of the result is one of the 3 left elements of the second vector 2013 // (or if there is no shift to be done at all). 2014 Swap = false; 2015 ShiftElts = (8 - M0) % 8; 2016 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2017 // Input vectors need to be swapped if the leading element 2018 // of the result is one of the 3 left elements of the first vector 2019 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2020 Swap = true; 2021 ShiftElts = (4 - M0) % 4; 2022 } 2023 2024 return true; 2025 } else { // BE 2026 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2027 // Input vectors don't need to be swapped if the leading element 2028 // of the result is one of the 4 elements of the first vector. 2029 Swap = false; 2030 ShiftElts = M0; 2031 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2032 // Input vectors need to be swapped if the leading element 2033 // of the result is one of the 4 elements of the right vector. 2034 Swap = true; 2035 ShiftElts = M0 - 4; 2036 } 2037 2038 return true; 2039 } 2040 } 2041 2042 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2043 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2044 2045 if (!isNByteElemShuffleMask(N, Width, -1)) 2046 return false; 2047 2048 for (int i = 0; i < 16; i += Width) 2049 if (N->getMaskElt(i) != i + Width - 1) 2050 return false; 2051 2052 return true; 2053 } 2054 2055 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2056 return isXXBRShuffleMaskHelper(N, 2); 2057 } 2058 2059 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2060 return isXXBRShuffleMaskHelper(N, 4); 2061 } 2062 2063 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2064 return isXXBRShuffleMaskHelper(N, 8); 2065 } 2066 2067 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2068 return isXXBRShuffleMaskHelper(N, 16); 2069 } 2070 2071 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2072 /// if the inputs to the instruction should be swapped and set \p DM to the 2073 /// value for the immediate. 2074 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2075 /// AND element 0 of the result comes from the first input (LE) or second input 2076 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2077 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2078 /// mask. 2079 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2080 bool &Swap, bool IsLE) { 2081 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2082 2083 // Ensure each byte index of the double word is consecutive. 2084 if (!isNByteElemShuffleMask(N, 8, 1)) 2085 return false; 2086 2087 unsigned M0 = N->getMaskElt(0) / 8; 2088 unsigned M1 = N->getMaskElt(8) / 8; 2089 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2090 2091 // If both vector operands for the shuffle are the same vector, the mask will 2092 // contain only elements from the first one and the second one will be undef. 2093 if (N->getOperand(1).isUndef()) { 2094 if ((M0 | M1) < 2) { 2095 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2096 Swap = false; 2097 return true; 2098 } else 2099 return false; 2100 } 2101 2102 if (IsLE) { 2103 if (M0 > 1 && M1 < 2) { 2104 Swap = false; 2105 } else if (M0 < 2 && M1 > 1) { 2106 M0 = (M0 + 2) % 4; 2107 M1 = (M1 + 2) % 4; 2108 Swap = true; 2109 } else 2110 return false; 2111 2112 // Note: if control flow comes here that means Swap is already set above 2113 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2114 return true; 2115 } else { // BE 2116 if (M0 < 2 && M1 > 1) { 2117 Swap = false; 2118 } else if (M0 > 1 && M1 < 2) { 2119 M0 = (M0 + 2) % 4; 2120 M1 = (M1 + 2) % 4; 2121 Swap = true; 2122 } else 2123 return false; 2124 2125 // Note: if control flow comes here that means Swap is already set above 2126 DM = (M0 << 1) + (M1 & 1); 2127 return true; 2128 } 2129 } 2130 2131 2132 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2133 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2134 /// elements are counted from the left of the vector register). 2135 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2136 SelectionDAG &DAG) { 2137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2138 assert(isSplatShuffleMask(SVOp, EltSize)); 2139 if (DAG.getDataLayout().isLittleEndian()) 2140 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2141 else 2142 return SVOp->getMaskElt(0) / EltSize; 2143 } 2144 2145 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2146 /// by using a vspltis[bhw] instruction of the specified element size, return 2147 /// the constant being splatted. The ByteSize field indicates the number of 2148 /// bytes of each element [124] -> [bhw]. 2149 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2150 SDValue OpVal(nullptr, 0); 2151 2152 // If ByteSize of the splat is bigger than the element size of the 2153 // build_vector, then we have a case where we are checking for a splat where 2154 // multiple elements of the buildvector are folded together into a single 2155 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2156 unsigned EltSize = 16/N->getNumOperands(); 2157 if (EltSize < ByteSize) { 2158 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2159 SDValue UniquedVals[4]; 2160 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2161 2162 // See if all of the elements in the buildvector agree across. 2163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2164 if (N->getOperand(i).isUndef()) continue; 2165 // If the element isn't a constant, bail fully out. 2166 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2167 2168 if (!UniquedVals[i&(Multiple-1)].getNode()) 2169 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2170 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2171 return SDValue(); // no match. 2172 } 2173 2174 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2175 // either constant or undef values that are identical for each chunk. See 2176 // if these chunks can form into a larger vspltis*. 2177 2178 // Check to see if all of the leading entries are either 0 or -1. If 2179 // neither, then this won't fit into the immediate field. 2180 bool LeadingZero = true; 2181 bool LeadingOnes = true; 2182 for (unsigned i = 0; i != Multiple-1; ++i) { 2183 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2184 2185 LeadingZero &= isNullConstant(UniquedVals[i]); 2186 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2187 } 2188 // Finally, check the least significant entry. 2189 if (LeadingZero) { 2190 if (!UniquedVals[Multiple-1].getNode()) 2191 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2192 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2193 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2194 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2195 } 2196 if (LeadingOnes) { 2197 if (!UniquedVals[Multiple-1].getNode()) 2198 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2199 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2200 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2201 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2202 } 2203 2204 return SDValue(); 2205 } 2206 2207 // Check to see if this buildvec has a single non-undef value in its elements. 2208 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2209 if (N->getOperand(i).isUndef()) continue; 2210 if (!OpVal.getNode()) 2211 OpVal = N->getOperand(i); 2212 else if (OpVal != N->getOperand(i)) 2213 return SDValue(); 2214 } 2215 2216 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2217 2218 unsigned ValSizeInBytes = EltSize; 2219 uint64_t Value = 0; 2220 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2221 Value = CN->getZExtValue(); 2222 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2223 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2224 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2225 } 2226 2227 // If the splat value is larger than the element value, then we can never do 2228 // this splat. The only case that we could fit the replicated bits into our 2229 // immediate field for would be zero, and we prefer to use vxor for it. 2230 if (ValSizeInBytes < ByteSize) return SDValue(); 2231 2232 // If the element value is larger than the splat value, check if it consists 2233 // of a repeated bit pattern of size ByteSize. 2234 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2235 return SDValue(); 2236 2237 // Properly sign extend the value. 2238 int MaskVal = SignExtend32(Value, ByteSize * 8); 2239 2240 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2241 if (MaskVal == 0) return SDValue(); 2242 2243 // Finally, if this value fits in a 5 bit sext field, return it 2244 if (SignExtend32<5>(MaskVal) == MaskVal) 2245 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2246 return SDValue(); 2247 } 2248 2249 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2250 /// amount, otherwise return -1. 2251 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2252 EVT VT = N->getValueType(0); 2253 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2254 return -1; 2255 2256 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2257 2258 // Find the first non-undef value in the shuffle mask. 2259 unsigned i; 2260 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2261 /*search*/; 2262 2263 if (i == 4) return -1; // all undef. 2264 2265 // Otherwise, check to see if the rest of the elements are consecutively 2266 // numbered from this value. 2267 unsigned ShiftAmt = SVOp->getMaskElt(i); 2268 if (ShiftAmt < i) return -1; 2269 ShiftAmt -= i; 2270 2271 // Check the rest of the elements to see if they are consecutive. 2272 for (++i; i != 4; ++i) 2273 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2274 return -1; 2275 2276 return ShiftAmt; 2277 } 2278 2279 //===----------------------------------------------------------------------===// 2280 // Addressing Mode Selection 2281 //===----------------------------------------------------------------------===// 2282 2283 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2284 /// or 64-bit immediate, and if the value can be accurately represented as a 2285 /// sign extension from a 16-bit value. If so, this returns true and the 2286 /// immediate. 2287 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2288 if (!isa<ConstantSDNode>(N)) 2289 return false; 2290 2291 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2292 if (N->getValueType(0) == MVT::i32) 2293 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2294 else 2295 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2296 } 2297 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2298 return isIntS16Immediate(Op.getNode(), Imm); 2299 } 2300 2301 2302 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2303 /// be represented as an indexed [r+r] operation. 2304 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2305 SDValue &Index, 2306 SelectionDAG &DAG) const { 2307 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2308 UI != E; ++UI) { 2309 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2310 if (Memop->getMemoryVT() == MVT::f64) { 2311 Base = N.getOperand(0); 2312 Index = N.getOperand(1); 2313 return true; 2314 } 2315 } 2316 } 2317 return false; 2318 } 2319 2320 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2321 /// can be represented as an indexed [r+r] operation. Returns false if it 2322 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2323 /// non-zero and N can be represented by a base register plus a signed 16-bit 2324 /// displacement, make a more precise judgement by checking (displacement % \p 2325 /// EncodingAlignment). 2326 bool PPCTargetLowering::SelectAddressRegReg( 2327 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2328 MaybeAlign EncodingAlignment) const { 2329 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2330 // a [pc+imm]. 2331 if (SelectAddressPCRel(N, Base)) 2332 return false; 2333 2334 int16_t Imm = 0; 2335 if (N.getOpcode() == ISD::ADD) { 2336 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2337 // SPE load/store can only handle 8-bit offsets. 2338 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2339 return true; 2340 if (isIntS16Immediate(N.getOperand(1), Imm) && 2341 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2342 return false; // r+i 2343 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2344 return false; // r+i 2345 2346 Base = N.getOperand(0); 2347 Index = N.getOperand(1); 2348 return true; 2349 } else if (N.getOpcode() == ISD::OR) { 2350 if (isIntS16Immediate(N.getOperand(1), Imm) && 2351 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2352 return false; // r+i can fold it if we can. 2353 2354 // If this is an or of disjoint bitfields, we can codegen this as an add 2355 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2356 // disjoint. 2357 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2358 2359 if (LHSKnown.Zero.getBoolValue()) { 2360 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2361 // If all of the bits are known zero on the LHS or RHS, the add won't 2362 // carry. 2363 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2364 Base = N.getOperand(0); 2365 Index = N.getOperand(1); 2366 return true; 2367 } 2368 } 2369 } 2370 2371 return false; 2372 } 2373 2374 // If we happen to be doing an i64 load or store into a stack slot that has 2375 // less than a 4-byte alignment, then the frame-index elimination may need to 2376 // use an indexed load or store instruction (because the offset may not be a 2377 // multiple of 4). The extra register needed to hold the offset comes from the 2378 // register scavenger, and it is possible that the scavenger will need to use 2379 // an emergency spill slot. As a result, we need to make sure that a spill slot 2380 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2381 // stack slot. 2382 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2383 // FIXME: This does not handle the LWA case. 2384 if (VT != MVT::i64) 2385 return; 2386 2387 // NOTE: We'll exclude negative FIs here, which come from argument 2388 // lowering, because there are no known test cases triggering this problem 2389 // using packed structures (or similar). We can remove this exclusion if 2390 // we find such a test case. The reason why this is so test-case driven is 2391 // because this entire 'fixup' is only to prevent crashes (from the 2392 // register scavenger) on not-really-valid inputs. For example, if we have: 2393 // %a = alloca i1 2394 // %b = bitcast i1* %a to i64* 2395 // store i64* a, i64 b 2396 // then the store should really be marked as 'align 1', but is not. If it 2397 // were marked as 'align 1' then the indexed form would have been 2398 // instruction-selected initially, and the problem this 'fixup' is preventing 2399 // won't happen regardless. 2400 if (FrameIdx < 0) 2401 return; 2402 2403 MachineFunction &MF = DAG.getMachineFunction(); 2404 MachineFrameInfo &MFI = MF.getFrameInfo(); 2405 2406 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2407 return; 2408 2409 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2410 FuncInfo->setHasNonRISpills(); 2411 } 2412 2413 /// Returns true if the address N can be represented by a base register plus 2414 /// a signed 16-bit displacement [r+imm], and if it is not better 2415 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2416 /// displacements that are multiples of that value. 2417 bool PPCTargetLowering::SelectAddressRegImm( 2418 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2419 MaybeAlign EncodingAlignment) const { 2420 // FIXME dl should come from parent load or store, not from address 2421 SDLoc dl(N); 2422 2423 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2424 // a [pc+imm]. 2425 if (SelectAddressPCRel(N, Base)) 2426 return false; 2427 2428 // If this can be more profitably realized as r+r, fail. 2429 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2430 return false; 2431 2432 if (N.getOpcode() == ISD::ADD) { 2433 int16_t imm = 0; 2434 if (isIntS16Immediate(N.getOperand(1), imm) && 2435 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2436 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2437 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2438 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2439 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2440 } else { 2441 Base = N.getOperand(0); 2442 } 2443 return true; // [r+i] 2444 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2445 // Match LOAD (ADD (X, Lo(G))). 2446 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2447 && "Cannot handle constant offsets yet!"); 2448 Disp = N.getOperand(1).getOperand(0); // The global address. 2449 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2450 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2451 Disp.getOpcode() == ISD::TargetConstantPool || 2452 Disp.getOpcode() == ISD::TargetJumpTable); 2453 Base = N.getOperand(0); 2454 return true; // [&g+r] 2455 } 2456 } else if (N.getOpcode() == ISD::OR) { 2457 int16_t imm = 0; 2458 if (isIntS16Immediate(N.getOperand(1), imm) && 2459 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2460 // If this is an or of disjoint bitfields, we can codegen this as an add 2461 // (for better address arithmetic) if the LHS and RHS of the OR are 2462 // provably disjoint. 2463 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2464 2465 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2466 // If all of the bits are known zero on the LHS or RHS, the add won't 2467 // carry. 2468 if (FrameIndexSDNode *FI = 2469 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2470 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2471 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2472 } else { 2473 Base = N.getOperand(0); 2474 } 2475 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2476 return true; 2477 } 2478 } 2479 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2480 // Loading from a constant address. 2481 2482 // If this address fits entirely in a 16-bit sext immediate field, codegen 2483 // this as "d, 0" 2484 int16_t Imm; 2485 if (isIntS16Immediate(CN, Imm) && 2486 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2487 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2488 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2489 CN->getValueType(0)); 2490 return true; 2491 } 2492 2493 // Handle 32-bit sext immediates with LIS + addr mode. 2494 if ((CN->getValueType(0) == MVT::i32 || 2495 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2496 (!EncodingAlignment || 2497 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2498 int Addr = (int)CN->getZExtValue(); 2499 2500 // Otherwise, break this down into an LIS + disp. 2501 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2502 2503 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2504 MVT::i32); 2505 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2506 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2507 return true; 2508 } 2509 } 2510 2511 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2512 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2513 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2514 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2515 } else 2516 Base = N; 2517 return true; // [r+0] 2518 } 2519 2520 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2521 /// represented as an indexed [r+r] operation. 2522 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2523 SDValue &Index, 2524 SelectionDAG &DAG) const { 2525 // Check to see if we can easily represent this as an [r+r] address. This 2526 // will fail if it thinks that the address is more profitably represented as 2527 // reg+imm, e.g. where imm = 0. 2528 if (SelectAddressRegReg(N, Base, Index, DAG)) 2529 return true; 2530 2531 // If the address is the result of an add, we will utilize the fact that the 2532 // address calculation includes an implicit add. However, we can reduce 2533 // register pressure if we do not materialize a constant just for use as the 2534 // index register. We only get rid of the add if it is not an add of a 2535 // value and a 16-bit signed constant and both have a single use. 2536 int16_t imm = 0; 2537 if (N.getOpcode() == ISD::ADD && 2538 (!isIntS16Immediate(N.getOperand(1), imm) || 2539 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2540 Base = N.getOperand(0); 2541 Index = N.getOperand(1); 2542 return true; 2543 } 2544 2545 // Otherwise, do it the hard way, using R0 as the base register. 2546 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2547 N.getValueType()); 2548 Index = N; 2549 return true; 2550 } 2551 2552 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2553 Ty *PCRelCand = dyn_cast<Ty>(N); 2554 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2555 } 2556 2557 /// Returns true if this address is a PC Relative address. 2558 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2559 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2560 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2561 // This is a materialize PC Relative node. Always select this as PC Relative. 2562 Base = N; 2563 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2564 return true; 2565 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2566 isValidPCRelNode<GlobalAddressSDNode>(N) || 2567 isValidPCRelNode<JumpTableSDNode>(N) || 2568 isValidPCRelNode<BlockAddressSDNode>(N)) 2569 return true; 2570 return false; 2571 } 2572 2573 /// Returns true if we should use a direct load into vector instruction 2574 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2575 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2576 2577 // If there are any other uses other than scalar to vector, then we should 2578 // keep it as a scalar load -> direct move pattern to prevent multiple 2579 // loads. 2580 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2581 if (!LD) 2582 return false; 2583 2584 EVT MemVT = LD->getMemoryVT(); 2585 if (!MemVT.isSimple()) 2586 return false; 2587 switch(MemVT.getSimpleVT().SimpleTy) { 2588 case MVT::i64: 2589 break; 2590 case MVT::i32: 2591 if (!ST.hasP8Vector()) 2592 return false; 2593 break; 2594 case MVT::i16: 2595 case MVT::i8: 2596 if (!ST.hasP9Vector()) 2597 return false; 2598 break; 2599 default: 2600 return false; 2601 } 2602 2603 SDValue LoadedVal(N, 0); 2604 if (!LoadedVal.hasOneUse()) 2605 return false; 2606 2607 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2608 UI != UE; ++UI) 2609 if (UI.getUse().get().getResNo() == 0 && 2610 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2611 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2612 return false; 2613 2614 return true; 2615 } 2616 2617 /// getPreIndexedAddressParts - returns true by value, base pointer and 2618 /// offset pointer and addressing mode by reference if the node's address 2619 /// can be legally represented as pre-indexed load / store address. 2620 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2621 SDValue &Offset, 2622 ISD::MemIndexedMode &AM, 2623 SelectionDAG &DAG) const { 2624 if (DisablePPCPreinc) return false; 2625 2626 bool isLoad = true; 2627 SDValue Ptr; 2628 EVT VT; 2629 unsigned Alignment; 2630 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2631 Ptr = LD->getBasePtr(); 2632 VT = LD->getMemoryVT(); 2633 Alignment = LD->getAlignment(); 2634 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2635 Ptr = ST->getBasePtr(); 2636 VT = ST->getMemoryVT(); 2637 Alignment = ST->getAlignment(); 2638 isLoad = false; 2639 } else 2640 return false; 2641 2642 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2643 // instructions because we can fold these into a more efficient instruction 2644 // instead, (such as LXSD). 2645 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2646 return false; 2647 } 2648 2649 // PowerPC doesn't have preinc load/store instructions for vectors 2650 if (VT.isVector()) 2651 return false; 2652 2653 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2654 // Common code will reject creating a pre-inc form if the base pointer 2655 // is a frame index, or if N is a store and the base pointer is either 2656 // the same as or a predecessor of the value being stored. Check for 2657 // those situations here, and try with swapped Base/Offset instead. 2658 bool Swap = false; 2659 2660 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2661 Swap = true; 2662 else if (!isLoad) { 2663 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2664 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2665 Swap = true; 2666 } 2667 2668 if (Swap) 2669 std::swap(Base, Offset); 2670 2671 AM = ISD::PRE_INC; 2672 return true; 2673 } 2674 2675 // LDU/STU can only handle immediates that are a multiple of 4. 2676 if (VT != MVT::i64) { 2677 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2678 return false; 2679 } else { 2680 // LDU/STU need an address with at least 4-byte alignment. 2681 if (Alignment < 4) 2682 return false; 2683 2684 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2685 return false; 2686 } 2687 2688 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2689 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2690 // sext i32 to i64 when addr mode is r+i. 2691 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2692 LD->getExtensionType() == ISD::SEXTLOAD && 2693 isa<ConstantSDNode>(Offset)) 2694 return false; 2695 } 2696 2697 AM = ISD::PRE_INC; 2698 return true; 2699 } 2700 2701 //===----------------------------------------------------------------------===// 2702 // LowerOperation implementation 2703 //===----------------------------------------------------------------------===// 2704 2705 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2706 /// and LoOpFlags to the target MO flags. 2707 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2708 unsigned &HiOpFlags, unsigned &LoOpFlags, 2709 const GlobalValue *GV = nullptr) { 2710 HiOpFlags = PPCII::MO_HA; 2711 LoOpFlags = PPCII::MO_LO; 2712 2713 // Don't use the pic base if not in PIC relocation model. 2714 if (IsPIC) { 2715 HiOpFlags |= PPCII::MO_PIC_FLAG; 2716 LoOpFlags |= PPCII::MO_PIC_FLAG; 2717 } 2718 } 2719 2720 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2721 SelectionDAG &DAG) { 2722 SDLoc DL(HiPart); 2723 EVT PtrVT = HiPart.getValueType(); 2724 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2725 2726 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2727 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2728 2729 // With PIC, the first instruction is actually "GR+hi(&G)". 2730 if (isPIC) 2731 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2732 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2733 2734 // Generate non-pic code that has direct accesses to the constant pool. 2735 // The address of the global is just (hi(&g)+lo(&g)). 2736 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2737 } 2738 2739 static void setUsesTOCBasePtr(MachineFunction &MF) { 2740 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2741 FuncInfo->setUsesTOCBasePtr(); 2742 } 2743 2744 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2745 setUsesTOCBasePtr(DAG.getMachineFunction()); 2746 } 2747 2748 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2749 SDValue GA) const { 2750 const bool Is64Bit = Subtarget.isPPC64(); 2751 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2752 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2753 : Subtarget.isAIXABI() 2754 ? DAG.getRegister(PPC::R2, VT) 2755 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2756 SDValue Ops[] = { GA, Reg }; 2757 return DAG.getMemIntrinsicNode( 2758 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2759 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2760 MachineMemOperand::MOLoad); 2761 } 2762 2763 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2764 SelectionDAG &DAG) const { 2765 EVT PtrVT = Op.getValueType(); 2766 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2767 const Constant *C = CP->getConstVal(); 2768 2769 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2770 // The actual address of the GlobalValue is stored in the TOC. 2771 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2772 if (Subtarget.isUsingPCRelativeCalls()) { 2773 SDLoc DL(CP); 2774 EVT Ty = getPointerTy(DAG.getDataLayout()); 2775 SDValue ConstPool = DAG.getTargetConstantPool( 2776 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2777 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2778 } 2779 setUsesTOCBasePtr(DAG); 2780 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2781 return getTOCEntry(DAG, SDLoc(CP), GA); 2782 } 2783 2784 unsigned MOHiFlag, MOLoFlag; 2785 bool IsPIC = isPositionIndependent(); 2786 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2787 2788 if (IsPIC && Subtarget.isSVR4ABI()) { 2789 SDValue GA = 2790 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2791 return getTOCEntry(DAG, SDLoc(CP), GA); 2792 } 2793 2794 SDValue CPIHi = 2795 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2796 SDValue CPILo = 2797 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2798 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2799 } 2800 2801 // For 64-bit PowerPC, prefer the more compact relative encodings. 2802 // This trades 32 bits per jump table entry for one or two instructions 2803 // on the jump site. 2804 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2805 if (isJumpTableRelative()) 2806 return MachineJumpTableInfo::EK_LabelDifference32; 2807 2808 return TargetLowering::getJumpTableEncoding(); 2809 } 2810 2811 bool PPCTargetLowering::isJumpTableRelative() const { 2812 if (UseAbsoluteJumpTables) 2813 return false; 2814 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2815 return true; 2816 return TargetLowering::isJumpTableRelative(); 2817 } 2818 2819 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2820 SelectionDAG &DAG) const { 2821 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2822 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2823 2824 switch (getTargetMachine().getCodeModel()) { 2825 case CodeModel::Small: 2826 case CodeModel::Medium: 2827 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2828 default: 2829 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2830 getPointerTy(DAG.getDataLayout())); 2831 } 2832 } 2833 2834 const MCExpr * 2835 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2836 unsigned JTI, 2837 MCContext &Ctx) const { 2838 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2839 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2840 2841 switch (getTargetMachine().getCodeModel()) { 2842 case CodeModel::Small: 2843 case CodeModel::Medium: 2844 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2845 default: 2846 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2847 } 2848 } 2849 2850 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2851 EVT PtrVT = Op.getValueType(); 2852 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2853 2854 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2855 if (Subtarget.isUsingPCRelativeCalls()) { 2856 SDLoc DL(JT); 2857 EVT Ty = getPointerTy(DAG.getDataLayout()); 2858 SDValue GA = 2859 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2860 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2861 return MatAddr; 2862 } 2863 2864 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2865 // The actual address of the GlobalValue is stored in the TOC. 2866 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2867 setUsesTOCBasePtr(DAG); 2868 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2869 return getTOCEntry(DAG, SDLoc(JT), GA); 2870 } 2871 2872 unsigned MOHiFlag, MOLoFlag; 2873 bool IsPIC = isPositionIndependent(); 2874 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2875 2876 if (IsPIC && Subtarget.isSVR4ABI()) { 2877 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2878 PPCII::MO_PIC_FLAG); 2879 return getTOCEntry(DAG, SDLoc(GA), GA); 2880 } 2881 2882 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2883 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2884 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2885 } 2886 2887 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2888 SelectionDAG &DAG) const { 2889 EVT PtrVT = Op.getValueType(); 2890 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2891 const BlockAddress *BA = BASDN->getBlockAddress(); 2892 2893 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2894 if (Subtarget.isUsingPCRelativeCalls()) { 2895 SDLoc DL(BASDN); 2896 EVT Ty = getPointerTy(DAG.getDataLayout()); 2897 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2898 PPCII::MO_PCREL_FLAG); 2899 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2900 return MatAddr; 2901 } 2902 2903 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2904 // The actual BlockAddress is stored in the TOC. 2905 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2906 setUsesTOCBasePtr(DAG); 2907 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2908 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2909 } 2910 2911 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2912 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2913 return getTOCEntry( 2914 DAG, SDLoc(BASDN), 2915 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2916 2917 unsigned MOHiFlag, MOLoFlag; 2918 bool IsPIC = isPositionIndependent(); 2919 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2920 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2921 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2922 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2923 } 2924 2925 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2926 SelectionDAG &DAG) const { 2927 // FIXME: TLS addresses currently use medium model code sequences, 2928 // which is the most useful form. Eventually support for small and 2929 // large models could be added if users need it, at the cost of 2930 // additional complexity. 2931 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 2932 report_fatal_error("Thread local storage is not supported with pc-relative" 2933 " addressing - please compile with -mno-pcrel"); 2934 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2935 if (DAG.getTarget().useEmulatedTLS()) 2936 return LowerToTLSEmulatedModel(GA, DAG); 2937 2938 SDLoc dl(GA); 2939 const GlobalValue *GV = GA->getGlobal(); 2940 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2941 bool is64bit = Subtarget.isPPC64(); 2942 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2943 PICLevel::Level picLevel = M->getPICLevel(); 2944 2945 const TargetMachine &TM = getTargetMachine(); 2946 TLSModel::Model Model = TM.getTLSModel(GV); 2947 2948 if (Model == TLSModel::LocalExec) { 2949 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2950 PPCII::MO_TPREL_HA); 2951 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2952 PPCII::MO_TPREL_LO); 2953 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2954 : DAG.getRegister(PPC::R2, MVT::i32); 2955 2956 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2957 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2958 } 2959 2960 if (Model == TLSModel::InitialExec) { 2961 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2962 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2963 PPCII::MO_TLS); 2964 SDValue GOTPtr; 2965 if (is64bit) { 2966 setUsesTOCBasePtr(DAG); 2967 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2968 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2969 PtrVT, GOTReg, TGA); 2970 } else { 2971 if (!TM.isPositionIndependent()) 2972 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2973 else if (picLevel == PICLevel::SmallPIC) 2974 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2975 else 2976 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2977 } 2978 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2979 PtrVT, TGA, GOTPtr); 2980 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2981 } 2982 2983 if (Model == TLSModel::GeneralDynamic) { 2984 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2985 SDValue GOTPtr; 2986 if (is64bit) { 2987 setUsesTOCBasePtr(DAG); 2988 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2989 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2990 GOTReg, TGA); 2991 } else { 2992 if (picLevel == PICLevel::SmallPIC) 2993 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2994 else 2995 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2996 } 2997 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2998 GOTPtr, TGA, TGA); 2999 } 3000 3001 if (Model == TLSModel::LocalDynamic) { 3002 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3003 SDValue GOTPtr; 3004 if (is64bit) { 3005 setUsesTOCBasePtr(DAG); 3006 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3007 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3008 GOTReg, TGA); 3009 } else { 3010 if (picLevel == PICLevel::SmallPIC) 3011 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3012 else 3013 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3014 } 3015 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3016 PtrVT, GOTPtr, TGA, TGA); 3017 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3018 PtrVT, TLSAddr, TGA); 3019 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3020 } 3021 3022 llvm_unreachable("Unknown TLS model!"); 3023 } 3024 3025 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3026 SelectionDAG &DAG) const { 3027 EVT PtrVT = Op.getValueType(); 3028 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3029 SDLoc DL(GSDN); 3030 const GlobalValue *GV = GSDN->getGlobal(); 3031 3032 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3033 // The actual address of the GlobalValue is stored in the TOC. 3034 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3035 if (Subtarget.isUsingPCRelativeCalls()) { 3036 EVT Ty = getPointerTy(DAG.getDataLayout()); 3037 if (isAccessedAsGotIndirect(Op)) { 3038 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3039 PPCII::MO_PCREL_FLAG | 3040 PPCII::MO_GOT_FLAG); 3041 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3042 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3043 MachinePointerInfo()); 3044 return Load; 3045 } else { 3046 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3047 PPCII::MO_PCREL_FLAG); 3048 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3049 } 3050 } 3051 setUsesTOCBasePtr(DAG); 3052 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3053 return getTOCEntry(DAG, DL, GA); 3054 } 3055 3056 unsigned MOHiFlag, MOLoFlag; 3057 bool IsPIC = isPositionIndependent(); 3058 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3059 3060 if (IsPIC && Subtarget.isSVR4ABI()) { 3061 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3062 GSDN->getOffset(), 3063 PPCII::MO_PIC_FLAG); 3064 return getTOCEntry(DAG, DL, GA); 3065 } 3066 3067 SDValue GAHi = 3068 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3069 SDValue GALo = 3070 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3071 3072 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3073 } 3074 3075 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3076 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3077 SDLoc dl(Op); 3078 3079 if (Op.getValueType() == MVT::v2i64) { 3080 // When the operands themselves are v2i64 values, we need to do something 3081 // special because VSX has no underlying comparison operations for these. 3082 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3083 // Equality can be handled by casting to the legal type for Altivec 3084 // comparisons, everything else needs to be expanded. 3085 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3086 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3087 DAG.getSetCC(dl, MVT::v4i32, 3088 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3089 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3090 CC)); 3091 } 3092 3093 return SDValue(); 3094 } 3095 3096 // We handle most of these in the usual way. 3097 return Op; 3098 } 3099 3100 // If we're comparing for equality to zero, expose the fact that this is 3101 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3102 // fold the new nodes. 3103 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3104 return V; 3105 3106 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3107 // Leave comparisons against 0 and -1 alone for now, since they're usually 3108 // optimized. FIXME: revisit this when we can custom lower all setcc 3109 // optimizations. 3110 if (C->isAllOnesValue() || C->isNullValue()) 3111 return SDValue(); 3112 } 3113 3114 // If we have an integer seteq/setne, turn it into a compare against zero 3115 // by xor'ing the rhs with the lhs, which is faster than setting a 3116 // condition register, reading it back out, and masking the correct bit. The 3117 // normal approach here uses sub to do this instead of xor. Using xor exposes 3118 // the result to other bit-twiddling opportunities. 3119 EVT LHSVT = Op.getOperand(0).getValueType(); 3120 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3121 EVT VT = Op.getValueType(); 3122 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3123 Op.getOperand(1)); 3124 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3125 } 3126 return SDValue(); 3127 } 3128 3129 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3130 SDNode *Node = Op.getNode(); 3131 EVT VT = Node->getValueType(0); 3132 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3133 SDValue InChain = Node->getOperand(0); 3134 SDValue VAListPtr = Node->getOperand(1); 3135 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3136 SDLoc dl(Node); 3137 3138 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3139 3140 // gpr_index 3141 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3142 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3143 InChain = GprIndex.getValue(1); 3144 3145 if (VT == MVT::i64) { 3146 // Check if GprIndex is even 3147 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3148 DAG.getConstant(1, dl, MVT::i32)); 3149 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3150 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3151 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3152 DAG.getConstant(1, dl, MVT::i32)); 3153 // Align GprIndex to be even if it isn't 3154 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3155 GprIndex); 3156 } 3157 3158 // fpr index is 1 byte after gpr 3159 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3160 DAG.getConstant(1, dl, MVT::i32)); 3161 3162 // fpr 3163 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3164 FprPtr, MachinePointerInfo(SV), MVT::i8); 3165 InChain = FprIndex.getValue(1); 3166 3167 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3168 DAG.getConstant(8, dl, MVT::i32)); 3169 3170 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3171 DAG.getConstant(4, dl, MVT::i32)); 3172 3173 // areas 3174 SDValue OverflowArea = 3175 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3176 InChain = OverflowArea.getValue(1); 3177 3178 SDValue RegSaveArea = 3179 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3180 InChain = RegSaveArea.getValue(1); 3181 3182 // select overflow_area if index > 8 3183 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3184 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3185 3186 // adjustment constant gpr_index * 4/8 3187 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3188 VT.isInteger() ? GprIndex : FprIndex, 3189 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3190 MVT::i32)); 3191 3192 // OurReg = RegSaveArea + RegConstant 3193 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3194 RegConstant); 3195 3196 // Floating types are 32 bytes into RegSaveArea 3197 if (VT.isFloatingPoint()) 3198 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3199 DAG.getConstant(32, dl, MVT::i32)); 3200 3201 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3202 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3203 VT.isInteger() ? GprIndex : FprIndex, 3204 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3205 MVT::i32)); 3206 3207 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3208 VT.isInteger() ? VAListPtr : FprPtr, 3209 MachinePointerInfo(SV), MVT::i8); 3210 3211 // determine if we should load from reg_save_area or overflow_area 3212 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3213 3214 // increase overflow_area by 4/8 if gpr/fpr > 8 3215 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3216 DAG.getConstant(VT.isInteger() ? 4 : 8, 3217 dl, MVT::i32)); 3218 3219 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3220 OverflowAreaPlusN); 3221 3222 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3223 MachinePointerInfo(), MVT::i32); 3224 3225 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3226 } 3227 3228 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3229 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3230 3231 // We have to copy the entire va_list struct: 3232 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3233 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3234 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3235 false, true, false, MachinePointerInfo(), 3236 MachinePointerInfo()); 3237 } 3238 3239 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3240 SelectionDAG &DAG) const { 3241 if (Subtarget.isAIXABI()) 3242 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3243 3244 return Op.getOperand(0); 3245 } 3246 3247 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3248 SelectionDAG &DAG) const { 3249 if (Subtarget.isAIXABI()) 3250 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3251 3252 SDValue Chain = Op.getOperand(0); 3253 SDValue Trmp = Op.getOperand(1); // trampoline 3254 SDValue FPtr = Op.getOperand(2); // nested function 3255 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3256 SDLoc dl(Op); 3257 3258 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3259 bool isPPC64 = (PtrVT == MVT::i64); 3260 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3261 3262 TargetLowering::ArgListTy Args; 3263 TargetLowering::ArgListEntry Entry; 3264 3265 Entry.Ty = IntPtrTy; 3266 Entry.Node = Trmp; Args.push_back(Entry); 3267 3268 // TrampSize == (isPPC64 ? 48 : 40); 3269 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3270 isPPC64 ? MVT::i64 : MVT::i32); 3271 Args.push_back(Entry); 3272 3273 Entry.Node = FPtr; Args.push_back(Entry); 3274 Entry.Node = Nest; Args.push_back(Entry); 3275 3276 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3277 TargetLowering::CallLoweringInfo CLI(DAG); 3278 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3279 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3280 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3281 3282 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3283 return CallResult.second; 3284 } 3285 3286 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3287 MachineFunction &MF = DAG.getMachineFunction(); 3288 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3289 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3290 3291 SDLoc dl(Op); 3292 3293 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3294 // vastart just stores the address of the VarArgsFrameIndex slot into the 3295 // memory location argument. 3296 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3297 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3298 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3299 MachinePointerInfo(SV)); 3300 } 3301 3302 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3303 // We suppose the given va_list is already allocated. 3304 // 3305 // typedef struct { 3306 // char gpr; /* index into the array of 8 GPRs 3307 // * stored in the register save area 3308 // * gpr=0 corresponds to r3, 3309 // * gpr=1 to r4, etc. 3310 // */ 3311 // char fpr; /* index into the array of 8 FPRs 3312 // * stored in the register save area 3313 // * fpr=0 corresponds to f1, 3314 // * fpr=1 to f2, etc. 3315 // */ 3316 // char *overflow_arg_area; 3317 // /* location on stack that holds 3318 // * the next overflow argument 3319 // */ 3320 // char *reg_save_area; 3321 // /* where r3:r10 and f1:f8 (if saved) 3322 // * are stored 3323 // */ 3324 // } va_list[1]; 3325 3326 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3327 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3328 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3329 PtrVT); 3330 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3331 PtrVT); 3332 3333 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3334 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3335 3336 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3337 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3338 3339 uint64_t FPROffset = 1; 3340 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3341 3342 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3343 3344 // Store first byte : number of int regs 3345 SDValue firstStore = 3346 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3347 MachinePointerInfo(SV), MVT::i8); 3348 uint64_t nextOffset = FPROffset; 3349 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3350 ConstFPROffset); 3351 3352 // Store second byte : number of float regs 3353 SDValue secondStore = 3354 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3355 MachinePointerInfo(SV, nextOffset), MVT::i8); 3356 nextOffset += StackOffset; 3357 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3358 3359 // Store second word : arguments given on stack 3360 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3361 MachinePointerInfo(SV, nextOffset)); 3362 nextOffset += FrameOffset; 3363 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3364 3365 // Store third word : arguments given in registers 3366 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3367 MachinePointerInfo(SV, nextOffset)); 3368 } 3369 3370 /// FPR - The set of FP registers that should be allocated for arguments 3371 /// on Darwin and AIX. 3372 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3373 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3374 PPC::F11, PPC::F12, PPC::F13}; 3375 3376 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3377 /// the stack. 3378 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3379 unsigned PtrByteSize) { 3380 unsigned ArgSize = ArgVT.getStoreSize(); 3381 if (Flags.isByVal()) 3382 ArgSize = Flags.getByValSize(); 3383 3384 // Round up to multiples of the pointer size, except for array members, 3385 // which are always packed. 3386 if (!Flags.isInConsecutiveRegs()) 3387 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3388 3389 return ArgSize; 3390 } 3391 3392 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3393 /// on the stack. 3394 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3395 ISD::ArgFlagsTy Flags, 3396 unsigned PtrByteSize) { 3397 Align Alignment(PtrByteSize); 3398 3399 // Altivec parameters are padded to a 16 byte boundary. 3400 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3401 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3402 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3403 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3404 Alignment = Align(16); 3405 3406 // ByVal parameters are aligned as requested. 3407 if (Flags.isByVal()) { 3408 auto BVAlign = Flags.getNonZeroByValAlign(); 3409 if (BVAlign > PtrByteSize) { 3410 if (BVAlign.value() % PtrByteSize != 0) 3411 llvm_unreachable( 3412 "ByVal alignment is not a multiple of the pointer size"); 3413 3414 Alignment = BVAlign; 3415 } 3416 } 3417 3418 // Array members are always packed to their original alignment. 3419 if (Flags.isInConsecutiveRegs()) { 3420 // If the array member was split into multiple registers, the first 3421 // needs to be aligned to the size of the full type. (Except for 3422 // ppcf128, which is only aligned as its f64 components.) 3423 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3424 Alignment = Align(OrigVT.getStoreSize()); 3425 else 3426 Alignment = Align(ArgVT.getStoreSize()); 3427 } 3428 3429 return Alignment; 3430 } 3431 3432 /// CalculateStackSlotUsed - Return whether this argument will use its 3433 /// stack slot (instead of being passed in registers). ArgOffset, 3434 /// AvailableFPRs, and AvailableVRs must hold the current argument 3435 /// position, and will be updated to account for this argument. 3436 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3437 unsigned PtrByteSize, unsigned LinkageSize, 3438 unsigned ParamAreaSize, unsigned &ArgOffset, 3439 unsigned &AvailableFPRs, 3440 unsigned &AvailableVRs) { 3441 bool UseMemory = false; 3442 3443 // Respect alignment of argument on the stack. 3444 Align Alignment = 3445 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3446 ArgOffset = alignTo(ArgOffset, Alignment); 3447 // If there's no space left in the argument save area, we must 3448 // use memory (this check also catches zero-sized arguments). 3449 if (ArgOffset >= LinkageSize + ParamAreaSize) 3450 UseMemory = true; 3451 3452 // Allocate argument on the stack. 3453 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3454 if (Flags.isInConsecutiveRegsLast()) 3455 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3456 // If we overran the argument save area, we must use memory 3457 // (this check catches arguments passed partially in memory) 3458 if (ArgOffset > LinkageSize + ParamAreaSize) 3459 UseMemory = true; 3460 3461 // However, if the argument is actually passed in an FPR or a VR, 3462 // we don't use memory after all. 3463 if (!Flags.isByVal()) { 3464 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3465 if (AvailableFPRs > 0) { 3466 --AvailableFPRs; 3467 return false; 3468 } 3469 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3470 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3471 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3472 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3473 if (AvailableVRs > 0) { 3474 --AvailableVRs; 3475 return false; 3476 } 3477 } 3478 3479 return UseMemory; 3480 } 3481 3482 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3483 /// ensure minimum alignment required for target. 3484 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3485 unsigned NumBytes) { 3486 return alignTo(NumBytes, Lowering->getStackAlign()); 3487 } 3488 3489 SDValue PPCTargetLowering::LowerFormalArguments( 3490 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3491 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3492 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3493 if (Subtarget.isAIXABI()) 3494 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3495 InVals); 3496 if (Subtarget.is64BitELFABI()) 3497 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3498 InVals); 3499 if (Subtarget.is32BitELFABI()) 3500 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3501 InVals); 3502 3503 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3504 InVals); 3505 } 3506 3507 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3508 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3509 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3510 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3511 3512 // 32-bit SVR4 ABI Stack Frame Layout: 3513 // +-----------------------------------+ 3514 // +--> | Back chain | 3515 // | +-----------------------------------+ 3516 // | | Floating-point register save area | 3517 // | +-----------------------------------+ 3518 // | | General register save area | 3519 // | +-----------------------------------+ 3520 // | | CR save word | 3521 // | +-----------------------------------+ 3522 // | | VRSAVE save word | 3523 // | +-----------------------------------+ 3524 // | | Alignment padding | 3525 // | +-----------------------------------+ 3526 // | | Vector register save area | 3527 // | +-----------------------------------+ 3528 // | | Local variable space | 3529 // | +-----------------------------------+ 3530 // | | Parameter list area | 3531 // | +-----------------------------------+ 3532 // | | LR save word | 3533 // | +-----------------------------------+ 3534 // SP--> +--- | Back chain | 3535 // +-----------------------------------+ 3536 // 3537 // Specifications: 3538 // System V Application Binary Interface PowerPC Processor Supplement 3539 // AltiVec Technology Programming Interface Manual 3540 3541 MachineFunction &MF = DAG.getMachineFunction(); 3542 MachineFrameInfo &MFI = MF.getFrameInfo(); 3543 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3544 3545 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3546 // Potential tail calls could cause overwriting of argument stack slots. 3547 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3548 (CallConv == CallingConv::Fast)); 3549 const Align PtrAlign(4); 3550 3551 // Assign locations to all of the incoming arguments. 3552 SmallVector<CCValAssign, 16> ArgLocs; 3553 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3554 *DAG.getContext()); 3555 3556 // Reserve space for the linkage area on the stack. 3557 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3558 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3559 if (useSoftFloat()) 3560 CCInfo.PreAnalyzeFormalArguments(Ins); 3561 3562 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3563 CCInfo.clearWasPPCF128(); 3564 3565 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3566 CCValAssign &VA = ArgLocs[i]; 3567 3568 // Arguments stored in registers. 3569 if (VA.isRegLoc()) { 3570 const TargetRegisterClass *RC; 3571 EVT ValVT = VA.getValVT(); 3572 3573 switch (ValVT.getSimpleVT().SimpleTy) { 3574 default: 3575 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3576 case MVT::i1: 3577 case MVT::i32: 3578 RC = &PPC::GPRCRegClass; 3579 break; 3580 case MVT::f32: 3581 if (Subtarget.hasP8Vector()) 3582 RC = &PPC::VSSRCRegClass; 3583 else if (Subtarget.hasSPE()) 3584 RC = &PPC::GPRCRegClass; 3585 else 3586 RC = &PPC::F4RCRegClass; 3587 break; 3588 case MVT::f64: 3589 if (Subtarget.hasVSX()) 3590 RC = &PPC::VSFRCRegClass; 3591 else if (Subtarget.hasSPE()) 3592 // SPE passes doubles in GPR pairs. 3593 RC = &PPC::GPRCRegClass; 3594 else 3595 RC = &PPC::F8RCRegClass; 3596 break; 3597 case MVT::v16i8: 3598 case MVT::v8i16: 3599 case MVT::v4i32: 3600 RC = &PPC::VRRCRegClass; 3601 break; 3602 case MVT::v4f32: 3603 RC = &PPC::VRRCRegClass; 3604 break; 3605 case MVT::v2f64: 3606 case MVT::v2i64: 3607 RC = &PPC::VRRCRegClass; 3608 break; 3609 } 3610 3611 SDValue ArgValue; 3612 // Transform the arguments stored in physical registers into 3613 // virtual ones. 3614 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3615 assert(i + 1 < e && "No second half of double precision argument"); 3616 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3617 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3618 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3619 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3620 if (!Subtarget.isLittleEndian()) 3621 std::swap (ArgValueLo, ArgValueHi); 3622 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3623 ArgValueHi); 3624 } else { 3625 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3626 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3627 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3628 if (ValVT == MVT::i1) 3629 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3630 } 3631 3632 InVals.push_back(ArgValue); 3633 } else { 3634 // Argument stored in memory. 3635 assert(VA.isMemLoc()); 3636 3637 // Get the extended size of the argument type in stack 3638 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3639 // Get the actual size of the argument type 3640 unsigned ObjSize = VA.getValVT().getStoreSize(); 3641 unsigned ArgOffset = VA.getLocMemOffset(); 3642 // Stack objects in PPC32 are right justified. 3643 ArgOffset += ArgSize - ObjSize; 3644 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3645 3646 // Create load nodes to retrieve arguments from the stack. 3647 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3648 InVals.push_back( 3649 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3650 } 3651 } 3652 3653 // Assign locations to all of the incoming aggregate by value arguments. 3654 // Aggregates passed by value are stored in the local variable space of the 3655 // caller's stack frame, right above the parameter list area. 3656 SmallVector<CCValAssign, 16> ByValArgLocs; 3657 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3658 ByValArgLocs, *DAG.getContext()); 3659 3660 // Reserve stack space for the allocations in CCInfo. 3661 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3662 3663 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3664 3665 // Area that is at least reserved in the caller of this function. 3666 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3667 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3668 3669 // Set the size that is at least reserved in caller of this function. Tail 3670 // call optimized function's reserved stack space needs to be aligned so that 3671 // taking the difference between two stack areas will result in an aligned 3672 // stack. 3673 MinReservedArea = 3674 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3675 FuncInfo->setMinReservedArea(MinReservedArea); 3676 3677 SmallVector<SDValue, 8> MemOps; 3678 3679 // If the function takes variable number of arguments, make a frame index for 3680 // the start of the first vararg value... for expansion of llvm.va_start. 3681 if (isVarArg) { 3682 static const MCPhysReg GPArgRegs[] = { 3683 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3684 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3685 }; 3686 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3687 3688 static const MCPhysReg FPArgRegs[] = { 3689 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3690 PPC::F8 3691 }; 3692 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3693 3694 if (useSoftFloat() || hasSPE()) 3695 NumFPArgRegs = 0; 3696 3697 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3698 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3699 3700 // Make room for NumGPArgRegs and NumFPArgRegs. 3701 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3702 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3703 3704 FuncInfo->setVarArgsStackOffset( 3705 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3706 CCInfo.getNextStackOffset(), true)); 3707 3708 FuncInfo->setVarArgsFrameIndex( 3709 MFI.CreateStackObject(Depth, Align(8), false)); 3710 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3711 3712 // The fixed integer arguments of a variadic function are stored to the 3713 // VarArgsFrameIndex on the stack so that they may be loaded by 3714 // dereferencing the result of va_next. 3715 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3716 // Get an existing live-in vreg, or add a new one. 3717 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3718 if (!VReg) 3719 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3720 3721 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3722 SDValue Store = 3723 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3724 MemOps.push_back(Store); 3725 // Increment the address by four for the next argument to store 3726 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3727 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3728 } 3729 3730 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3731 // is set. 3732 // The double arguments are stored to the VarArgsFrameIndex 3733 // on the stack. 3734 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3735 // Get an existing live-in vreg, or add a new one. 3736 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3737 if (!VReg) 3738 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3739 3740 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3741 SDValue Store = 3742 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3743 MemOps.push_back(Store); 3744 // Increment the address by eight for the next argument to store 3745 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3746 PtrVT); 3747 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3748 } 3749 } 3750 3751 if (!MemOps.empty()) 3752 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3753 3754 return Chain; 3755 } 3756 3757 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3758 // value to MVT::i64 and then truncate to the correct register size. 3759 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3760 EVT ObjectVT, SelectionDAG &DAG, 3761 SDValue ArgVal, 3762 const SDLoc &dl) const { 3763 if (Flags.isSExt()) 3764 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3765 DAG.getValueType(ObjectVT)); 3766 else if (Flags.isZExt()) 3767 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3768 DAG.getValueType(ObjectVT)); 3769 3770 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3771 } 3772 3773 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3774 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3775 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3776 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3777 // TODO: add description of PPC stack frame format, or at least some docs. 3778 // 3779 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3780 bool isLittleEndian = Subtarget.isLittleEndian(); 3781 MachineFunction &MF = DAG.getMachineFunction(); 3782 MachineFrameInfo &MFI = MF.getFrameInfo(); 3783 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3784 3785 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3786 "fastcc not supported on varargs functions"); 3787 3788 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3789 // Potential tail calls could cause overwriting of argument stack slots. 3790 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3791 (CallConv == CallingConv::Fast)); 3792 unsigned PtrByteSize = 8; 3793 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3794 3795 static const MCPhysReg GPR[] = { 3796 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3797 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3798 }; 3799 static const MCPhysReg VR[] = { 3800 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3801 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3802 }; 3803 3804 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3805 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3806 const unsigned Num_VR_Regs = array_lengthof(VR); 3807 3808 // Do a first pass over the arguments to determine whether the ABI 3809 // guarantees that our caller has allocated the parameter save area 3810 // on its stack frame. In the ELFv1 ABI, this is always the case; 3811 // in the ELFv2 ABI, it is true if this is a vararg function or if 3812 // any parameter is located in a stack slot. 3813 3814 bool HasParameterArea = !isELFv2ABI || isVarArg; 3815 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3816 unsigned NumBytes = LinkageSize; 3817 unsigned AvailableFPRs = Num_FPR_Regs; 3818 unsigned AvailableVRs = Num_VR_Regs; 3819 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3820 if (Ins[i].Flags.isNest()) 3821 continue; 3822 3823 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3824 PtrByteSize, LinkageSize, ParamAreaSize, 3825 NumBytes, AvailableFPRs, AvailableVRs)) 3826 HasParameterArea = true; 3827 } 3828 3829 // Add DAG nodes to load the arguments or copy them out of registers. On 3830 // entry to a function on PPC, the arguments start after the linkage area, 3831 // although the first ones are often in registers. 3832 3833 unsigned ArgOffset = LinkageSize; 3834 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3835 SmallVector<SDValue, 8> MemOps; 3836 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3837 unsigned CurArgIdx = 0; 3838 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3839 SDValue ArgVal; 3840 bool needsLoad = false; 3841 EVT ObjectVT = Ins[ArgNo].VT; 3842 EVT OrigVT = Ins[ArgNo].ArgVT; 3843 unsigned ObjSize = ObjectVT.getStoreSize(); 3844 unsigned ArgSize = ObjSize; 3845 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3846 if (Ins[ArgNo].isOrigArg()) { 3847 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3848 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3849 } 3850 // We re-align the argument offset for each argument, except when using the 3851 // fast calling convention, when we need to make sure we do that only when 3852 // we'll actually use a stack slot. 3853 unsigned CurArgOffset; 3854 Align Alignment; 3855 auto ComputeArgOffset = [&]() { 3856 /* Respect alignment of argument on the stack. */ 3857 Alignment = 3858 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3859 ArgOffset = alignTo(ArgOffset, Alignment); 3860 CurArgOffset = ArgOffset; 3861 }; 3862 3863 if (CallConv != CallingConv::Fast) { 3864 ComputeArgOffset(); 3865 3866 /* Compute GPR index associated with argument offset. */ 3867 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3868 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3869 } 3870 3871 // FIXME the codegen can be much improved in some cases. 3872 // We do not have to keep everything in memory. 3873 if (Flags.isByVal()) { 3874 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3875 3876 if (CallConv == CallingConv::Fast) 3877 ComputeArgOffset(); 3878 3879 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3880 ObjSize = Flags.getByValSize(); 3881 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3882 // Empty aggregate parameters do not take up registers. Examples: 3883 // struct { } a; 3884 // union { } b; 3885 // int c[0]; 3886 // etc. However, we have to provide a place-holder in InVals, so 3887 // pretend we have an 8-byte item at the current address for that 3888 // purpose. 3889 if (!ObjSize) { 3890 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3891 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3892 InVals.push_back(FIN); 3893 continue; 3894 } 3895 3896 // Create a stack object covering all stack doublewords occupied 3897 // by the argument. If the argument is (fully or partially) on 3898 // the stack, or if the argument is fully in registers but the 3899 // caller has allocated the parameter save anyway, we can refer 3900 // directly to the caller's stack frame. Otherwise, create a 3901 // local copy in our own frame. 3902 int FI; 3903 if (HasParameterArea || 3904 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3905 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3906 else 3907 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3908 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3909 3910 // Handle aggregates smaller than 8 bytes. 3911 if (ObjSize < PtrByteSize) { 3912 // The value of the object is its address, which differs from the 3913 // address of the enclosing doubleword on big-endian systems. 3914 SDValue Arg = FIN; 3915 if (!isLittleEndian) { 3916 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3917 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3918 } 3919 InVals.push_back(Arg); 3920 3921 if (GPR_idx != Num_GPR_Regs) { 3922 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3923 FuncInfo->addLiveInAttr(VReg, Flags); 3924 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3925 SDValue Store; 3926 3927 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3928 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3929 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3930 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3931 MachinePointerInfo(&*FuncArg), ObjType); 3932 } else { 3933 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3934 // store the whole register as-is to the parameter save area 3935 // slot. 3936 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3937 MachinePointerInfo(&*FuncArg)); 3938 } 3939 3940 MemOps.push_back(Store); 3941 } 3942 // Whether we copied from a register or not, advance the offset 3943 // into the parameter save area by a full doubleword. 3944 ArgOffset += PtrByteSize; 3945 continue; 3946 } 3947 3948 // The value of the object is its address, which is the address of 3949 // its first stack doubleword. 3950 InVals.push_back(FIN); 3951 3952 // Store whatever pieces of the object are in registers to memory. 3953 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3954 if (GPR_idx == Num_GPR_Regs) 3955 break; 3956 3957 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3958 FuncInfo->addLiveInAttr(VReg, Flags); 3959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3960 SDValue Addr = FIN; 3961 if (j) { 3962 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3963 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3964 } 3965 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3966 MachinePointerInfo(&*FuncArg, j)); 3967 MemOps.push_back(Store); 3968 ++GPR_idx; 3969 } 3970 ArgOffset += ArgSize; 3971 continue; 3972 } 3973 3974 switch (ObjectVT.getSimpleVT().SimpleTy) { 3975 default: llvm_unreachable("Unhandled argument type!"); 3976 case MVT::i1: 3977 case MVT::i32: 3978 case MVT::i64: 3979 if (Flags.isNest()) { 3980 // The 'nest' parameter, if any, is passed in R11. 3981 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3982 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3983 3984 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3985 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3986 3987 break; 3988 } 3989 3990 // These can be scalar arguments or elements of an integer array type 3991 // passed directly. Clang may use those instead of "byval" aggregate 3992 // types to avoid forcing arguments to memory unnecessarily. 3993 if (GPR_idx != Num_GPR_Regs) { 3994 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3995 FuncInfo->addLiveInAttr(VReg, Flags); 3996 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3997 3998 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3999 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4000 // value to MVT::i64 and then truncate to the correct register size. 4001 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4002 } else { 4003 if (CallConv == CallingConv::Fast) 4004 ComputeArgOffset(); 4005 4006 needsLoad = true; 4007 ArgSize = PtrByteSize; 4008 } 4009 if (CallConv != CallingConv::Fast || needsLoad) 4010 ArgOffset += 8; 4011 break; 4012 4013 case MVT::f32: 4014 case MVT::f64: 4015 // These can be scalar arguments or elements of a float array type 4016 // passed directly. The latter are used to implement ELFv2 homogenous 4017 // float aggregates. 4018 if (FPR_idx != Num_FPR_Regs) { 4019 unsigned VReg; 4020 4021 if (ObjectVT == MVT::f32) 4022 VReg = MF.addLiveIn(FPR[FPR_idx], 4023 Subtarget.hasP8Vector() 4024 ? &PPC::VSSRCRegClass 4025 : &PPC::F4RCRegClass); 4026 else 4027 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4028 ? &PPC::VSFRCRegClass 4029 : &PPC::F8RCRegClass); 4030 4031 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4032 ++FPR_idx; 4033 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4034 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4035 // once we support fp <-> gpr moves. 4036 4037 // This can only ever happen in the presence of f32 array types, 4038 // since otherwise we never run out of FPRs before running out 4039 // of GPRs. 4040 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4041 FuncInfo->addLiveInAttr(VReg, Flags); 4042 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4043 4044 if (ObjectVT == MVT::f32) { 4045 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4046 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4047 DAG.getConstant(32, dl, MVT::i32)); 4048 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4049 } 4050 4051 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4052 } else { 4053 if (CallConv == CallingConv::Fast) 4054 ComputeArgOffset(); 4055 4056 needsLoad = true; 4057 } 4058 4059 // When passing an array of floats, the array occupies consecutive 4060 // space in the argument area; only round up to the next doubleword 4061 // at the end of the array. Otherwise, each float takes 8 bytes. 4062 if (CallConv != CallingConv::Fast || needsLoad) { 4063 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4064 ArgOffset += ArgSize; 4065 if (Flags.isInConsecutiveRegsLast()) 4066 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4067 } 4068 break; 4069 case MVT::v4f32: 4070 case MVT::v4i32: 4071 case MVT::v8i16: 4072 case MVT::v16i8: 4073 case MVT::v2f64: 4074 case MVT::v2i64: 4075 case MVT::v1i128: 4076 case MVT::f128: 4077 // These can be scalar arguments or elements of a vector array type 4078 // passed directly. The latter are used to implement ELFv2 homogenous 4079 // vector aggregates. 4080 if (VR_idx != Num_VR_Regs) { 4081 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4082 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4083 ++VR_idx; 4084 } else { 4085 if (CallConv == CallingConv::Fast) 4086 ComputeArgOffset(); 4087 needsLoad = true; 4088 } 4089 if (CallConv != CallingConv::Fast || needsLoad) 4090 ArgOffset += 16; 4091 break; 4092 } 4093 4094 // We need to load the argument to a virtual register if we determined 4095 // above that we ran out of physical registers of the appropriate type. 4096 if (needsLoad) { 4097 if (ObjSize < ArgSize && !isLittleEndian) 4098 CurArgOffset += ArgSize - ObjSize; 4099 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4100 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4101 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4102 } 4103 4104 InVals.push_back(ArgVal); 4105 } 4106 4107 // Area that is at least reserved in the caller of this function. 4108 unsigned MinReservedArea; 4109 if (HasParameterArea) 4110 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4111 else 4112 MinReservedArea = LinkageSize; 4113 4114 // Set the size that is at least reserved in caller of this function. Tail 4115 // call optimized functions' reserved stack space needs to be aligned so that 4116 // taking the difference between two stack areas will result in an aligned 4117 // stack. 4118 MinReservedArea = 4119 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4120 FuncInfo->setMinReservedArea(MinReservedArea); 4121 4122 // If the function takes variable number of arguments, make a frame index for 4123 // the start of the first vararg value... for expansion of llvm.va_start. 4124 // On ELFv2ABI spec, it writes: 4125 // C programs that are intended to be *portable* across different compilers 4126 // and architectures must use the header file <stdarg.h> to deal with variable 4127 // argument lists. 4128 if (isVarArg && MFI.hasVAStart()) { 4129 int Depth = ArgOffset; 4130 4131 FuncInfo->setVarArgsFrameIndex( 4132 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4133 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4134 4135 // If this function is vararg, store any remaining integer argument regs 4136 // to their spots on the stack so that they may be loaded by dereferencing 4137 // the result of va_next. 4138 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4139 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4140 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4141 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4142 SDValue Store = 4143 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4144 MemOps.push_back(Store); 4145 // Increment the address by four for the next argument to store 4146 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4147 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4148 } 4149 } 4150 4151 if (!MemOps.empty()) 4152 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4153 4154 return Chain; 4155 } 4156 4157 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4158 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4159 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4160 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4161 // TODO: add description of PPC stack frame format, or at least some docs. 4162 // 4163 MachineFunction &MF = DAG.getMachineFunction(); 4164 MachineFrameInfo &MFI = MF.getFrameInfo(); 4165 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4166 4167 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4168 bool isPPC64 = PtrVT == MVT::i64; 4169 // Potential tail calls could cause overwriting of argument stack slots. 4170 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4171 (CallConv == CallingConv::Fast)); 4172 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4173 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4174 unsigned ArgOffset = LinkageSize; 4175 // Area that is at least reserved in caller of this function. 4176 unsigned MinReservedArea = ArgOffset; 4177 4178 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4179 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4180 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4181 }; 4182 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4183 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4184 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4185 }; 4186 static const MCPhysReg VR[] = { 4187 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4188 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4189 }; 4190 4191 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4192 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4193 const unsigned Num_VR_Regs = array_lengthof( VR); 4194 4195 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4196 4197 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4198 4199 // In 32-bit non-varargs functions, the stack space for vectors is after the 4200 // stack space for non-vectors. We do not use this space unless we have 4201 // too many vectors to fit in registers, something that only occurs in 4202 // constructed examples:), but we have to walk the arglist to figure 4203 // that out...for the pathological case, compute VecArgOffset as the 4204 // start of the vector parameter area. Computing VecArgOffset is the 4205 // entire point of the following loop. 4206 unsigned VecArgOffset = ArgOffset; 4207 if (!isVarArg && !isPPC64) { 4208 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4209 ++ArgNo) { 4210 EVT ObjectVT = Ins[ArgNo].VT; 4211 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4212 4213 if (Flags.isByVal()) { 4214 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4215 unsigned ObjSize = Flags.getByValSize(); 4216 unsigned ArgSize = 4217 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4218 VecArgOffset += ArgSize; 4219 continue; 4220 } 4221 4222 switch(ObjectVT.getSimpleVT().SimpleTy) { 4223 default: llvm_unreachable("Unhandled argument type!"); 4224 case MVT::i1: 4225 case MVT::i32: 4226 case MVT::f32: 4227 VecArgOffset += 4; 4228 break; 4229 case MVT::i64: // PPC64 4230 case MVT::f64: 4231 // FIXME: We are guaranteed to be !isPPC64 at this point. 4232 // Does MVT::i64 apply? 4233 VecArgOffset += 8; 4234 break; 4235 case MVT::v4f32: 4236 case MVT::v4i32: 4237 case MVT::v8i16: 4238 case MVT::v16i8: 4239 // Nothing to do, we're only looking at Nonvector args here. 4240 break; 4241 } 4242 } 4243 } 4244 // We've found where the vector parameter area in memory is. Skip the 4245 // first 12 parameters; these don't use that memory. 4246 VecArgOffset = ((VecArgOffset+15)/16)*16; 4247 VecArgOffset += 12*16; 4248 4249 // Add DAG nodes to load the arguments or copy them out of registers. On 4250 // entry to a function on PPC, the arguments start after the linkage area, 4251 // although the first ones are often in registers. 4252 4253 SmallVector<SDValue, 8> MemOps; 4254 unsigned nAltivecParamsAtEnd = 0; 4255 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4256 unsigned CurArgIdx = 0; 4257 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4258 SDValue ArgVal; 4259 bool needsLoad = false; 4260 EVT ObjectVT = Ins[ArgNo].VT; 4261 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4262 unsigned ArgSize = ObjSize; 4263 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4264 if (Ins[ArgNo].isOrigArg()) { 4265 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4266 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4267 } 4268 unsigned CurArgOffset = ArgOffset; 4269 4270 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4271 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4272 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4273 if (isVarArg || isPPC64) { 4274 MinReservedArea = ((MinReservedArea+15)/16)*16; 4275 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4276 Flags, 4277 PtrByteSize); 4278 } else nAltivecParamsAtEnd++; 4279 } else 4280 // Calculate min reserved area. 4281 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4282 Flags, 4283 PtrByteSize); 4284 4285 // FIXME the codegen can be much improved in some cases. 4286 // We do not have to keep everything in memory. 4287 if (Flags.isByVal()) { 4288 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4289 4290 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4291 ObjSize = Flags.getByValSize(); 4292 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4293 // Objects of size 1 and 2 are right justified, everything else is 4294 // left justified. This means the memory address is adjusted forwards. 4295 if (ObjSize==1 || ObjSize==2) { 4296 CurArgOffset = CurArgOffset + (4 - ObjSize); 4297 } 4298 // The value of the object is its address. 4299 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4300 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4301 InVals.push_back(FIN); 4302 if (ObjSize==1 || ObjSize==2) { 4303 if (GPR_idx != Num_GPR_Regs) { 4304 unsigned VReg; 4305 if (isPPC64) 4306 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4307 else 4308 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4309 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4310 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4311 SDValue Store = 4312 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4313 MachinePointerInfo(&*FuncArg), ObjType); 4314 MemOps.push_back(Store); 4315 ++GPR_idx; 4316 } 4317 4318 ArgOffset += PtrByteSize; 4319 4320 continue; 4321 } 4322 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4323 // Store whatever pieces of the object are in registers 4324 // to memory. ArgOffset will be the address of the beginning 4325 // of the object. 4326 if (GPR_idx != Num_GPR_Regs) { 4327 unsigned VReg; 4328 if (isPPC64) 4329 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4330 else 4331 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4332 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4333 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4334 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4335 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4336 MachinePointerInfo(&*FuncArg, j)); 4337 MemOps.push_back(Store); 4338 ++GPR_idx; 4339 ArgOffset += PtrByteSize; 4340 } else { 4341 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4342 break; 4343 } 4344 } 4345 continue; 4346 } 4347 4348 switch (ObjectVT.getSimpleVT().SimpleTy) { 4349 default: llvm_unreachable("Unhandled argument type!"); 4350 case MVT::i1: 4351 case MVT::i32: 4352 if (!isPPC64) { 4353 if (GPR_idx != Num_GPR_Regs) { 4354 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4355 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4356 4357 if (ObjectVT == MVT::i1) 4358 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4359 4360 ++GPR_idx; 4361 } else { 4362 needsLoad = true; 4363 ArgSize = PtrByteSize; 4364 } 4365 // All int arguments reserve stack space in the Darwin ABI. 4366 ArgOffset += PtrByteSize; 4367 break; 4368 } 4369 LLVM_FALLTHROUGH; 4370 case MVT::i64: // PPC64 4371 if (GPR_idx != Num_GPR_Regs) { 4372 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4373 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4374 4375 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4376 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4377 // value to MVT::i64 and then truncate to the correct register size. 4378 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4379 4380 ++GPR_idx; 4381 } else { 4382 needsLoad = true; 4383 ArgSize = PtrByteSize; 4384 } 4385 // All int arguments reserve stack space in the Darwin ABI. 4386 ArgOffset += 8; 4387 break; 4388 4389 case MVT::f32: 4390 case MVT::f64: 4391 // Every 4 bytes of argument space consumes one of the GPRs available for 4392 // argument passing. 4393 if (GPR_idx != Num_GPR_Regs) { 4394 ++GPR_idx; 4395 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4396 ++GPR_idx; 4397 } 4398 if (FPR_idx != Num_FPR_Regs) { 4399 unsigned VReg; 4400 4401 if (ObjectVT == MVT::f32) 4402 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4403 else 4404 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4405 4406 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4407 ++FPR_idx; 4408 } else { 4409 needsLoad = true; 4410 } 4411 4412 // All FP arguments reserve stack space in the Darwin ABI. 4413 ArgOffset += isPPC64 ? 8 : ObjSize; 4414 break; 4415 case MVT::v4f32: 4416 case MVT::v4i32: 4417 case MVT::v8i16: 4418 case MVT::v16i8: 4419 // Note that vector arguments in registers don't reserve stack space, 4420 // except in varargs functions. 4421 if (VR_idx != Num_VR_Regs) { 4422 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4423 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4424 if (isVarArg) { 4425 while ((ArgOffset % 16) != 0) { 4426 ArgOffset += PtrByteSize; 4427 if (GPR_idx != Num_GPR_Regs) 4428 GPR_idx++; 4429 } 4430 ArgOffset += 16; 4431 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4432 } 4433 ++VR_idx; 4434 } else { 4435 if (!isVarArg && !isPPC64) { 4436 // Vectors go after all the nonvectors. 4437 CurArgOffset = VecArgOffset; 4438 VecArgOffset += 16; 4439 } else { 4440 // Vectors are aligned. 4441 ArgOffset = ((ArgOffset+15)/16)*16; 4442 CurArgOffset = ArgOffset; 4443 ArgOffset += 16; 4444 } 4445 needsLoad = true; 4446 } 4447 break; 4448 } 4449 4450 // We need to load the argument to a virtual register if we determined above 4451 // that we ran out of physical registers of the appropriate type. 4452 if (needsLoad) { 4453 int FI = MFI.CreateFixedObject(ObjSize, 4454 CurArgOffset + (ArgSize - ObjSize), 4455 isImmutable); 4456 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4457 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4458 } 4459 4460 InVals.push_back(ArgVal); 4461 } 4462 4463 // Allow for Altivec parameters at the end, if needed. 4464 if (nAltivecParamsAtEnd) { 4465 MinReservedArea = ((MinReservedArea+15)/16)*16; 4466 MinReservedArea += 16*nAltivecParamsAtEnd; 4467 } 4468 4469 // Area that is at least reserved in the caller of this function. 4470 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4471 4472 // Set the size that is at least reserved in caller of this function. Tail 4473 // call optimized functions' reserved stack space needs to be aligned so that 4474 // taking the difference between two stack areas will result in an aligned 4475 // stack. 4476 MinReservedArea = 4477 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4478 FuncInfo->setMinReservedArea(MinReservedArea); 4479 4480 // If the function takes variable number of arguments, make a frame index for 4481 // the start of the first vararg value... for expansion of llvm.va_start. 4482 if (isVarArg) { 4483 int Depth = ArgOffset; 4484 4485 FuncInfo->setVarArgsFrameIndex( 4486 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4487 Depth, true)); 4488 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4489 4490 // If this function is vararg, store any remaining integer argument regs 4491 // to their spots on the stack so that they may be loaded by dereferencing 4492 // the result of va_next. 4493 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4494 unsigned VReg; 4495 4496 if (isPPC64) 4497 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4498 else 4499 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4500 4501 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4502 SDValue Store = 4503 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4504 MemOps.push_back(Store); 4505 // Increment the address by four for the next argument to store 4506 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4507 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4508 } 4509 } 4510 4511 if (!MemOps.empty()) 4512 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4513 4514 return Chain; 4515 } 4516 4517 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4518 /// adjusted to accommodate the arguments for the tailcall. 4519 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4520 unsigned ParamSize) { 4521 4522 if (!isTailCall) return 0; 4523 4524 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4525 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4526 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4527 // Remember only if the new adjustment is bigger. 4528 if (SPDiff < FI->getTailCallSPDelta()) 4529 FI->setTailCallSPDelta(SPDiff); 4530 4531 return SPDiff; 4532 } 4533 4534 static bool isFunctionGlobalAddress(SDValue Callee); 4535 4536 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4537 const TargetMachine &TM) { 4538 // It does not make sense to call callsShareTOCBase() with a caller that 4539 // is PC Relative since PC Relative callers do not have a TOC. 4540 #ifndef NDEBUG 4541 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4542 assert(!STICaller->isUsingPCRelativeCalls() && 4543 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4544 #endif 4545 4546 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4547 // don't have enough information to determine if the caller and callee share 4548 // the same TOC base, so we have to pessimistically assume they don't for 4549 // correctness. 4550 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4551 if (!G) 4552 return false; 4553 4554 const GlobalValue *GV = G->getGlobal(); 4555 4556 // If the callee is preemptable, then the static linker will use a plt-stub 4557 // which saves the toc to the stack, and needs a nop after the call 4558 // instruction to convert to a toc-restore. 4559 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4560 return false; 4561 4562 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4563 // We may need a TOC restore in the situation where the caller requires a 4564 // valid TOC but the callee is PC Relative and does not. 4565 const Function *F = dyn_cast<Function>(GV); 4566 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4567 4568 // If we have an Alias we can try to get the function from there. 4569 if (Alias) { 4570 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4571 F = dyn_cast<Function>(GlobalObj); 4572 } 4573 4574 // If we still have no valid function pointer we do not have enough 4575 // information to determine if the callee uses PC Relative calls so we must 4576 // assume that it does. 4577 if (!F) 4578 return false; 4579 4580 // If the callee uses PC Relative we cannot guarantee that the callee won't 4581 // clobber the TOC of the caller and so we must assume that the two 4582 // functions do not share a TOC base. 4583 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4584 if (STICallee->isUsingPCRelativeCalls()) 4585 return false; 4586 4587 // The medium and large code models are expected to provide a sufficiently 4588 // large TOC to provide all data addressing needs of a module with a 4589 // single TOC. 4590 if (CodeModel::Medium == TM.getCodeModel() || 4591 CodeModel::Large == TM.getCodeModel()) 4592 return true; 4593 4594 // Otherwise we need to ensure callee and caller are in the same section, 4595 // since the linker may allocate multiple TOCs, and we don't know which 4596 // sections will belong to the same TOC base. 4597 if (!GV->isStrongDefinitionForLinker()) 4598 return false; 4599 4600 // Any explicitly-specified sections and section prefixes must also match. 4601 // Also, if we're using -ffunction-sections, then each function is always in 4602 // a different section (the same is true for COMDAT functions). 4603 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4604 GV->getSection() != Caller->getSection()) 4605 return false; 4606 if (const auto *F = dyn_cast<Function>(GV)) { 4607 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4608 return false; 4609 } 4610 4611 return true; 4612 } 4613 4614 static bool 4615 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4616 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4617 assert(Subtarget.is64BitELFABI()); 4618 4619 const unsigned PtrByteSize = 8; 4620 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4621 4622 static const MCPhysReg GPR[] = { 4623 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4624 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4625 }; 4626 static const MCPhysReg VR[] = { 4627 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4628 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4629 }; 4630 4631 const unsigned NumGPRs = array_lengthof(GPR); 4632 const unsigned NumFPRs = 13; 4633 const unsigned NumVRs = array_lengthof(VR); 4634 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4635 4636 unsigned NumBytes = LinkageSize; 4637 unsigned AvailableFPRs = NumFPRs; 4638 unsigned AvailableVRs = NumVRs; 4639 4640 for (const ISD::OutputArg& Param : Outs) { 4641 if (Param.Flags.isNest()) continue; 4642 4643 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4644 LinkageSize, ParamAreaSize, NumBytes, 4645 AvailableFPRs, AvailableVRs)) 4646 return true; 4647 } 4648 return false; 4649 } 4650 4651 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4652 if (CB.arg_size() != CallerFn->arg_size()) 4653 return false; 4654 4655 auto CalleeArgIter = CB.arg_begin(); 4656 auto CalleeArgEnd = CB.arg_end(); 4657 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4658 4659 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4660 const Value* CalleeArg = *CalleeArgIter; 4661 const Value* CallerArg = &(*CallerArgIter); 4662 if (CalleeArg == CallerArg) 4663 continue; 4664 4665 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4666 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4667 // } 4668 // 1st argument of callee is undef and has the same type as caller. 4669 if (CalleeArg->getType() == CallerArg->getType() && 4670 isa<UndefValue>(CalleeArg)) 4671 continue; 4672 4673 return false; 4674 } 4675 4676 return true; 4677 } 4678 4679 // Returns true if TCO is possible between the callers and callees 4680 // calling conventions. 4681 static bool 4682 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4683 CallingConv::ID CalleeCC) { 4684 // Tail calls are possible with fastcc and ccc. 4685 auto isTailCallableCC = [] (CallingConv::ID CC){ 4686 return CC == CallingConv::C || CC == CallingConv::Fast; 4687 }; 4688 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4689 return false; 4690 4691 // We can safely tail call both fastcc and ccc callees from a c calling 4692 // convention caller. If the caller is fastcc, we may have less stack space 4693 // than a non-fastcc caller with the same signature so disable tail-calls in 4694 // that case. 4695 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4696 } 4697 4698 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4699 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4700 const SmallVectorImpl<ISD::OutputArg> &Outs, 4701 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4702 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4703 4704 if (DisableSCO && !TailCallOpt) return false; 4705 4706 // Variadic argument functions are not supported. 4707 if (isVarArg) return false; 4708 4709 auto &Caller = DAG.getMachineFunction().getFunction(); 4710 // Check that the calling conventions are compatible for tco. 4711 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4712 return false; 4713 4714 // Caller contains any byval parameter is not supported. 4715 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4716 return false; 4717 4718 // Callee contains any byval parameter is not supported, too. 4719 // Note: This is a quick work around, because in some cases, e.g. 4720 // caller's stack size > callee's stack size, we are still able to apply 4721 // sibling call optimization. For example, gcc is able to do SCO for caller1 4722 // in the following example, but not for caller2. 4723 // struct test { 4724 // long int a; 4725 // char ary[56]; 4726 // } gTest; 4727 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4728 // b->a = v.a; 4729 // return 0; 4730 // } 4731 // void caller1(struct test a, struct test c, struct test *b) { 4732 // callee(gTest, b); } 4733 // void caller2(struct test *b) { callee(gTest, b); } 4734 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4735 return false; 4736 4737 // If callee and caller use different calling conventions, we cannot pass 4738 // parameters on stack since offsets for the parameter area may be different. 4739 if (Caller.getCallingConv() != CalleeCC && 4740 needStackSlotPassParameters(Subtarget, Outs)) 4741 return false; 4742 4743 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4744 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4745 // callee potentially have different TOC bases then we cannot tail call since 4746 // we need to restore the TOC pointer after the call. 4747 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4748 // We cannot guarantee this for indirect calls or calls to external functions. 4749 // When PC-Relative addressing is used, the concept of the TOC is no longer 4750 // applicable so this check is not required. 4751 // Check first for indirect calls. 4752 if (!Subtarget.isUsingPCRelativeCalls() && 4753 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4754 return false; 4755 4756 // Check if we share the TOC base. 4757 if (!Subtarget.isUsingPCRelativeCalls() && 4758 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4759 return false; 4760 4761 // TCO allows altering callee ABI, so we don't have to check further. 4762 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4763 return true; 4764 4765 if (DisableSCO) return false; 4766 4767 // If callee use the same argument list that caller is using, then we can 4768 // apply SCO on this case. If it is not, then we need to check if callee needs 4769 // stack for passing arguments. 4770 // PC Relative tail calls may not have a CallBase. 4771 // If there is no CallBase we cannot verify if we have the same argument 4772 // list so assume that we don't have the same argument list. 4773 if (CB && !hasSameArgumentList(&Caller, *CB) && 4774 needStackSlotPassParameters(Subtarget, Outs)) 4775 return false; 4776 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4777 return false; 4778 4779 return true; 4780 } 4781 4782 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4783 /// for tail call optimization. Targets which want to do tail call 4784 /// optimization should implement this function. 4785 bool 4786 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4787 CallingConv::ID CalleeCC, 4788 bool isVarArg, 4789 const SmallVectorImpl<ISD::InputArg> &Ins, 4790 SelectionDAG& DAG) const { 4791 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4792 return false; 4793 4794 // Variable argument functions are not supported. 4795 if (isVarArg) 4796 return false; 4797 4798 MachineFunction &MF = DAG.getMachineFunction(); 4799 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4800 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4801 // Functions containing by val parameters are not supported. 4802 for (unsigned i = 0; i != Ins.size(); i++) { 4803 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4804 if (Flags.isByVal()) return false; 4805 } 4806 4807 // Non-PIC/GOT tail calls are supported. 4808 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4809 return true; 4810 4811 // At the moment we can only do local tail calls (in same module, hidden 4812 // or protected) if we are generating PIC. 4813 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4814 return G->getGlobal()->hasHiddenVisibility() 4815 || G->getGlobal()->hasProtectedVisibility(); 4816 } 4817 4818 return false; 4819 } 4820 4821 /// isCallCompatibleAddress - Return the immediate to use if the specified 4822 /// 32-bit value is representable in the immediate field of a BxA instruction. 4823 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4824 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4825 if (!C) return nullptr; 4826 4827 int Addr = C->getZExtValue(); 4828 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4829 SignExtend32<26>(Addr) != Addr) 4830 return nullptr; // Top 6 bits have to be sext of immediate. 4831 4832 return DAG 4833 .getConstant( 4834 (int)C->getZExtValue() >> 2, SDLoc(Op), 4835 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4836 .getNode(); 4837 } 4838 4839 namespace { 4840 4841 struct TailCallArgumentInfo { 4842 SDValue Arg; 4843 SDValue FrameIdxOp; 4844 int FrameIdx = 0; 4845 4846 TailCallArgumentInfo() = default; 4847 }; 4848 4849 } // end anonymous namespace 4850 4851 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4852 static void StoreTailCallArgumentsToStackSlot( 4853 SelectionDAG &DAG, SDValue Chain, 4854 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4855 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4856 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4857 SDValue Arg = TailCallArgs[i].Arg; 4858 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4859 int FI = TailCallArgs[i].FrameIdx; 4860 // Store relative to framepointer. 4861 MemOpChains.push_back(DAG.getStore( 4862 Chain, dl, Arg, FIN, 4863 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4864 } 4865 } 4866 4867 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4868 /// the appropriate stack slot for the tail call optimized function call. 4869 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4870 SDValue OldRetAddr, SDValue OldFP, 4871 int SPDiff, const SDLoc &dl) { 4872 if (SPDiff) { 4873 // Calculate the new stack slot for the return address. 4874 MachineFunction &MF = DAG.getMachineFunction(); 4875 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4876 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4877 bool isPPC64 = Subtarget.isPPC64(); 4878 int SlotSize = isPPC64 ? 8 : 4; 4879 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4880 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4881 NewRetAddrLoc, true); 4882 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4883 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4884 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4885 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4886 } 4887 return Chain; 4888 } 4889 4890 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4891 /// the position of the argument. 4892 static void 4893 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4894 SDValue Arg, int SPDiff, unsigned ArgOffset, 4895 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4896 int Offset = ArgOffset + SPDiff; 4897 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4898 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4899 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4900 SDValue FIN = DAG.getFrameIndex(FI, VT); 4901 TailCallArgumentInfo Info; 4902 Info.Arg = Arg; 4903 Info.FrameIdxOp = FIN; 4904 Info.FrameIdx = FI; 4905 TailCallArguments.push_back(Info); 4906 } 4907 4908 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4909 /// stack slot. Returns the chain as result and the loaded frame pointers in 4910 /// LROpOut/FPOpout. Used when tail calling. 4911 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4912 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4913 SDValue &FPOpOut, const SDLoc &dl) const { 4914 if (SPDiff) { 4915 // Load the LR and FP stack slot for later adjusting. 4916 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4917 LROpOut = getReturnAddrFrameIndex(DAG); 4918 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4919 Chain = SDValue(LROpOut.getNode(), 1); 4920 } 4921 return Chain; 4922 } 4923 4924 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4925 /// by "Src" to address "Dst" of size "Size". Alignment information is 4926 /// specified by the specific parameter attribute. The copy will be passed as 4927 /// a byval function parameter. 4928 /// Sometimes what we are copying is the end of a larger object, the part that 4929 /// does not fit in registers. 4930 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4931 SDValue Chain, ISD::ArgFlagsTy Flags, 4932 SelectionDAG &DAG, const SDLoc &dl) { 4933 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4934 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4935 Flags.getNonZeroByValAlign(), false, false, false, 4936 MachinePointerInfo(), MachinePointerInfo()); 4937 } 4938 4939 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4940 /// tail calls. 4941 static void LowerMemOpCallTo( 4942 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4943 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4944 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4945 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4946 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4947 if (!isTailCall) { 4948 if (isVector) { 4949 SDValue StackPtr; 4950 if (isPPC64) 4951 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4952 else 4953 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4954 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4955 DAG.getConstant(ArgOffset, dl, PtrVT)); 4956 } 4957 MemOpChains.push_back( 4958 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4959 // Calculate and remember argument location. 4960 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4961 TailCallArguments); 4962 } 4963 4964 static void 4965 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4966 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4967 SDValue FPOp, 4968 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4969 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4970 // might overwrite each other in case of tail call optimization. 4971 SmallVector<SDValue, 8> MemOpChains2; 4972 // Do not flag preceding copytoreg stuff together with the following stuff. 4973 InFlag = SDValue(); 4974 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4975 MemOpChains2, dl); 4976 if (!MemOpChains2.empty()) 4977 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4978 4979 // Store the return address to the appropriate stack slot. 4980 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4981 4982 // Emit callseq_end just before tailcall node. 4983 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4984 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4985 InFlag = Chain.getValue(1); 4986 } 4987 4988 // Is this global address that of a function that can be called by name? (as 4989 // opposed to something that must hold a descriptor for an indirect call). 4990 static bool isFunctionGlobalAddress(SDValue Callee) { 4991 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4992 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4993 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4994 return false; 4995 4996 return G->getGlobal()->getValueType()->isFunctionTy(); 4997 } 4998 4999 return false; 5000 } 5001 5002 SDValue PPCTargetLowering::LowerCallResult( 5003 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5004 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5005 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5006 SmallVector<CCValAssign, 16> RVLocs; 5007 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5008 *DAG.getContext()); 5009 5010 CCRetInfo.AnalyzeCallResult( 5011 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5012 ? RetCC_PPC_Cold 5013 : RetCC_PPC); 5014 5015 // Copy all of the result registers out of their specified physreg. 5016 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5017 CCValAssign &VA = RVLocs[i]; 5018 assert(VA.isRegLoc() && "Can only return in registers!"); 5019 5020 SDValue Val; 5021 5022 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5023 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5024 InFlag); 5025 Chain = Lo.getValue(1); 5026 InFlag = Lo.getValue(2); 5027 VA = RVLocs[++i]; // skip ahead to next loc 5028 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5029 InFlag); 5030 Chain = Hi.getValue(1); 5031 InFlag = Hi.getValue(2); 5032 if (!Subtarget.isLittleEndian()) 5033 std::swap (Lo, Hi); 5034 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5035 } else { 5036 Val = DAG.getCopyFromReg(Chain, dl, 5037 VA.getLocReg(), VA.getLocVT(), InFlag); 5038 Chain = Val.getValue(1); 5039 InFlag = Val.getValue(2); 5040 } 5041 5042 switch (VA.getLocInfo()) { 5043 default: llvm_unreachable("Unknown loc info!"); 5044 case CCValAssign::Full: break; 5045 case CCValAssign::AExt: 5046 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5047 break; 5048 case CCValAssign::ZExt: 5049 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5050 DAG.getValueType(VA.getValVT())); 5051 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5052 break; 5053 case CCValAssign::SExt: 5054 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5055 DAG.getValueType(VA.getValVT())); 5056 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5057 break; 5058 } 5059 5060 InVals.push_back(Val); 5061 } 5062 5063 return Chain; 5064 } 5065 5066 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5067 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5068 // PatchPoint calls are not indirect. 5069 if (isPatchPoint) 5070 return false; 5071 5072 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5073 return false; 5074 5075 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5076 // becuase the immediate function pointer points to a descriptor instead of 5077 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5078 // pointer immediate points to the global entry point, while the BLA would 5079 // need to jump to the local entry point (see rL211174). 5080 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5081 isBLACompatibleAddress(Callee, DAG)) 5082 return false; 5083 5084 return true; 5085 } 5086 5087 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5088 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5089 return Subtarget.isAIXABI() || 5090 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5091 } 5092 5093 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5094 const Function &Caller, 5095 const SDValue &Callee, 5096 const PPCSubtarget &Subtarget, 5097 const TargetMachine &TM) { 5098 if (CFlags.IsTailCall) 5099 return PPCISD::TC_RETURN; 5100 5101 // This is a call through a function pointer. 5102 if (CFlags.IsIndirect) { 5103 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5104 // indirect calls. The save of the caller's TOC pointer to the stack will be 5105 // inserted into the DAG as part of call lowering. The restore of the TOC 5106 // pointer is modeled by using a pseudo instruction for the call opcode that 5107 // represents the 2 instruction sequence of an indirect branch and link, 5108 // immediately followed by a load of the TOC pointer from the the stack save 5109 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5110 // as it is not saved or used. 5111 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5112 : PPCISD::BCTRL; 5113 } 5114 5115 if (Subtarget.isUsingPCRelativeCalls()) { 5116 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5117 return PPCISD::CALL_NOTOC; 5118 } 5119 5120 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5121 // immediately following the call instruction if the caller and callee may 5122 // have different TOC bases. At link time if the linker determines the calls 5123 // may not share a TOC base, the call is redirected to a trampoline inserted 5124 // by the linker. The trampoline will (among other things) save the callers 5125 // TOC pointer at an ABI designated offset in the linkage area and the linker 5126 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5127 // into gpr2. 5128 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5129 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5130 : PPCISD::CALL_NOP; 5131 5132 return PPCISD::CALL; 5133 } 5134 5135 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5136 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5137 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5138 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5139 return SDValue(Dest, 0); 5140 5141 // Returns true if the callee is local, and false otherwise. 5142 auto isLocalCallee = [&]() { 5143 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5144 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5145 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5146 5147 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5148 !dyn_cast_or_null<GlobalIFunc>(GV); 5149 }; 5150 5151 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5152 // a static relocation model causes some versions of GNU LD (2.17.50, at 5153 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5154 // built with secure-PLT. 5155 bool UsePlt = 5156 Subtarget.is32BitELFABI() && !isLocalCallee() && 5157 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5158 5159 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5160 const TargetMachine &TM = Subtarget.getTargetMachine(); 5161 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5162 MCSymbolXCOFF *S = 5163 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5164 5165 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5166 return DAG.getMCSymbol(S, PtrVT); 5167 }; 5168 5169 if (isFunctionGlobalAddress(Callee)) { 5170 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5171 5172 if (Subtarget.isAIXABI()) { 5173 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5174 return getAIXFuncEntryPointSymbolSDNode(GV); 5175 } 5176 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5177 UsePlt ? PPCII::MO_PLT : 0); 5178 } 5179 5180 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5181 const char *SymName = S->getSymbol(); 5182 if (Subtarget.isAIXABI()) { 5183 // If there exists a user-declared function whose name is the same as the 5184 // ExternalSymbol's, then we pick up the user-declared version. 5185 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5186 if (const Function *F = 5187 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5188 return getAIXFuncEntryPointSymbolSDNode(F); 5189 5190 // On AIX, direct function calls reference the symbol for the function's 5191 // entry point, which is named by prepending a "." before the function's 5192 // C-linkage name. A Qualname is returned here because an external 5193 // function entry point is a csect with XTY_ER property. 5194 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5195 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5196 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5197 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5198 SectionKind::getMetadata()); 5199 return Sec->getQualNameSymbol(); 5200 }; 5201 5202 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5203 } 5204 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5205 UsePlt ? PPCII::MO_PLT : 0); 5206 } 5207 5208 // No transformation needed. 5209 assert(Callee.getNode() && "What no callee?"); 5210 return Callee; 5211 } 5212 5213 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5214 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5215 "Expected a CALLSEQ_STARTSDNode."); 5216 5217 // The last operand is the chain, except when the node has glue. If the node 5218 // has glue, then the last operand is the glue, and the chain is the second 5219 // last operand. 5220 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5221 if (LastValue.getValueType() != MVT::Glue) 5222 return LastValue; 5223 5224 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5225 } 5226 5227 // Creates the node that moves a functions address into the count register 5228 // to prepare for an indirect call instruction. 5229 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5230 SDValue &Glue, SDValue &Chain, 5231 const SDLoc &dl) { 5232 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5233 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5234 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5235 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5236 // The glue is the second value produced. 5237 Glue = Chain.getValue(1); 5238 } 5239 5240 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5241 SDValue &Glue, SDValue &Chain, 5242 SDValue CallSeqStart, 5243 const CallBase *CB, const SDLoc &dl, 5244 bool hasNest, 5245 const PPCSubtarget &Subtarget) { 5246 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5247 // entry point, but to the function descriptor (the function entry point 5248 // address is part of the function descriptor though). 5249 // The function descriptor is a three doubleword structure with the 5250 // following fields: function entry point, TOC base address and 5251 // environment pointer. 5252 // Thus for a call through a function pointer, the following actions need 5253 // to be performed: 5254 // 1. Save the TOC of the caller in the TOC save area of its stack 5255 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5256 // 2. Load the address of the function entry point from the function 5257 // descriptor. 5258 // 3. Load the TOC of the callee from the function descriptor into r2. 5259 // 4. Load the environment pointer from the function descriptor into 5260 // r11. 5261 // 5. Branch to the function entry point address. 5262 // 6. On return of the callee, the TOC of the caller needs to be 5263 // restored (this is done in FinishCall()). 5264 // 5265 // The loads are scheduled at the beginning of the call sequence, and the 5266 // register copies are flagged together to ensure that no other 5267 // operations can be scheduled in between. E.g. without flagging the 5268 // copies together, a TOC access in the caller could be scheduled between 5269 // the assignment of the callee TOC and the branch to the callee, which leads 5270 // to incorrect code. 5271 5272 // Start by loading the function address from the descriptor. 5273 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5274 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5275 ? (MachineMemOperand::MODereferenceable | 5276 MachineMemOperand::MOInvariant) 5277 : MachineMemOperand::MONone; 5278 5279 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5280 5281 // Registers used in building the DAG. 5282 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5283 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5284 5285 // Offsets of descriptor members. 5286 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5287 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5288 5289 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5290 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5291 5292 // One load for the functions entry point address. 5293 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5294 Alignment, MMOFlags); 5295 5296 // One for loading the TOC anchor for the module that contains the called 5297 // function. 5298 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5299 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5300 SDValue TOCPtr = 5301 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5302 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5303 5304 // One for loading the environment pointer. 5305 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5306 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5307 SDValue LoadEnvPtr = 5308 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5309 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5310 5311 5312 // Then copy the newly loaded TOC anchor to the TOC pointer. 5313 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5314 Chain = TOCVal.getValue(0); 5315 Glue = TOCVal.getValue(1); 5316 5317 // If the function call has an explicit 'nest' parameter, it takes the 5318 // place of the environment pointer. 5319 assert((!hasNest || !Subtarget.isAIXABI()) && 5320 "Nest parameter is not supported on AIX."); 5321 if (!hasNest) { 5322 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5323 Chain = EnvVal.getValue(0); 5324 Glue = EnvVal.getValue(1); 5325 } 5326 5327 // The rest of the indirect call sequence is the same as the non-descriptor 5328 // DAG. 5329 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5330 } 5331 5332 static void 5333 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5334 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5335 SelectionDAG &DAG, 5336 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5337 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5338 const PPCSubtarget &Subtarget) { 5339 const bool IsPPC64 = Subtarget.isPPC64(); 5340 // MVT for a general purpose register. 5341 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5342 5343 // First operand is always the chain. 5344 Ops.push_back(Chain); 5345 5346 // If it's a direct call pass the callee as the second operand. 5347 if (!CFlags.IsIndirect) 5348 Ops.push_back(Callee); 5349 else { 5350 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5351 5352 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5353 // on the stack (this would have been done in `LowerCall_64SVR4` or 5354 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5355 // represents both the indirect branch and a load that restores the TOC 5356 // pointer from the linkage area. The operand for the TOC restore is an add 5357 // of the TOC save offset to the stack pointer. This must be the second 5358 // operand: after the chain input but before any other variadic arguments. 5359 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5360 // saved or used. 5361 if (isTOCSaveRestoreRequired(Subtarget)) { 5362 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5363 5364 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5365 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5366 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5367 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5368 Ops.push_back(AddTOC); 5369 } 5370 5371 // Add the register used for the environment pointer. 5372 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5373 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5374 RegVT)); 5375 5376 5377 // Add CTR register as callee so a bctr can be emitted later. 5378 if (CFlags.IsTailCall) 5379 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5380 } 5381 5382 // If this is a tail call add stack pointer delta. 5383 if (CFlags.IsTailCall) 5384 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5385 5386 // Add argument registers to the end of the list so that they are known live 5387 // into the call. 5388 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5389 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5390 RegsToPass[i].second.getValueType())); 5391 5392 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5393 // no way to mark dependencies as implicit here. 5394 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5395 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5396 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5397 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5398 5399 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5400 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5401 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5402 5403 // Add a register mask operand representing the call-preserved registers. 5404 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5405 const uint32_t *Mask = 5406 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5407 assert(Mask && "Missing call preserved mask for calling convention"); 5408 Ops.push_back(DAG.getRegisterMask(Mask)); 5409 5410 // If the glue is valid, it is the last operand. 5411 if (Glue.getNode()) 5412 Ops.push_back(Glue); 5413 } 5414 5415 SDValue PPCTargetLowering::FinishCall( 5416 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5417 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5418 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5419 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5420 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5421 5422 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5423 Subtarget.isAIXABI()) 5424 setUsesTOCBasePtr(DAG); 5425 5426 unsigned CallOpc = 5427 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5428 Subtarget, DAG.getTarget()); 5429 5430 if (!CFlags.IsIndirect) 5431 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5432 else if (Subtarget.usesFunctionDescriptors()) 5433 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5434 dl, CFlags.HasNest, Subtarget); 5435 else 5436 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5437 5438 // Build the operand list for the call instruction. 5439 SmallVector<SDValue, 8> Ops; 5440 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5441 SPDiff, Subtarget); 5442 5443 // Emit tail call. 5444 if (CFlags.IsTailCall) { 5445 // Indirect tail call when using PC Relative calls do not have the same 5446 // constraints. 5447 assert(((Callee.getOpcode() == ISD::Register && 5448 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5449 Callee.getOpcode() == ISD::TargetExternalSymbol || 5450 Callee.getOpcode() == ISD::TargetGlobalAddress || 5451 isa<ConstantSDNode>(Callee) || 5452 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5453 "Expecting a global address, external symbol, absolute value, " 5454 "register or an indirect tail call when PC Relative calls are " 5455 "used."); 5456 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5457 assert(CallOpc == PPCISD::TC_RETURN && 5458 "Unexpected call opcode for a tail call."); 5459 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5460 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5461 } 5462 5463 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5464 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5465 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5466 Glue = Chain.getValue(1); 5467 5468 // When performing tail call optimization the callee pops its arguments off 5469 // the stack. Account for this here so these bytes can be pushed back on in 5470 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5471 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5472 getTargetMachine().Options.GuaranteedTailCallOpt) 5473 ? NumBytes 5474 : 0; 5475 5476 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5477 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5478 Glue, dl); 5479 Glue = Chain.getValue(1); 5480 5481 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5482 DAG, InVals); 5483 } 5484 5485 SDValue 5486 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5487 SmallVectorImpl<SDValue> &InVals) const { 5488 SelectionDAG &DAG = CLI.DAG; 5489 SDLoc &dl = CLI.DL; 5490 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5491 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5492 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5493 SDValue Chain = CLI.Chain; 5494 SDValue Callee = CLI.Callee; 5495 bool &isTailCall = CLI.IsTailCall; 5496 CallingConv::ID CallConv = CLI.CallConv; 5497 bool isVarArg = CLI.IsVarArg; 5498 bool isPatchPoint = CLI.IsPatchPoint; 5499 const CallBase *CB = CLI.CB; 5500 5501 if (isTailCall) { 5502 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5503 isTailCall = false; 5504 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5505 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5506 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5507 else 5508 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5509 Ins, DAG); 5510 if (isTailCall) { 5511 ++NumTailCalls; 5512 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5513 ++NumSiblingCalls; 5514 5515 // PC Relative calls no longer guarantee that the callee is a Global 5516 // Address Node. The callee could be an indirect tail call in which 5517 // case the SDValue for the callee could be a load (to load the address 5518 // of a function pointer) or it may be a register copy (to move the 5519 // address of the callee from a function parameter into a virtual 5520 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5521 assert((Subtarget.isUsingPCRelativeCalls() || 5522 isa<GlobalAddressSDNode>(Callee)) && 5523 "Callee should be an llvm::Function object."); 5524 5525 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5526 << "\nTCO callee: "); 5527 LLVM_DEBUG(Callee.dump()); 5528 } 5529 } 5530 5531 if (!isTailCall && CB && CB->isMustTailCall()) 5532 report_fatal_error("failed to perform tail call elimination on a call " 5533 "site marked musttail"); 5534 5535 // When long calls (i.e. indirect calls) are always used, calls are always 5536 // made via function pointer. If we have a function name, first translate it 5537 // into a pointer. 5538 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5539 !isTailCall) 5540 Callee = LowerGlobalAddress(Callee, DAG); 5541 5542 CallFlags CFlags( 5543 CallConv, isTailCall, isVarArg, isPatchPoint, 5544 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5545 // hasNest 5546 Subtarget.is64BitELFABI() && 5547 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5548 CLI.NoMerge); 5549 5550 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5551 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5552 InVals, CB); 5553 5554 if (Subtarget.isSVR4ABI()) 5555 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5556 InVals, CB); 5557 5558 if (Subtarget.isAIXABI()) 5559 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5560 InVals, CB); 5561 5562 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5563 InVals, CB); 5564 } 5565 5566 SDValue PPCTargetLowering::LowerCall_32SVR4( 5567 SDValue Chain, SDValue Callee, CallFlags CFlags, 5568 const SmallVectorImpl<ISD::OutputArg> &Outs, 5569 const SmallVectorImpl<SDValue> &OutVals, 5570 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5571 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5572 const CallBase *CB) const { 5573 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5574 // of the 32-bit SVR4 ABI stack frame layout. 5575 5576 const CallingConv::ID CallConv = CFlags.CallConv; 5577 const bool IsVarArg = CFlags.IsVarArg; 5578 const bool IsTailCall = CFlags.IsTailCall; 5579 5580 assert((CallConv == CallingConv::C || 5581 CallConv == CallingConv::Cold || 5582 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5583 5584 const Align PtrAlign(4); 5585 5586 MachineFunction &MF = DAG.getMachineFunction(); 5587 5588 // Mark this function as potentially containing a function that contains a 5589 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5590 // and restoring the callers stack pointer in this functions epilog. This is 5591 // done because by tail calling the called function might overwrite the value 5592 // in this function's (MF) stack pointer stack slot 0(SP). 5593 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5594 CallConv == CallingConv::Fast) 5595 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5596 5597 // Count how many bytes are to be pushed on the stack, including the linkage 5598 // area, parameter list area and the part of the local variable space which 5599 // contains copies of aggregates which are passed by value. 5600 5601 // Assign locations to all of the outgoing arguments. 5602 SmallVector<CCValAssign, 16> ArgLocs; 5603 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5604 5605 // Reserve space for the linkage area on the stack. 5606 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5607 PtrAlign); 5608 if (useSoftFloat()) 5609 CCInfo.PreAnalyzeCallOperands(Outs); 5610 5611 if (IsVarArg) { 5612 // Handle fixed and variable vector arguments differently. 5613 // Fixed vector arguments go into registers as long as registers are 5614 // available. Variable vector arguments always go into memory. 5615 unsigned NumArgs = Outs.size(); 5616 5617 for (unsigned i = 0; i != NumArgs; ++i) { 5618 MVT ArgVT = Outs[i].VT; 5619 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5620 bool Result; 5621 5622 if (Outs[i].IsFixed) { 5623 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5624 CCInfo); 5625 } else { 5626 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5627 ArgFlags, CCInfo); 5628 } 5629 5630 if (Result) { 5631 #ifndef NDEBUG 5632 errs() << "Call operand #" << i << " has unhandled type " 5633 << EVT(ArgVT).getEVTString() << "\n"; 5634 #endif 5635 llvm_unreachable(nullptr); 5636 } 5637 } 5638 } else { 5639 // All arguments are treated the same. 5640 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5641 } 5642 CCInfo.clearWasPPCF128(); 5643 5644 // Assign locations to all of the outgoing aggregate by value arguments. 5645 SmallVector<CCValAssign, 16> ByValArgLocs; 5646 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5647 5648 // Reserve stack space for the allocations in CCInfo. 5649 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5650 5651 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5652 5653 // Size of the linkage area, parameter list area and the part of the local 5654 // space variable where copies of aggregates which are passed by value are 5655 // stored. 5656 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5657 5658 // Calculate by how many bytes the stack has to be adjusted in case of tail 5659 // call optimization. 5660 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5661 5662 // Adjust the stack pointer for the new arguments... 5663 // These operations are automatically eliminated by the prolog/epilog pass 5664 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5665 SDValue CallSeqStart = Chain; 5666 5667 // Load the return address and frame pointer so it can be moved somewhere else 5668 // later. 5669 SDValue LROp, FPOp; 5670 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5671 5672 // Set up a copy of the stack pointer for use loading and storing any 5673 // arguments that may not fit in the registers available for argument 5674 // passing. 5675 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5676 5677 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5678 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5679 SmallVector<SDValue, 8> MemOpChains; 5680 5681 bool seenFloatArg = false; 5682 // Walk the register/memloc assignments, inserting copies/loads. 5683 // i - Tracks the index into the list of registers allocated for the call 5684 // RealArgIdx - Tracks the index into the list of actual function arguments 5685 // j - Tracks the index into the list of byval arguments 5686 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5687 i != e; 5688 ++i, ++RealArgIdx) { 5689 CCValAssign &VA = ArgLocs[i]; 5690 SDValue Arg = OutVals[RealArgIdx]; 5691 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5692 5693 if (Flags.isByVal()) { 5694 // Argument is an aggregate which is passed by value, thus we need to 5695 // create a copy of it in the local variable space of the current stack 5696 // frame (which is the stack frame of the caller) and pass the address of 5697 // this copy to the callee. 5698 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5699 CCValAssign &ByValVA = ByValArgLocs[j++]; 5700 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5701 5702 // Memory reserved in the local variable space of the callers stack frame. 5703 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5704 5705 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5706 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5707 StackPtr, PtrOff); 5708 5709 // Create a copy of the argument in the local area of the current 5710 // stack frame. 5711 SDValue MemcpyCall = 5712 CreateCopyOfByValArgument(Arg, PtrOff, 5713 CallSeqStart.getNode()->getOperand(0), 5714 Flags, DAG, dl); 5715 5716 // This must go outside the CALLSEQ_START..END. 5717 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5718 SDLoc(MemcpyCall)); 5719 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5720 NewCallSeqStart.getNode()); 5721 Chain = CallSeqStart = NewCallSeqStart; 5722 5723 // Pass the address of the aggregate copy on the stack either in a 5724 // physical register or in the parameter list area of the current stack 5725 // frame to the callee. 5726 Arg = PtrOff; 5727 } 5728 5729 // When useCRBits() is true, there can be i1 arguments. 5730 // It is because getRegisterType(MVT::i1) => MVT::i1, 5731 // and for other integer types getRegisterType() => MVT::i32. 5732 // Extend i1 and ensure callee will get i32. 5733 if (Arg.getValueType() == MVT::i1) 5734 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5735 dl, MVT::i32, Arg); 5736 5737 if (VA.isRegLoc()) { 5738 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5739 // Put argument in a physical register. 5740 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5741 bool IsLE = Subtarget.isLittleEndian(); 5742 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5743 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5744 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5745 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5746 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5747 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5748 SVal.getValue(0))); 5749 } else 5750 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5751 } else { 5752 // Put argument in the parameter list area of the current stack frame. 5753 assert(VA.isMemLoc()); 5754 unsigned LocMemOffset = VA.getLocMemOffset(); 5755 5756 if (!IsTailCall) { 5757 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5758 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5759 StackPtr, PtrOff); 5760 5761 MemOpChains.push_back( 5762 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5763 } else { 5764 // Calculate and remember argument location. 5765 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5766 TailCallArguments); 5767 } 5768 } 5769 } 5770 5771 if (!MemOpChains.empty()) 5772 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5773 5774 // Build a sequence of copy-to-reg nodes chained together with token chain 5775 // and flag operands which copy the outgoing args into the appropriate regs. 5776 SDValue InFlag; 5777 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5778 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5779 RegsToPass[i].second, InFlag); 5780 InFlag = Chain.getValue(1); 5781 } 5782 5783 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5784 // registers. 5785 if (IsVarArg) { 5786 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5787 SDValue Ops[] = { Chain, InFlag }; 5788 5789 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5790 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5791 5792 InFlag = Chain.getValue(1); 5793 } 5794 5795 if (IsTailCall) 5796 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5797 TailCallArguments); 5798 5799 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5800 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5801 } 5802 5803 // Copy an argument into memory, being careful to do this outside the 5804 // call sequence for the call to which the argument belongs. 5805 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5806 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5807 SelectionDAG &DAG, const SDLoc &dl) const { 5808 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5809 CallSeqStart.getNode()->getOperand(0), 5810 Flags, DAG, dl); 5811 // The MEMCPY must go outside the CALLSEQ_START..END. 5812 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5813 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5814 SDLoc(MemcpyCall)); 5815 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5816 NewCallSeqStart.getNode()); 5817 return NewCallSeqStart; 5818 } 5819 5820 SDValue PPCTargetLowering::LowerCall_64SVR4( 5821 SDValue Chain, SDValue Callee, CallFlags CFlags, 5822 const SmallVectorImpl<ISD::OutputArg> &Outs, 5823 const SmallVectorImpl<SDValue> &OutVals, 5824 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5825 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5826 const CallBase *CB) const { 5827 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5828 bool isLittleEndian = Subtarget.isLittleEndian(); 5829 unsigned NumOps = Outs.size(); 5830 bool IsSibCall = false; 5831 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5832 5833 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5834 unsigned PtrByteSize = 8; 5835 5836 MachineFunction &MF = DAG.getMachineFunction(); 5837 5838 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5839 IsSibCall = true; 5840 5841 // Mark this function as potentially containing a function that contains a 5842 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5843 // and restoring the callers stack pointer in this functions epilog. This is 5844 // done because by tail calling the called function might overwrite the value 5845 // in this function's (MF) stack pointer stack slot 0(SP). 5846 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5847 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5848 5849 assert(!(IsFastCall && CFlags.IsVarArg) && 5850 "fastcc not supported on varargs functions"); 5851 5852 // Count how many bytes are to be pushed on the stack, including the linkage 5853 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5854 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5855 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5856 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5857 unsigned NumBytes = LinkageSize; 5858 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5859 5860 static const MCPhysReg GPR[] = { 5861 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5862 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5863 }; 5864 static const MCPhysReg VR[] = { 5865 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5866 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5867 }; 5868 5869 const unsigned NumGPRs = array_lengthof(GPR); 5870 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5871 const unsigned NumVRs = array_lengthof(VR); 5872 5873 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5874 // can be passed to the callee in registers. 5875 // For the fast calling convention, there is another check below. 5876 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5877 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5878 if (!HasParameterArea) { 5879 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5880 unsigned AvailableFPRs = NumFPRs; 5881 unsigned AvailableVRs = NumVRs; 5882 unsigned NumBytesTmp = NumBytes; 5883 for (unsigned i = 0; i != NumOps; ++i) { 5884 if (Outs[i].Flags.isNest()) continue; 5885 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5886 PtrByteSize, LinkageSize, ParamAreaSize, 5887 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5888 HasParameterArea = true; 5889 } 5890 } 5891 5892 // When using the fast calling convention, we don't provide backing for 5893 // arguments that will be in registers. 5894 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5895 5896 // Avoid allocating parameter area for fastcc functions if all the arguments 5897 // can be passed in the registers. 5898 if (IsFastCall) 5899 HasParameterArea = false; 5900 5901 // Add up all the space actually used. 5902 for (unsigned i = 0; i != NumOps; ++i) { 5903 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5904 EVT ArgVT = Outs[i].VT; 5905 EVT OrigVT = Outs[i].ArgVT; 5906 5907 if (Flags.isNest()) 5908 continue; 5909 5910 if (IsFastCall) { 5911 if (Flags.isByVal()) { 5912 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5913 if (NumGPRsUsed > NumGPRs) 5914 HasParameterArea = true; 5915 } else { 5916 switch (ArgVT.getSimpleVT().SimpleTy) { 5917 default: llvm_unreachable("Unexpected ValueType for argument!"); 5918 case MVT::i1: 5919 case MVT::i32: 5920 case MVT::i64: 5921 if (++NumGPRsUsed <= NumGPRs) 5922 continue; 5923 break; 5924 case MVT::v4i32: 5925 case MVT::v8i16: 5926 case MVT::v16i8: 5927 case MVT::v2f64: 5928 case MVT::v2i64: 5929 case MVT::v1i128: 5930 case MVT::f128: 5931 if (++NumVRsUsed <= NumVRs) 5932 continue; 5933 break; 5934 case MVT::v4f32: 5935 if (++NumVRsUsed <= NumVRs) 5936 continue; 5937 break; 5938 case MVT::f32: 5939 case MVT::f64: 5940 if (++NumFPRsUsed <= NumFPRs) 5941 continue; 5942 break; 5943 } 5944 HasParameterArea = true; 5945 } 5946 } 5947 5948 /* Respect alignment of argument on the stack. */ 5949 auto Alignement = 5950 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5951 NumBytes = alignTo(NumBytes, Alignement); 5952 5953 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5954 if (Flags.isInConsecutiveRegsLast()) 5955 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5956 } 5957 5958 unsigned NumBytesActuallyUsed = NumBytes; 5959 5960 // In the old ELFv1 ABI, 5961 // the prolog code of the callee may store up to 8 GPR argument registers to 5962 // the stack, allowing va_start to index over them in memory if its varargs. 5963 // Because we cannot tell if this is needed on the caller side, we have to 5964 // conservatively assume that it is needed. As such, make sure we have at 5965 // least enough stack space for the caller to store the 8 GPRs. 5966 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5967 // really requires memory operands, e.g. a vararg function. 5968 if (HasParameterArea) 5969 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5970 else 5971 NumBytes = LinkageSize; 5972 5973 // Tail call needs the stack to be aligned. 5974 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5975 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5976 5977 int SPDiff = 0; 5978 5979 // Calculate by how many bytes the stack has to be adjusted in case of tail 5980 // call optimization. 5981 if (!IsSibCall) 5982 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5983 5984 // To protect arguments on the stack from being clobbered in a tail call, 5985 // force all the loads to happen before doing any other lowering. 5986 if (CFlags.IsTailCall) 5987 Chain = DAG.getStackArgumentTokenFactor(Chain); 5988 5989 // Adjust the stack pointer for the new arguments... 5990 // These operations are automatically eliminated by the prolog/epilog pass 5991 if (!IsSibCall) 5992 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5993 SDValue CallSeqStart = Chain; 5994 5995 // Load the return address and frame pointer so it can be move somewhere else 5996 // later. 5997 SDValue LROp, FPOp; 5998 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5999 6000 // Set up a copy of the stack pointer for use loading and storing any 6001 // arguments that may not fit in the registers available for argument 6002 // passing. 6003 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6004 6005 // Figure out which arguments are going to go in registers, and which in 6006 // memory. Also, if this is a vararg function, floating point operations 6007 // must be stored to our stack, and loaded into integer regs as well, if 6008 // any integer regs are available for argument passing. 6009 unsigned ArgOffset = LinkageSize; 6010 6011 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6012 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6013 6014 SmallVector<SDValue, 8> MemOpChains; 6015 for (unsigned i = 0; i != NumOps; ++i) { 6016 SDValue Arg = OutVals[i]; 6017 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6018 EVT ArgVT = Outs[i].VT; 6019 EVT OrigVT = Outs[i].ArgVT; 6020 6021 // PtrOff will be used to store the current argument to the stack if a 6022 // register cannot be found for it. 6023 SDValue PtrOff; 6024 6025 // We re-align the argument offset for each argument, except when using the 6026 // fast calling convention, when we need to make sure we do that only when 6027 // we'll actually use a stack slot. 6028 auto ComputePtrOff = [&]() { 6029 /* Respect alignment of argument on the stack. */ 6030 auto Alignment = 6031 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6032 ArgOffset = alignTo(ArgOffset, Alignment); 6033 6034 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6035 6036 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6037 }; 6038 6039 if (!IsFastCall) { 6040 ComputePtrOff(); 6041 6042 /* Compute GPR index associated with argument offset. */ 6043 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6044 GPR_idx = std::min(GPR_idx, NumGPRs); 6045 } 6046 6047 // Promote integers to 64-bit values. 6048 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6049 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6050 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6051 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6052 } 6053 6054 // FIXME memcpy is used way more than necessary. Correctness first. 6055 // Note: "by value" is code for passing a structure by value, not 6056 // basic types. 6057 if (Flags.isByVal()) { 6058 // Note: Size includes alignment padding, so 6059 // struct x { short a; char b; } 6060 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6061 // These are the proper values we need for right-justifying the 6062 // aggregate in a parameter register. 6063 unsigned Size = Flags.getByValSize(); 6064 6065 // An empty aggregate parameter takes up no storage and no 6066 // registers. 6067 if (Size == 0) 6068 continue; 6069 6070 if (IsFastCall) 6071 ComputePtrOff(); 6072 6073 // All aggregates smaller than 8 bytes must be passed right-justified. 6074 if (Size==1 || Size==2 || Size==4) { 6075 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6076 if (GPR_idx != NumGPRs) { 6077 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6078 MachinePointerInfo(), VT); 6079 MemOpChains.push_back(Load.getValue(1)); 6080 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6081 6082 ArgOffset += PtrByteSize; 6083 continue; 6084 } 6085 } 6086 6087 if (GPR_idx == NumGPRs && Size < 8) { 6088 SDValue AddPtr = PtrOff; 6089 if (!isLittleEndian) { 6090 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6091 PtrOff.getValueType()); 6092 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6093 } 6094 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6095 CallSeqStart, 6096 Flags, DAG, dl); 6097 ArgOffset += PtrByteSize; 6098 continue; 6099 } 6100 // Copy entire object into memory. There are cases where gcc-generated 6101 // code assumes it is there, even if it could be put entirely into 6102 // registers. (This is not what the doc says.) 6103 6104 // FIXME: The above statement is likely due to a misunderstanding of the 6105 // documents. All arguments must be copied into the parameter area BY 6106 // THE CALLEE in the event that the callee takes the address of any 6107 // formal argument. That has not yet been implemented. However, it is 6108 // reasonable to use the stack area as a staging area for the register 6109 // load. 6110 6111 // Skip this for small aggregates, as we will use the same slot for a 6112 // right-justified copy, below. 6113 if (Size >= 8) 6114 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6115 CallSeqStart, 6116 Flags, DAG, dl); 6117 6118 // When a register is available, pass a small aggregate right-justified. 6119 if (Size < 8 && GPR_idx != NumGPRs) { 6120 // The easiest way to get this right-justified in a register 6121 // is to copy the structure into the rightmost portion of a 6122 // local variable slot, then load the whole slot into the 6123 // register. 6124 // FIXME: The memcpy seems to produce pretty awful code for 6125 // small aggregates, particularly for packed ones. 6126 // FIXME: It would be preferable to use the slot in the 6127 // parameter save area instead of a new local variable. 6128 SDValue AddPtr = PtrOff; 6129 if (!isLittleEndian) { 6130 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6131 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6132 } 6133 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6134 CallSeqStart, 6135 Flags, DAG, dl); 6136 6137 // Load the slot into the register. 6138 SDValue Load = 6139 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6140 MemOpChains.push_back(Load.getValue(1)); 6141 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6142 6143 // Done with this argument. 6144 ArgOffset += PtrByteSize; 6145 continue; 6146 } 6147 6148 // For aggregates larger than PtrByteSize, copy the pieces of the 6149 // object that fit into registers from the parameter save area. 6150 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6151 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6152 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6153 if (GPR_idx != NumGPRs) { 6154 SDValue Load = 6155 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6156 MemOpChains.push_back(Load.getValue(1)); 6157 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6158 ArgOffset += PtrByteSize; 6159 } else { 6160 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6161 break; 6162 } 6163 } 6164 continue; 6165 } 6166 6167 switch (Arg.getSimpleValueType().SimpleTy) { 6168 default: llvm_unreachable("Unexpected ValueType for argument!"); 6169 case MVT::i1: 6170 case MVT::i32: 6171 case MVT::i64: 6172 if (Flags.isNest()) { 6173 // The 'nest' parameter, if any, is passed in R11. 6174 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6175 break; 6176 } 6177 6178 // These can be scalar arguments or elements of an integer array type 6179 // passed directly. Clang may use those instead of "byval" aggregate 6180 // types to avoid forcing arguments to memory unnecessarily. 6181 if (GPR_idx != NumGPRs) { 6182 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6183 } else { 6184 if (IsFastCall) 6185 ComputePtrOff(); 6186 6187 assert(HasParameterArea && 6188 "Parameter area must exist to pass an argument in memory."); 6189 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6190 true, CFlags.IsTailCall, false, MemOpChains, 6191 TailCallArguments, dl); 6192 if (IsFastCall) 6193 ArgOffset += PtrByteSize; 6194 } 6195 if (!IsFastCall) 6196 ArgOffset += PtrByteSize; 6197 break; 6198 case MVT::f32: 6199 case MVT::f64: { 6200 // These can be scalar arguments or elements of a float array type 6201 // passed directly. The latter are used to implement ELFv2 homogenous 6202 // float aggregates. 6203 6204 // Named arguments go into FPRs first, and once they overflow, the 6205 // remaining arguments go into GPRs and then the parameter save area. 6206 // Unnamed arguments for vararg functions always go to GPRs and 6207 // then the parameter save area. For now, put all arguments to vararg 6208 // routines always in both locations (FPR *and* GPR or stack slot). 6209 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6210 bool NeededLoad = false; 6211 6212 // First load the argument into the next available FPR. 6213 if (FPR_idx != NumFPRs) 6214 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6215 6216 // Next, load the argument into GPR or stack slot if needed. 6217 if (!NeedGPROrStack) 6218 ; 6219 else if (GPR_idx != NumGPRs && !IsFastCall) { 6220 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6221 // once we support fp <-> gpr moves. 6222 6223 // In the non-vararg case, this can only ever happen in the 6224 // presence of f32 array types, since otherwise we never run 6225 // out of FPRs before running out of GPRs. 6226 SDValue ArgVal; 6227 6228 // Double values are always passed in a single GPR. 6229 if (Arg.getValueType() != MVT::f32) { 6230 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6231 6232 // Non-array float values are extended and passed in a GPR. 6233 } else if (!Flags.isInConsecutiveRegs()) { 6234 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6235 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6236 6237 // If we have an array of floats, we collect every odd element 6238 // together with its predecessor into one GPR. 6239 } else if (ArgOffset % PtrByteSize != 0) { 6240 SDValue Lo, Hi; 6241 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6242 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6243 if (!isLittleEndian) 6244 std::swap(Lo, Hi); 6245 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6246 6247 // The final element, if even, goes into the first half of a GPR. 6248 } else if (Flags.isInConsecutiveRegsLast()) { 6249 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6250 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6251 if (!isLittleEndian) 6252 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6253 DAG.getConstant(32, dl, MVT::i32)); 6254 6255 // Non-final even elements are skipped; they will be handled 6256 // together the with subsequent argument on the next go-around. 6257 } else 6258 ArgVal = SDValue(); 6259 6260 if (ArgVal.getNode()) 6261 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6262 } else { 6263 if (IsFastCall) 6264 ComputePtrOff(); 6265 6266 // Single-precision floating-point values are mapped to the 6267 // second (rightmost) word of the stack doubleword. 6268 if (Arg.getValueType() == MVT::f32 && 6269 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6270 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6271 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6272 } 6273 6274 assert(HasParameterArea && 6275 "Parameter area must exist to pass an argument in memory."); 6276 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6277 true, CFlags.IsTailCall, false, MemOpChains, 6278 TailCallArguments, dl); 6279 6280 NeededLoad = true; 6281 } 6282 // When passing an array of floats, the array occupies consecutive 6283 // space in the argument area; only round up to the next doubleword 6284 // at the end of the array. Otherwise, each float takes 8 bytes. 6285 if (!IsFastCall || NeededLoad) { 6286 ArgOffset += (Arg.getValueType() == MVT::f32 && 6287 Flags.isInConsecutiveRegs()) ? 4 : 8; 6288 if (Flags.isInConsecutiveRegsLast()) 6289 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6290 } 6291 break; 6292 } 6293 case MVT::v4f32: 6294 case MVT::v4i32: 6295 case MVT::v8i16: 6296 case MVT::v16i8: 6297 case MVT::v2f64: 6298 case MVT::v2i64: 6299 case MVT::v1i128: 6300 case MVT::f128: 6301 // These can be scalar arguments or elements of a vector array type 6302 // passed directly. The latter are used to implement ELFv2 homogenous 6303 // vector aggregates. 6304 6305 // For a varargs call, named arguments go into VRs or on the stack as 6306 // usual; unnamed arguments always go to the stack or the corresponding 6307 // GPRs when within range. For now, we always put the value in both 6308 // locations (or even all three). 6309 if (CFlags.IsVarArg) { 6310 assert(HasParameterArea && 6311 "Parameter area must exist if we have a varargs call."); 6312 // We could elide this store in the case where the object fits 6313 // entirely in R registers. Maybe later. 6314 SDValue Store = 6315 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6316 MemOpChains.push_back(Store); 6317 if (VR_idx != NumVRs) { 6318 SDValue Load = 6319 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6320 MemOpChains.push_back(Load.getValue(1)); 6321 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6322 } 6323 ArgOffset += 16; 6324 for (unsigned i=0; i<16; i+=PtrByteSize) { 6325 if (GPR_idx == NumGPRs) 6326 break; 6327 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6328 DAG.getConstant(i, dl, PtrVT)); 6329 SDValue Load = 6330 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6331 MemOpChains.push_back(Load.getValue(1)); 6332 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6333 } 6334 break; 6335 } 6336 6337 // Non-varargs Altivec params go into VRs or on the stack. 6338 if (VR_idx != NumVRs) { 6339 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6340 } else { 6341 if (IsFastCall) 6342 ComputePtrOff(); 6343 6344 assert(HasParameterArea && 6345 "Parameter area must exist to pass an argument in memory."); 6346 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6347 true, CFlags.IsTailCall, true, MemOpChains, 6348 TailCallArguments, dl); 6349 if (IsFastCall) 6350 ArgOffset += 16; 6351 } 6352 6353 if (!IsFastCall) 6354 ArgOffset += 16; 6355 break; 6356 } 6357 } 6358 6359 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6360 "mismatch in size of parameter area"); 6361 (void)NumBytesActuallyUsed; 6362 6363 if (!MemOpChains.empty()) 6364 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6365 6366 // Check if this is an indirect call (MTCTR/BCTRL). 6367 // See prepareDescriptorIndirectCall and buildCallOperands for more 6368 // information about calls through function pointers in the 64-bit SVR4 ABI. 6369 if (CFlags.IsIndirect) { 6370 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6371 // caller in the TOC save area. 6372 if (isTOCSaveRestoreRequired(Subtarget)) { 6373 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6374 // Load r2 into a virtual register and store it to the TOC save area. 6375 setUsesTOCBasePtr(DAG); 6376 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6377 // TOC save area offset. 6378 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6379 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6380 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6381 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6382 MachinePointerInfo::getStack( 6383 DAG.getMachineFunction(), TOCSaveOffset)); 6384 } 6385 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6386 // This does not mean the MTCTR instruction must use R12; it's easier 6387 // to model this as an extra parameter, so do that. 6388 if (isELFv2ABI && !CFlags.IsPatchPoint) 6389 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6390 } 6391 6392 // Build a sequence of copy-to-reg nodes chained together with token chain 6393 // and flag operands which copy the outgoing args into the appropriate regs. 6394 SDValue InFlag; 6395 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6396 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6397 RegsToPass[i].second, InFlag); 6398 InFlag = Chain.getValue(1); 6399 } 6400 6401 if (CFlags.IsTailCall && !IsSibCall) 6402 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6403 TailCallArguments); 6404 6405 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6406 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6407 } 6408 6409 SDValue PPCTargetLowering::LowerCall_Darwin( 6410 SDValue Chain, SDValue Callee, CallFlags CFlags, 6411 const SmallVectorImpl<ISD::OutputArg> &Outs, 6412 const SmallVectorImpl<SDValue> &OutVals, 6413 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6414 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6415 const CallBase *CB) const { 6416 unsigned NumOps = Outs.size(); 6417 6418 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6419 bool isPPC64 = PtrVT == MVT::i64; 6420 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6421 6422 MachineFunction &MF = DAG.getMachineFunction(); 6423 6424 // Mark this function as potentially containing a function that contains a 6425 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6426 // and restoring the callers stack pointer in this functions epilog. This is 6427 // done because by tail calling the called function might overwrite the value 6428 // in this function's (MF) stack pointer stack slot 0(SP). 6429 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6430 CFlags.CallConv == CallingConv::Fast) 6431 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6432 6433 // Count how many bytes are to be pushed on the stack, including the linkage 6434 // area, and parameter passing area. We start with 24/48 bytes, which is 6435 // prereserved space for [SP][CR][LR][3 x unused]. 6436 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6437 unsigned NumBytes = LinkageSize; 6438 6439 // Add up all the space actually used. 6440 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6441 // they all go in registers, but we must reserve stack space for them for 6442 // possible use by the caller. In varargs or 64-bit calls, parameters are 6443 // assigned stack space in order, with padding so Altivec parameters are 6444 // 16-byte aligned. 6445 unsigned nAltivecParamsAtEnd = 0; 6446 for (unsigned i = 0; i != NumOps; ++i) { 6447 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6448 EVT ArgVT = Outs[i].VT; 6449 // Varargs Altivec parameters are padded to a 16 byte boundary. 6450 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6451 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6452 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6453 if (!CFlags.IsVarArg && !isPPC64) { 6454 // Non-varargs Altivec parameters go after all the non-Altivec 6455 // parameters; handle those later so we know how much padding we need. 6456 nAltivecParamsAtEnd++; 6457 continue; 6458 } 6459 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6460 NumBytes = ((NumBytes+15)/16)*16; 6461 } 6462 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6463 } 6464 6465 // Allow for Altivec parameters at the end, if needed. 6466 if (nAltivecParamsAtEnd) { 6467 NumBytes = ((NumBytes+15)/16)*16; 6468 NumBytes += 16*nAltivecParamsAtEnd; 6469 } 6470 6471 // The prolog code of the callee may store up to 8 GPR argument registers to 6472 // the stack, allowing va_start to index over them in memory if its varargs. 6473 // Because we cannot tell if this is needed on the caller side, we have to 6474 // conservatively assume that it is needed. As such, make sure we have at 6475 // least enough stack space for the caller to store the 8 GPRs. 6476 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6477 6478 // Tail call needs the stack to be aligned. 6479 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6480 CFlags.CallConv == CallingConv::Fast) 6481 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6482 6483 // Calculate by how many bytes the stack has to be adjusted in case of tail 6484 // call optimization. 6485 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6486 6487 // To protect arguments on the stack from being clobbered in a tail call, 6488 // force all the loads to happen before doing any other lowering. 6489 if (CFlags.IsTailCall) 6490 Chain = DAG.getStackArgumentTokenFactor(Chain); 6491 6492 // Adjust the stack pointer for the new arguments... 6493 // These operations are automatically eliminated by the prolog/epilog pass 6494 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6495 SDValue CallSeqStart = Chain; 6496 6497 // Load the return address and frame pointer so it can be move somewhere else 6498 // later. 6499 SDValue LROp, FPOp; 6500 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6501 6502 // Set up a copy of the stack pointer for use loading and storing any 6503 // arguments that may not fit in the registers available for argument 6504 // passing. 6505 SDValue StackPtr; 6506 if (isPPC64) 6507 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6508 else 6509 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6510 6511 // Figure out which arguments are going to go in registers, and which in 6512 // memory. Also, if this is a vararg function, floating point operations 6513 // must be stored to our stack, and loaded into integer regs as well, if 6514 // any integer regs are available for argument passing. 6515 unsigned ArgOffset = LinkageSize; 6516 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6517 6518 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6519 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6520 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6521 }; 6522 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6523 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6524 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6525 }; 6526 static const MCPhysReg VR[] = { 6527 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6528 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6529 }; 6530 const unsigned NumGPRs = array_lengthof(GPR_32); 6531 const unsigned NumFPRs = 13; 6532 const unsigned NumVRs = array_lengthof(VR); 6533 6534 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6535 6536 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6537 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6538 6539 SmallVector<SDValue, 8> MemOpChains; 6540 for (unsigned i = 0; i != NumOps; ++i) { 6541 SDValue Arg = OutVals[i]; 6542 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6543 6544 // PtrOff will be used to store the current argument to the stack if a 6545 // register cannot be found for it. 6546 SDValue PtrOff; 6547 6548 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6549 6550 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6551 6552 // On PPC64, promote integers to 64-bit values. 6553 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6554 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6555 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6556 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6557 } 6558 6559 // FIXME memcpy is used way more than necessary. Correctness first. 6560 // Note: "by value" is code for passing a structure by value, not 6561 // basic types. 6562 if (Flags.isByVal()) { 6563 unsigned Size = Flags.getByValSize(); 6564 // Very small objects are passed right-justified. Everything else is 6565 // passed left-justified. 6566 if (Size==1 || Size==2) { 6567 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6568 if (GPR_idx != NumGPRs) { 6569 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6570 MachinePointerInfo(), VT); 6571 MemOpChains.push_back(Load.getValue(1)); 6572 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6573 6574 ArgOffset += PtrByteSize; 6575 } else { 6576 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6577 PtrOff.getValueType()); 6578 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6579 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6580 CallSeqStart, 6581 Flags, DAG, dl); 6582 ArgOffset += PtrByteSize; 6583 } 6584 continue; 6585 } 6586 // Copy entire object into memory. There are cases where gcc-generated 6587 // code assumes it is there, even if it could be put entirely into 6588 // registers. (This is not what the doc says.) 6589 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6590 CallSeqStart, 6591 Flags, DAG, dl); 6592 6593 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6594 // copy the pieces of the object that fit into registers from the 6595 // parameter save area. 6596 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6597 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6598 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6599 if (GPR_idx != NumGPRs) { 6600 SDValue Load = 6601 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6602 MemOpChains.push_back(Load.getValue(1)); 6603 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6604 ArgOffset += PtrByteSize; 6605 } else { 6606 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6607 break; 6608 } 6609 } 6610 continue; 6611 } 6612 6613 switch (Arg.getSimpleValueType().SimpleTy) { 6614 default: llvm_unreachable("Unexpected ValueType for argument!"); 6615 case MVT::i1: 6616 case MVT::i32: 6617 case MVT::i64: 6618 if (GPR_idx != NumGPRs) { 6619 if (Arg.getValueType() == MVT::i1) 6620 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6621 6622 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6623 } else { 6624 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6625 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6626 TailCallArguments, dl); 6627 } 6628 ArgOffset += PtrByteSize; 6629 break; 6630 case MVT::f32: 6631 case MVT::f64: 6632 if (FPR_idx != NumFPRs) { 6633 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6634 6635 if (CFlags.IsVarArg) { 6636 SDValue Store = 6637 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6638 MemOpChains.push_back(Store); 6639 6640 // Float varargs are always shadowed in available integer registers 6641 if (GPR_idx != NumGPRs) { 6642 SDValue Load = 6643 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6644 MemOpChains.push_back(Load.getValue(1)); 6645 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6646 } 6647 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6648 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6649 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6650 SDValue Load = 6651 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6652 MemOpChains.push_back(Load.getValue(1)); 6653 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6654 } 6655 } else { 6656 // If we have any FPRs remaining, we may also have GPRs remaining. 6657 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6658 // GPRs. 6659 if (GPR_idx != NumGPRs) 6660 ++GPR_idx; 6661 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6662 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6663 ++GPR_idx; 6664 } 6665 } else 6666 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6667 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6668 TailCallArguments, dl); 6669 if (isPPC64) 6670 ArgOffset += 8; 6671 else 6672 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6673 break; 6674 case MVT::v4f32: 6675 case MVT::v4i32: 6676 case MVT::v8i16: 6677 case MVT::v16i8: 6678 if (CFlags.IsVarArg) { 6679 // These go aligned on the stack, or in the corresponding R registers 6680 // when within range. The Darwin PPC ABI doc claims they also go in 6681 // V registers; in fact gcc does this only for arguments that are 6682 // prototyped, not for those that match the ... We do it for all 6683 // arguments, seems to work. 6684 while (ArgOffset % 16 !=0) { 6685 ArgOffset += PtrByteSize; 6686 if (GPR_idx != NumGPRs) 6687 GPR_idx++; 6688 } 6689 // We could elide this store in the case where the object fits 6690 // entirely in R registers. Maybe later. 6691 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6692 DAG.getConstant(ArgOffset, dl, PtrVT)); 6693 SDValue Store = 6694 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6695 MemOpChains.push_back(Store); 6696 if (VR_idx != NumVRs) { 6697 SDValue Load = 6698 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6699 MemOpChains.push_back(Load.getValue(1)); 6700 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6701 } 6702 ArgOffset += 16; 6703 for (unsigned i=0; i<16; i+=PtrByteSize) { 6704 if (GPR_idx == NumGPRs) 6705 break; 6706 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6707 DAG.getConstant(i, dl, PtrVT)); 6708 SDValue Load = 6709 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6710 MemOpChains.push_back(Load.getValue(1)); 6711 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6712 } 6713 break; 6714 } 6715 6716 // Non-varargs Altivec params generally go in registers, but have 6717 // stack space allocated at the end. 6718 if (VR_idx != NumVRs) { 6719 // Doesn't have GPR space allocated. 6720 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6721 } else if (nAltivecParamsAtEnd==0) { 6722 // We are emitting Altivec params in order. 6723 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6724 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6725 TailCallArguments, dl); 6726 ArgOffset += 16; 6727 } 6728 break; 6729 } 6730 } 6731 // If all Altivec parameters fit in registers, as they usually do, 6732 // they get stack space following the non-Altivec parameters. We 6733 // don't track this here because nobody below needs it. 6734 // If there are more Altivec parameters than fit in registers emit 6735 // the stores here. 6736 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6737 unsigned j = 0; 6738 // Offset is aligned; skip 1st 12 params which go in V registers. 6739 ArgOffset = ((ArgOffset+15)/16)*16; 6740 ArgOffset += 12*16; 6741 for (unsigned i = 0; i != NumOps; ++i) { 6742 SDValue Arg = OutVals[i]; 6743 EVT ArgType = Outs[i].VT; 6744 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6745 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6746 if (++j > NumVRs) { 6747 SDValue PtrOff; 6748 // We are emitting Altivec params in order. 6749 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6750 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6751 TailCallArguments, dl); 6752 ArgOffset += 16; 6753 } 6754 } 6755 } 6756 } 6757 6758 if (!MemOpChains.empty()) 6759 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6760 6761 // On Darwin, R12 must contain the address of an indirect callee. This does 6762 // not mean the MTCTR instruction must use R12; it's easier to model this as 6763 // an extra parameter, so do that. 6764 if (CFlags.IsIndirect) { 6765 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6766 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6767 PPC::R12), Callee)); 6768 } 6769 6770 // Build a sequence of copy-to-reg nodes chained together with token chain 6771 // and flag operands which copy the outgoing args into the appropriate regs. 6772 SDValue InFlag; 6773 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6774 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6775 RegsToPass[i].second, InFlag); 6776 InFlag = Chain.getValue(1); 6777 } 6778 6779 if (CFlags.IsTailCall) 6780 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6781 TailCallArguments); 6782 6783 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6784 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6785 } 6786 6787 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6788 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6789 CCState &State) { 6790 6791 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6792 State.getMachineFunction().getSubtarget()); 6793 const bool IsPPC64 = Subtarget.isPPC64(); 6794 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6795 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6796 6797 assert((!ValVT.isInteger() || 6798 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6799 "Integer argument exceeds register size: should have been legalized"); 6800 6801 if (ValVT == MVT::f128) 6802 report_fatal_error("f128 is unimplemented on AIX."); 6803 6804 if (ArgFlags.isNest()) 6805 report_fatal_error("Nest arguments are unimplemented."); 6806 6807 if (ValVT.isVector() || LocVT.isVector()) 6808 report_fatal_error("Vector arguments are unimplemented on AIX."); 6809 6810 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6811 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6812 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6813 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6814 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6815 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6816 6817 if (ArgFlags.isByVal()) { 6818 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6819 report_fatal_error("Pass-by-value arguments with alignment greater than " 6820 "register width are not supported."); 6821 6822 const unsigned ByValSize = ArgFlags.getByValSize(); 6823 6824 // An empty aggregate parameter takes up no storage and no registers, 6825 // but needs a MemLoc for a stack slot for the formal arguments side. 6826 if (ByValSize == 0) { 6827 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6828 State.getNextStackOffset(), RegVT, 6829 LocInfo)); 6830 return false; 6831 } 6832 6833 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6834 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6835 for (const unsigned E = Offset + StackSize; Offset < E; 6836 Offset += PtrAlign.value()) { 6837 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6838 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6839 else { 6840 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6841 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6842 LocInfo)); 6843 break; 6844 } 6845 } 6846 return false; 6847 } 6848 6849 // Arguments always reserve parameter save area. 6850 switch (ValVT.SimpleTy) { 6851 default: 6852 report_fatal_error("Unhandled value type for argument."); 6853 case MVT::i64: 6854 // i64 arguments should have been split to i32 for PPC32. 6855 assert(IsPPC64 && "PPC32 should have split i64 values."); 6856 LLVM_FALLTHROUGH; 6857 case MVT::i1: 6858 case MVT::i32: { 6859 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6860 // AIX integer arguments are always passed in register width. 6861 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6862 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6863 : CCValAssign::LocInfo::ZExt; 6864 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6865 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6866 else 6867 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6868 6869 return false; 6870 } 6871 case MVT::f32: 6872 case MVT::f64: { 6873 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6874 const unsigned StoreSize = LocVT.getStoreSize(); 6875 // Floats are always 4-byte aligned in the PSA on AIX. 6876 // This includes f64 in 64-bit mode for ABI compatibility. 6877 const unsigned Offset = 6878 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6879 unsigned FReg = State.AllocateReg(FPR); 6880 if (FReg) 6881 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6882 6883 // Reserve and initialize GPRs or initialize the PSA as required. 6884 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6885 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6886 assert(FReg && "An FPR should be available when a GPR is reserved."); 6887 if (State.isVarArg()) { 6888 // Successfully reserved GPRs are only initialized for vararg calls. 6889 // Custom handling is required for: 6890 // f64 in PPC32 needs to be split into 2 GPRs. 6891 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6892 State.addLoc( 6893 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6894 } 6895 } else { 6896 // If there are insufficient GPRs, the PSA needs to be initialized. 6897 // Initialization occurs even if an FPR was initialized for 6898 // compatibility with the AIX XL compiler. The full memory for the 6899 // argument will be initialized even if a prior word is saved in GPR. 6900 // A custom memLoc is used when the argument also passes in FPR so 6901 // that the callee handling can skip over it easily. 6902 State.addLoc( 6903 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6904 LocInfo) 6905 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6906 break; 6907 } 6908 } 6909 6910 return false; 6911 } 6912 } 6913 return true; 6914 } 6915 6916 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6917 bool IsPPC64) { 6918 assert((IsPPC64 || SVT != MVT::i64) && 6919 "i64 should have been split for 32-bit codegen."); 6920 6921 switch (SVT) { 6922 default: 6923 report_fatal_error("Unexpected value type for formal argument"); 6924 case MVT::i1: 6925 case MVT::i32: 6926 case MVT::i64: 6927 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6928 case MVT::f32: 6929 return &PPC::F4RCRegClass; 6930 case MVT::f64: 6931 return &PPC::F8RCRegClass; 6932 } 6933 } 6934 6935 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6936 SelectionDAG &DAG, SDValue ArgValue, 6937 MVT LocVT, const SDLoc &dl) { 6938 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6939 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6940 6941 if (Flags.isSExt()) 6942 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6943 DAG.getValueType(ValVT)); 6944 else if (Flags.isZExt()) 6945 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6946 DAG.getValueType(ValVT)); 6947 6948 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6949 } 6950 6951 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6952 const unsigned LASize = FL->getLinkageSize(); 6953 6954 if (PPC::GPRCRegClass.contains(Reg)) { 6955 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6956 "Reg must be a valid argument register!"); 6957 return LASize + 4 * (Reg - PPC::R3); 6958 } 6959 6960 if (PPC::G8RCRegClass.contains(Reg)) { 6961 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6962 "Reg must be a valid argument register!"); 6963 return LASize + 8 * (Reg - PPC::X3); 6964 } 6965 6966 llvm_unreachable("Only general purpose registers expected."); 6967 } 6968 6969 // AIX ABI Stack Frame Layout: 6970 // 6971 // Low Memory +--------------------------------------------+ 6972 // SP +---> | Back chain | ---+ 6973 // | +--------------------------------------------+ | 6974 // | | Saved Condition Register | | 6975 // | +--------------------------------------------+ | 6976 // | | Saved Linkage Register | | 6977 // | +--------------------------------------------+ | Linkage Area 6978 // | | Reserved for compilers | | 6979 // | +--------------------------------------------+ | 6980 // | | Reserved for binders | | 6981 // | +--------------------------------------------+ | 6982 // | | Saved TOC pointer | ---+ 6983 // | +--------------------------------------------+ 6984 // | | Parameter save area | 6985 // | +--------------------------------------------+ 6986 // | | Alloca space | 6987 // | +--------------------------------------------+ 6988 // | | Local variable space | 6989 // | +--------------------------------------------+ 6990 // | | Float/int conversion temporary | 6991 // | +--------------------------------------------+ 6992 // | | Save area for AltiVec registers | 6993 // | +--------------------------------------------+ 6994 // | | AltiVec alignment padding | 6995 // | +--------------------------------------------+ 6996 // | | Save area for VRSAVE register | 6997 // | +--------------------------------------------+ 6998 // | | Save area for General Purpose registers | 6999 // | +--------------------------------------------+ 7000 // | | Save area for Floating Point registers | 7001 // | +--------------------------------------------+ 7002 // +---- | Back chain | 7003 // High Memory +--------------------------------------------+ 7004 // 7005 // Specifications: 7006 // AIX 7.2 Assembler Language Reference 7007 // Subroutine linkage convention 7008 7009 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7010 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7011 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7012 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7013 7014 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7015 CallConv == CallingConv::Fast) && 7016 "Unexpected calling convention!"); 7017 7018 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7019 report_fatal_error("Tail call support is unimplemented on AIX."); 7020 7021 if (useSoftFloat()) 7022 report_fatal_error("Soft float support is unimplemented on AIX."); 7023 7024 const PPCSubtarget &Subtarget = 7025 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7026 7027 const bool IsPPC64 = Subtarget.isPPC64(); 7028 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7029 7030 // Assign locations to all of the incoming arguments. 7031 SmallVector<CCValAssign, 16> ArgLocs; 7032 MachineFunction &MF = DAG.getMachineFunction(); 7033 MachineFrameInfo &MFI = MF.getFrameInfo(); 7034 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7035 7036 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7037 // Reserve space for the linkage area on the stack. 7038 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7039 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7040 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7041 7042 SmallVector<SDValue, 8> MemOps; 7043 7044 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7045 CCValAssign &VA = ArgLocs[I++]; 7046 MVT LocVT = VA.getLocVT(); 7047 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7048 7049 // For compatibility with the AIX XL compiler, the float args in the 7050 // parameter save area are initialized even if the argument is available 7051 // in register. The caller is required to initialize both the register 7052 // and memory, however, the callee can choose to expect it in either. 7053 // The memloc is dismissed here because the argument is retrieved from 7054 // the register. 7055 if (VA.isMemLoc() && VA.needsCustom()) 7056 continue; 7057 7058 if (Flags.isByVal() && VA.isMemLoc()) { 7059 const unsigned Size = 7060 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7061 PtrByteSize); 7062 const int FI = MF.getFrameInfo().CreateFixedObject( 7063 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7064 /* IsAliased */ true); 7065 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7066 InVals.push_back(FIN); 7067 7068 continue; 7069 } 7070 7071 if (Flags.isByVal()) { 7072 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7073 7074 const MCPhysReg ArgReg = VA.getLocReg(); 7075 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7076 7077 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7078 report_fatal_error("Over aligned byvals not supported yet."); 7079 7080 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7081 const int FI = MF.getFrameInfo().CreateFixedObject( 7082 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7083 /* IsAliased */ true); 7084 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7085 InVals.push_back(FIN); 7086 7087 // Add live ins for all the RegLocs for the same ByVal. 7088 const TargetRegisterClass *RegClass = 7089 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7090 7091 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7092 unsigned Offset) { 7093 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7094 // Since the callers side has left justified the aggregate in the 7095 // register, we can simply store the entire register into the stack 7096 // slot. 7097 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7098 // The store to the fixedstack object is needed becuase accessing a 7099 // field of the ByVal will use a gep and load. Ideally we will optimize 7100 // to extracting the value from the register directly, and elide the 7101 // stores when the arguments address is not taken, but that will need to 7102 // be future work. 7103 SDValue Store = DAG.getStore( 7104 CopyFrom.getValue(1), dl, CopyFrom, 7105 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7106 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7107 7108 MemOps.push_back(Store); 7109 }; 7110 7111 unsigned Offset = 0; 7112 HandleRegLoc(VA.getLocReg(), Offset); 7113 Offset += PtrByteSize; 7114 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7115 Offset += PtrByteSize) { 7116 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7117 "RegLocs should be for ByVal argument."); 7118 7119 const CCValAssign RL = ArgLocs[I++]; 7120 HandleRegLoc(RL.getLocReg(), Offset); 7121 } 7122 7123 if (Offset != StackSize) { 7124 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7125 "Expected MemLoc for remaining bytes."); 7126 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7127 // Consume the MemLoc.The InVal has already been emitted, so nothing 7128 // more needs to be done. 7129 ++I; 7130 } 7131 7132 continue; 7133 } 7134 7135 EVT ValVT = VA.getValVT(); 7136 if (VA.isRegLoc() && !VA.needsCustom()) { 7137 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7138 unsigned VReg = 7139 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7140 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7141 if (ValVT.isScalarInteger() && 7142 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7143 ArgValue = 7144 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7145 } 7146 InVals.push_back(ArgValue); 7147 continue; 7148 } 7149 if (VA.isMemLoc()) { 7150 const unsigned LocSize = LocVT.getStoreSize(); 7151 const unsigned ValSize = ValVT.getStoreSize(); 7152 assert((ValSize <= LocSize) && 7153 "Object size is larger than size of MemLoc"); 7154 int CurArgOffset = VA.getLocMemOffset(); 7155 // Objects are right-justified because AIX is big-endian. 7156 if (LocSize > ValSize) 7157 CurArgOffset += LocSize - ValSize; 7158 // Potential tail calls could cause overwriting of argument stack slots. 7159 const bool IsImmutable = 7160 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7161 (CallConv == CallingConv::Fast)); 7162 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7163 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7164 SDValue ArgValue = 7165 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7166 InVals.push_back(ArgValue); 7167 continue; 7168 } 7169 } 7170 7171 // On AIX a minimum of 8 words is saved to the parameter save area. 7172 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7173 // Area that is at least reserved in the caller of this function. 7174 unsigned CallerReservedArea = 7175 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7176 7177 // Set the size that is at least reserved in caller of this function. Tail 7178 // call optimized function's reserved stack space needs to be aligned so 7179 // that taking the difference between two stack areas will result in an 7180 // aligned stack. 7181 CallerReservedArea = 7182 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7183 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7184 FuncInfo->setMinReservedArea(CallerReservedArea); 7185 7186 if (isVarArg) { 7187 FuncInfo->setVarArgsFrameIndex( 7188 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7189 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7190 7191 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7192 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7193 7194 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7195 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7196 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7197 7198 // The fixed integer arguments of a variadic function are stored to the 7199 // VarArgsFrameIndex on the stack so that they may be loaded by 7200 // dereferencing the result of va_next. 7201 for (unsigned GPRIndex = 7202 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7203 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7204 7205 const unsigned VReg = 7206 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7207 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7208 7209 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7210 SDValue Store = 7211 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7212 MemOps.push_back(Store); 7213 // Increment the address for the next argument to store. 7214 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7215 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7216 } 7217 } 7218 7219 if (!MemOps.empty()) 7220 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7221 7222 return Chain; 7223 } 7224 7225 SDValue PPCTargetLowering::LowerCall_AIX( 7226 SDValue Chain, SDValue Callee, CallFlags CFlags, 7227 const SmallVectorImpl<ISD::OutputArg> &Outs, 7228 const SmallVectorImpl<SDValue> &OutVals, 7229 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7230 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7231 const CallBase *CB) const { 7232 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7233 // AIX ABI stack frame layout. 7234 7235 assert((CFlags.CallConv == CallingConv::C || 7236 CFlags.CallConv == CallingConv::Cold || 7237 CFlags.CallConv == CallingConv::Fast) && 7238 "Unexpected calling convention!"); 7239 7240 if (CFlags.IsPatchPoint) 7241 report_fatal_error("This call type is unimplemented on AIX."); 7242 7243 const PPCSubtarget& Subtarget = 7244 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7245 if (Subtarget.hasAltivec()) 7246 report_fatal_error("Altivec support is unimplemented on AIX."); 7247 7248 MachineFunction &MF = DAG.getMachineFunction(); 7249 SmallVector<CCValAssign, 16> ArgLocs; 7250 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7251 *DAG.getContext()); 7252 7253 // Reserve space for the linkage save area (LSA) on the stack. 7254 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7255 // [SP][CR][LR][2 x reserved][TOC]. 7256 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7257 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7258 const bool IsPPC64 = Subtarget.isPPC64(); 7259 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7260 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7261 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7262 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7263 7264 // The prolog code of the callee may store up to 8 GPR argument registers to 7265 // the stack, allowing va_start to index over them in memory if the callee 7266 // is variadic. 7267 // Because we cannot tell if this is needed on the caller side, we have to 7268 // conservatively assume that it is needed. As such, make sure we have at 7269 // least enough stack space for the caller to store the 8 GPRs. 7270 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7271 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7272 CCInfo.getNextStackOffset()); 7273 7274 // Adjust the stack pointer for the new arguments... 7275 // These operations are automatically eliminated by the prolog/epilog pass. 7276 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7277 SDValue CallSeqStart = Chain; 7278 7279 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7280 SmallVector<SDValue, 8> MemOpChains; 7281 7282 // Set up a copy of the stack pointer for loading and storing any 7283 // arguments that may not fit in the registers available for argument 7284 // passing. 7285 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7286 : DAG.getRegister(PPC::R1, MVT::i32); 7287 7288 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7289 const unsigned ValNo = ArgLocs[I].getValNo(); 7290 SDValue Arg = OutVals[ValNo]; 7291 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7292 7293 if (Flags.isByVal()) { 7294 const unsigned ByValSize = Flags.getByValSize(); 7295 7296 // Nothing to do for zero-sized ByVals on the caller side. 7297 if (!ByValSize) { 7298 ++I; 7299 continue; 7300 } 7301 7302 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7303 return DAG.getExtLoad( 7304 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7305 (LoadOffset != 0) 7306 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7307 : Arg, 7308 MachinePointerInfo(), VT); 7309 }; 7310 7311 unsigned LoadOffset = 0; 7312 7313 // Initialize registers, which are fully occupied by the by-val argument. 7314 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7315 SDValue Load = GetLoad(PtrVT, LoadOffset); 7316 MemOpChains.push_back(Load.getValue(1)); 7317 LoadOffset += PtrByteSize; 7318 const CCValAssign &ByValVA = ArgLocs[I++]; 7319 assert(ByValVA.getValNo() == ValNo && 7320 "Unexpected location for pass-by-value argument."); 7321 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7322 } 7323 7324 if (LoadOffset == ByValSize) 7325 continue; 7326 7327 // There must be one more loc to handle the remainder. 7328 assert(ArgLocs[I].getValNo() == ValNo && 7329 "Expected additional location for by-value argument."); 7330 7331 if (ArgLocs[I].isMemLoc()) { 7332 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7333 const CCValAssign &ByValVA = ArgLocs[I++]; 7334 ISD::ArgFlagsTy MemcpyFlags = Flags; 7335 // Only memcpy the bytes that don't pass in register. 7336 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7337 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7338 (LoadOffset != 0) 7339 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7340 : Arg, 7341 DAG.getObjectPtrOffset(dl, StackPtr, 7342 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7343 CallSeqStart, MemcpyFlags, DAG, dl); 7344 continue; 7345 } 7346 7347 // Initialize the final register residue. 7348 // Any residue that occupies the final by-val arg register must be 7349 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7350 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7351 // 2 and 1 byte loads. 7352 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7353 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7354 "Unexpected register residue for by-value argument."); 7355 SDValue ResidueVal; 7356 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7357 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7358 const MVT VT = 7359 N == 1 ? MVT::i8 7360 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7361 SDValue Load = GetLoad(VT, LoadOffset); 7362 MemOpChains.push_back(Load.getValue(1)); 7363 LoadOffset += N; 7364 Bytes += N; 7365 7366 // By-val arguments are passed left-justfied in register. 7367 // Every load here needs to be shifted, otherwise a full register load 7368 // should have been used. 7369 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7370 "Unexpected load emitted during handling of pass-by-value " 7371 "argument."); 7372 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7373 EVT ShiftAmountTy = 7374 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7375 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7376 SDValue ShiftedLoad = 7377 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7378 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7379 ShiftedLoad) 7380 : ShiftedLoad; 7381 } 7382 7383 const CCValAssign &ByValVA = ArgLocs[I++]; 7384 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7385 continue; 7386 } 7387 7388 CCValAssign &VA = ArgLocs[I++]; 7389 const MVT LocVT = VA.getLocVT(); 7390 const MVT ValVT = VA.getValVT(); 7391 7392 switch (VA.getLocInfo()) { 7393 default: 7394 report_fatal_error("Unexpected argument extension type."); 7395 case CCValAssign::Full: 7396 break; 7397 case CCValAssign::ZExt: 7398 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7399 break; 7400 case CCValAssign::SExt: 7401 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7402 break; 7403 } 7404 7405 if (VA.isRegLoc() && !VA.needsCustom()) { 7406 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7407 continue; 7408 } 7409 7410 if (VA.isMemLoc()) { 7411 SDValue PtrOff = 7412 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7413 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7414 MemOpChains.push_back( 7415 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7416 7417 continue; 7418 } 7419 7420 // Custom handling is used for GPR initializations for vararg float 7421 // arguments. 7422 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7423 ValVT.isFloatingPoint() && LocVT.isInteger() && 7424 "Unexpected register handling for calling convention."); 7425 7426 SDValue ArgAsInt = 7427 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7428 7429 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7430 // f32 in 32-bit GPR 7431 // f64 in 64-bit GPR 7432 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7433 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7434 // f32 in 64-bit GPR. 7435 RegsToPass.push_back(std::make_pair( 7436 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7437 else { 7438 // f64 in two 32-bit GPRs 7439 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7440 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7441 "Unexpected custom register for argument!"); 7442 CCValAssign &GPR1 = VA; 7443 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7444 DAG.getConstant(32, dl, MVT::i8)); 7445 RegsToPass.push_back(std::make_pair( 7446 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7447 7448 if (I != E) { 7449 // If only 1 GPR was available, there will only be one custom GPR and 7450 // the argument will also pass in memory. 7451 CCValAssign &PeekArg = ArgLocs[I]; 7452 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7453 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7454 CCValAssign &GPR2 = ArgLocs[I++]; 7455 RegsToPass.push_back(std::make_pair( 7456 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7457 } 7458 } 7459 } 7460 } 7461 7462 if (!MemOpChains.empty()) 7463 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7464 7465 // For indirect calls, we need to save the TOC base to the stack for 7466 // restoration after the call. 7467 if (CFlags.IsIndirect) { 7468 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7469 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7470 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7471 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7472 const unsigned TOCSaveOffset = 7473 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7474 7475 setUsesTOCBasePtr(DAG); 7476 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7477 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7478 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7479 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7480 Chain = DAG.getStore( 7481 Val.getValue(1), dl, Val, AddPtr, 7482 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7483 } 7484 7485 // Build a sequence of copy-to-reg nodes chained together with token chain 7486 // and flag operands which copy the outgoing args into the appropriate regs. 7487 SDValue InFlag; 7488 for (auto Reg : RegsToPass) { 7489 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7490 InFlag = Chain.getValue(1); 7491 } 7492 7493 const int SPDiff = 0; 7494 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7495 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7496 } 7497 7498 bool 7499 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7500 MachineFunction &MF, bool isVarArg, 7501 const SmallVectorImpl<ISD::OutputArg> &Outs, 7502 LLVMContext &Context) const { 7503 SmallVector<CCValAssign, 16> RVLocs; 7504 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7505 return CCInfo.CheckReturn( 7506 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7507 ? RetCC_PPC_Cold 7508 : RetCC_PPC); 7509 } 7510 7511 SDValue 7512 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7513 bool isVarArg, 7514 const SmallVectorImpl<ISD::OutputArg> &Outs, 7515 const SmallVectorImpl<SDValue> &OutVals, 7516 const SDLoc &dl, SelectionDAG &DAG) const { 7517 SmallVector<CCValAssign, 16> RVLocs; 7518 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7519 *DAG.getContext()); 7520 CCInfo.AnalyzeReturn(Outs, 7521 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7522 ? RetCC_PPC_Cold 7523 : RetCC_PPC); 7524 7525 SDValue Flag; 7526 SmallVector<SDValue, 4> RetOps(1, Chain); 7527 7528 // Copy the result values into the output registers. 7529 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7530 CCValAssign &VA = RVLocs[i]; 7531 assert(VA.isRegLoc() && "Can only return in registers!"); 7532 7533 SDValue Arg = OutVals[RealResIdx]; 7534 7535 switch (VA.getLocInfo()) { 7536 default: llvm_unreachable("Unknown loc info!"); 7537 case CCValAssign::Full: break; 7538 case CCValAssign::AExt: 7539 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7540 break; 7541 case CCValAssign::ZExt: 7542 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7543 break; 7544 case CCValAssign::SExt: 7545 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7546 break; 7547 } 7548 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7549 bool isLittleEndian = Subtarget.isLittleEndian(); 7550 // Legalize ret f64 -> ret 2 x i32. 7551 SDValue SVal = 7552 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7553 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7554 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7555 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7556 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7557 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7558 Flag = Chain.getValue(1); 7559 VA = RVLocs[++i]; // skip ahead to next loc 7560 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7561 } else 7562 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7563 Flag = Chain.getValue(1); 7564 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7565 } 7566 7567 RetOps[0] = Chain; // Update chain. 7568 7569 // Add the flag if we have it. 7570 if (Flag.getNode()) 7571 RetOps.push_back(Flag); 7572 7573 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7574 } 7575 7576 SDValue 7577 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7578 SelectionDAG &DAG) const { 7579 SDLoc dl(Op); 7580 7581 // Get the correct type for integers. 7582 EVT IntVT = Op.getValueType(); 7583 7584 // Get the inputs. 7585 SDValue Chain = Op.getOperand(0); 7586 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7587 // Build a DYNAREAOFFSET node. 7588 SDValue Ops[2] = {Chain, FPSIdx}; 7589 SDVTList VTs = DAG.getVTList(IntVT); 7590 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7591 } 7592 7593 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7594 SelectionDAG &DAG) const { 7595 // When we pop the dynamic allocation we need to restore the SP link. 7596 SDLoc dl(Op); 7597 7598 // Get the correct type for pointers. 7599 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7600 7601 // Construct the stack pointer operand. 7602 bool isPPC64 = Subtarget.isPPC64(); 7603 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7604 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7605 7606 // Get the operands for the STACKRESTORE. 7607 SDValue Chain = Op.getOperand(0); 7608 SDValue SaveSP = Op.getOperand(1); 7609 7610 // Load the old link SP. 7611 SDValue LoadLinkSP = 7612 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7613 7614 // Restore the stack pointer. 7615 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7616 7617 // Store the old link SP. 7618 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7619 } 7620 7621 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7622 MachineFunction &MF = DAG.getMachineFunction(); 7623 bool isPPC64 = Subtarget.isPPC64(); 7624 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7625 7626 // Get current frame pointer save index. The users of this index will be 7627 // primarily DYNALLOC instructions. 7628 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7629 int RASI = FI->getReturnAddrSaveIndex(); 7630 7631 // If the frame pointer save index hasn't been defined yet. 7632 if (!RASI) { 7633 // Find out what the fix offset of the frame pointer save area. 7634 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7635 // Allocate the frame index for frame pointer save area. 7636 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7637 // Save the result. 7638 FI->setReturnAddrSaveIndex(RASI); 7639 } 7640 return DAG.getFrameIndex(RASI, PtrVT); 7641 } 7642 7643 SDValue 7644 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7645 MachineFunction &MF = DAG.getMachineFunction(); 7646 bool isPPC64 = Subtarget.isPPC64(); 7647 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7648 7649 // Get current frame pointer save index. The users of this index will be 7650 // primarily DYNALLOC instructions. 7651 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7652 int FPSI = FI->getFramePointerSaveIndex(); 7653 7654 // If the frame pointer save index hasn't been defined yet. 7655 if (!FPSI) { 7656 // Find out what the fix offset of the frame pointer save area. 7657 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7658 // Allocate the frame index for frame pointer save area. 7659 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7660 // Save the result. 7661 FI->setFramePointerSaveIndex(FPSI); 7662 } 7663 return DAG.getFrameIndex(FPSI, PtrVT); 7664 } 7665 7666 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7667 SelectionDAG &DAG) const { 7668 MachineFunction &MF = DAG.getMachineFunction(); 7669 // Get the inputs. 7670 SDValue Chain = Op.getOperand(0); 7671 SDValue Size = Op.getOperand(1); 7672 SDLoc dl(Op); 7673 7674 // Get the correct type for pointers. 7675 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7676 // Negate the size. 7677 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7678 DAG.getConstant(0, dl, PtrVT), Size); 7679 // Construct a node for the frame pointer save index. 7680 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7681 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7682 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7683 if (hasInlineStackProbe(MF)) 7684 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7685 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7686 } 7687 7688 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7689 SelectionDAG &DAG) const { 7690 MachineFunction &MF = DAG.getMachineFunction(); 7691 7692 bool isPPC64 = Subtarget.isPPC64(); 7693 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7694 7695 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7696 return DAG.getFrameIndex(FI, PtrVT); 7697 } 7698 7699 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7700 SelectionDAG &DAG) const { 7701 SDLoc DL(Op); 7702 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7703 DAG.getVTList(MVT::i32, MVT::Other), 7704 Op.getOperand(0), Op.getOperand(1)); 7705 } 7706 7707 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7708 SelectionDAG &DAG) const { 7709 SDLoc DL(Op); 7710 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7711 Op.getOperand(0), Op.getOperand(1)); 7712 } 7713 7714 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7715 7716 assert(Op.getValueType() == MVT::i1 && 7717 "Custom lowering only for i1 loads"); 7718 7719 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7720 7721 SDLoc dl(Op); 7722 LoadSDNode *LD = cast<LoadSDNode>(Op); 7723 7724 SDValue Chain = LD->getChain(); 7725 SDValue BasePtr = LD->getBasePtr(); 7726 MachineMemOperand *MMO = LD->getMemOperand(); 7727 7728 SDValue NewLD = 7729 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7730 BasePtr, MVT::i8, MMO); 7731 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7732 7733 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7734 return DAG.getMergeValues(Ops, dl); 7735 } 7736 7737 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7738 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7739 "Custom lowering only for i1 stores"); 7740 7741 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7742 7743 SDLoc dl(Op); 7744 StoreSDNode *ST = cast<StoreSDNode>(Op); 7745 7746 SDValue Chain = ST->getChain(); 7747 SDValue BasePtr = ST->getBasePtr(); 7748 SDValue Value = ST->getValue(); 7749 MachineMemOperand *MMO = ST->getMemOperand(); 7750 7751 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7752 Value); 7753 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7754 } 7755 7756 // FIXME: Remove this once the ANDI glue bug is fixed: 7757 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7758 assert(Op.getValueType() == MVT::i1 && 7759 "Custom lowering only for i1 results"); 7760 7761 SDLoc DL(Op); 7762 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7763 } 7764 7765 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7766 SelectionDAG &DAG) const { 7767 7768 // Implements a vector truncate that fits in a vector register as a shuffle. 7769 // We want to legalize vector truncates down to where the source fits in 7770 // a vector register (and target is therefore smaller than vector register 7771 // size). At that point legalization will try to custom lower the sub-legal 7772 // result and get here - where we can contain the truncate as a single target 7773 // operation. 7774 7775 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7776 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7777 // 7778 // We will implement it for big-endian ordering as this (where x denotes 7779 // undefined): 7780 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7781 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7782 // 7783 // The same operation in little-endian ordering will be: 7784 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7785 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7786 7787 assert(Op.getValueType().isVector() && "Vector type expected."); 7788 7789 SDLoc DL(Op); 7790 SDValue N1 = Op.getOperand(0); 7791 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7792 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7793 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7794 7795 EVT TrgVT = Op.getValueType(); 7796 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7797 EVT EltVT = TrgVT.getVectorElementType(); 7798 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7799 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7800 7801 // First list the elements we want to keep. 7802 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7803 SmallVector<int, 16> ShuffV; 7804 if (Subtarget.isLittleEndian()) 7805 for (unsigned i = 0; i < TrgNumElts; ++i) 7806 ShuffV.push_back(i * SizeMult); 7807 else 7808 for (unsigned i = 1; i <= TrgNumElts; ++i) 7809 ShuffV.push_back(i * SizeMult - 1); 7810 7811 // Populate the remaining elements with undefs. 7812 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7813 // ShuffV.push_back(i + WideNumElts); 7814 ShuffV.push_back(WideNumElts + 1); 7815 7816 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7817 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7818 } 7819 7820 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7821 /// possible. 7822 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7823 // Not FP, or using SPE? Not a fsel. 7824 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7825 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7826 return Op; 7827 7828 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7829 7830 EVT ResVT = Op.getValueType(); 7831 EVT CmpVT = Op.getOperand(0).getValueType(); 7832 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7833 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7834 SDLoc dl(Op); 7835 SDNodeFlags Flags = Op.getNode()->getFlags(); 7836 7837 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7838 // presence of infinities. 7839 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7840 switch (CC) { 7841 default: 7842 break; 7843 case ISD::SETOGT: 7844 case ISD::SETGT: 7845 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7846 case ISD::SETOLT: 7847 case ISD::SETLT: 7848 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7849 } 7850 } 7851 7852 // We might be able to do better than this under some circumstances, but in 7853 // general, fsel-based lowering of select is a finite-math-only optimization. 7854 // For more information, see section F.3 of the 2.06 ISA specification. 7855 // With ISA 3.0 7856 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7857 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7858 return Op; 7859 7860 // If the RHS of the comparison is a 0.0, we don't need to do the 7861 // subtraction at all. 7862 SDValue Sel1; 7863 if (isFloatingPointZero(RHS)) 7864 switch (CC) { 7865 default: break; // SETUO etc aren't handled by fsel. 7866 case ISD::SETNE: 7867 std::swap(TV, FV); 7868 LLVM_FALLTHROUGH; 7869 case ISD::SETEQ: 7870 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7871 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7872 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7873 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7874 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7875 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7876 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7877 case ISD::SETULT: 7878 case ISD::SETLT: 7879 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7880 LLVM_FALLTHROUGH; 7881 case ISD::SETOGE: 7882 case ISD::SETGE: 7883 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7884 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7885 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7886 case ISD::SETUGT: 7887 case ISD::SETGT: 7888 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7889 LLVM_FALLTHROUGH; 7890 case ISD::SETOLE: 7891 case ISD::SETLE: 7892 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7893 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7894 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7895 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7896 } 7897 7898 SDValue Cmp; 7899 switch (CC) { 7900 default: break; // SETUO etc aren't handled by fsel. 7901 case ISD::SETNE: 7902 std::swap(TV, FV); 7903 LLVM_FALLTHROUGH; 7904 case ISD::SETEQ: 7905 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7906 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7907 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7908 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7909 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7910 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7911 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7912 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7913 case ISD::SETULT: 7914 case ISD::SETLT: 7915 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7916 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7917 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7918 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7919 case ISD::SETOGE: 7920 case ISD::SETGE: 7921 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7922 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7923 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7924 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7925 case ISD::SETUGT: 7926 case ISD::SETGT: 7927 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7928 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7929 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7930 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7931 case ISD::SETOLE: 7932 case ISD::SETLE: 7933 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7934 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7935 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7936 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7937 } 7938 return Op; 7939 } 7940 7941 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7942 const PPCSubtarget &Subtarget) { 7943 SDLoc dl(Op); 7944 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT; 7945 SDValue Src = Op.getOperand(0); 7946 assert(Src.getValueType().isFloatingPoint()); 7947 if (Src.getValueType() == MVT::f32) 7948 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7949 SDValue Conv; 7950 switch (Op.getSimpleValueType().SimpleTy) { 7951 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7952 case MVT::i32: 7953 Conv = DAG.getNode( 7954 IsSigned ? PPCISD::FCTIWZ 7955 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7956 dl, MVT::f64, Src); 7957 break; 7958 case MVT::i64: 7959 assert((IsSigned || Subtarget.hasFPCVT()) && 7960 "i64 FP_TO_UINT is supported only with FPCVT"); 7961 Conv = DAG.getNode(IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ, dl, 7962 MVT::f64, Src); 7963 } 7964 return Conv; 7965 } 7966 7967 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7968 SelectionDAG &DAG, 7969 const SDLoc &dl) const { 7970 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 7971 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT; 7972 7973 // Convert the FP value to an int value through memory. 7974 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7975 (IsSigned || Subtarget.hasFPCVT()); 7976 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7977 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7978 MachinePointerInfo MPI = 7979 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7980 7981 // Emit a store to the stack slot. 7982 SDValue Chain; 7983 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 7984 if (i32Stack) { 7985 MachineFunction &MF = DAG.getMachineFunction(); 7986 Alignment = Align(4); 7987 MachineMemOperand *MMO = 7988 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 7989 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7990 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7991 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7992 } else 7993 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment); 7994 7995 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7996 // add in a bias on big endian. 7997 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7998 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7999 DAG.getConstant(4, dl, FIPtr.getValueType())); 8000 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8001 } 8002 8003 RLI.Chain = Chain; 8004 RLI.Ptr = FIPtr; 8005 RLI.MPI = MPI; 8006 RLI.Alignment = Alignment; 8007 } 8008 8009 /// Custom lowers floating point to integer conversions to use 8010 /// the direct move instructions available in ISA 2.07 to avoid the 8011 /// need for load/store combinations. 8012 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8013 SelectionDAG &DAG, 8014 const SDLoc &dl) const { 8015 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 8016 return DAG.getNode(PPCISD::MFVSR, dl, Op.getSimpleValueType().SimpleTy, 8017 convertFPToInt(Op, DAG, Subtarget)); 8018 } 8019 8020 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8021 const SDLoc &dl) const { 8022 SDValue Src = Op.getOperand(0); 8023 // FP to INT conversions are legal for f128. 8024 if (Src.getValueType() == MVT::f128) 8025 return Op; 8026 8027 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8028 // PPC (the libcall is not available). 8029 if (Src.getValueType() == MVT::ppcf128) { 8030 if (Op.getValueType() == MVT::i32) { 8031 if (Op.getOpcode() == ISD::FP_TO_SINT) { 8032 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8033 DAG.getIntPtrConstant(0, dl)); 8034 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8035 DAG.getIntPtrConstant(1, dl)); 8036 8037 // Add the two halves of the long double in round-to-zero mode. 8038 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8039 8040 // Now use a smaller FP_TO_SINT. 8041 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8042 } 8043 if (Op.getOpcode() == ISD::FP_TO_UINT) { 8044 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8045 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8046 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8047 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8048 // FIXME: generated code sucks. 8049 // TODO: Are there fast-math-flags to propagate to this FSUB? 8050 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp); 8051 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8052 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8053 DAG.getConstant(0x80000000, dl, MVT::i32)); 8054 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8055 return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE); 8056 } 8057 } 8058 8059 return SDValue(); 8060 } 8061 8062 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8063 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8064 8065 ReuseLoadInfo RLI; 8066 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8067 8068 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8069 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8070 } 8071 8072 // We're trying to insert a regular store, S, and then a load, L. If the 8073 // incoming value, O, is a load, we might just be able to have our load use the 8074 // address used by O. However, we don't know if anything else will store to 8075 // that address before we can load from it. To prevent this situation, we need 8076 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8077 // the same chain operand as O, we create a token factor from the chain results 8078 // of O and L, and we replace all uses of O's chain result with that token 8079 // factor (see spliceIntoChain below for this last part). 8080 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8081 ReuseLoadInfo &RLI, 8082 SelectionDAG &DAG, 8083 ISD::LoadExtType ET) const { 8084 SDLoc dl(Op); 8085 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8086 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8087 if (ET == ISD::NON_EXTLOAD && 8088 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8089 isOperationLegalOrCustom(Op.getOpcode(), 8090 Op.getOperand(0).getValueType())) { 8091 8092 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8093 return true; 8094 } 8095 8096 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8097 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8098 LD->isNonTemporal()) 8099 return false; 8100 if (LD->getMemoryVT() != MemVT) 8101 return false; 8102 8103 RLI.Ptr = LD->getBasePtr(); 8104 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8105 assert(LD->getAddressingMode() == ISD::PRE_INC && 8106 "Non-pre-inc AM on PPC?"); 8107 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8108 LD->getOffset()); 8109 } 8110 8111 RLI.Chain = LD->getChain(); 8112 RLI.MPI = LD->getPointerInfo(); 8113 RLI.IsDereferenceable = LD->isDereferenceable(); 8114 RLI.IsInvariant = LD->isInvariant(); 8115 RLI.Alignment = LD->getAlign(); 8116 RLI.AAInfo = LD->getAAInfo(); 8117 RLI.Ranges = LD->getRanges(); 8118 8119 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8120 return true; 8121 } 8122 8123 // Given the head of the old chain, ResChain, insert a token factor containing 8124 // it and NewResChain, and make users of ResChain now be users of that token 8125 // factor. 8126 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8127 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8128 SDValue NewResChain, 8129 SelectionDAG &DAG) const { 8130 if (!ResChain) 8131 return; 8132 8133 SDLoc dl(NewResChain); 8134 8135 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8136 NewResChain, DAG.getUNDEF(MVT::Other)); 8137 assert(TF.getNode() != NewResChain.getNode() && 8138 "A new TF really is required here"); 8139 8140 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8141 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8142 } 8143 8144 /// Analyze profitability of direct move 8145 /// prefer float load to int load plus direct move 8146 /// when there is no integer use of int load 8147 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8148 SDNode *Origin = Op.getOperand(0).getNode(); 8149 if (Origin->getOpcode() != ISD::LOAD) 8150 return true; 8151 8152 // If there is no LXSIBZX/LXSIHZX, like Power8, 8153 // prefer direct move if the memory size is 1 or 2 bytes. 8154 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8155 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8156 return true; 8157 8158 for (SDNode::use_iterator UI = Origin->use_begin(), 8159 UE = Origin->use_end(); 8160 UI != UE; ++UI) { 8161 8162 // Only look at the users of the loaded value. 8163 if (UI.getUse().get().getResNo() != 0) 8164 continue; 8165 8166 if (UI->getOpcode() != ISD::SINT_TO_FP && 8167 UI->getOpcode() != ISD::UINT_TO_FP) 8168 return true; 8169 } 8170 8171 return false; 8172 } 8173 8174 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8175 const PPCSubtarget &Subtarget) { 8176 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP; 8177 SDLoc dl(Op); 8178 // If we have FCFIDS, then use it when converting to single-precision. 8179 // Otherwise, convert to double-precision and then round. 8180 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8181 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8182 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8183 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8184 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8185 } 8186 8187 /// Custom lowers integer to floating point conversions to use 8188 /// the direct move instructions available in ISA 2.07 to avoid the 8189 /// need for load/store combinations. 8190 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8191 SelectionDAG &DAG, 8192 const SDLoc &dl) const { 8193 assert((Op.getValueType() == MVT::f32 || 8194 Op.getValueType() == MVT::f64) && 8195 "Invalid floating point type as target of conversion"); 8196 assert(Subtarget.hasFPCVT() && 8197 "Int to FP conversions with direct moves require FPCVT"); 8198 SDValue Src = Op.getOperand(0); 8199 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8200 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8201 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8202 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8203 return convertIntToFP(Op, Mov, DAG, Subtarget); 8204 } 8205 8206 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8207 8208 EVT VecVT = Vec.getValueType(); 8209 assert(VecVT.isVector() && "Expected a vector type."); 8210 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8211 8212 EVT EltVT = VecVT.getVectorElementType(); 8213 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8214 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8215 8216 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8217 SmallVector<SDValue, 16> Ops(NumConcat); 8218 Ops[0] = Vec; 8219 SDValue UndefVec = DAG.getUNDEF(VecVT); 8220 for (unsigned i = 1; i < NumConcat; ++i) 8221 Ops[i] = UndefVec; 8222 8223 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8224 } 8225 8226 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8227 const SDLoc &dl) const { 8228 8229 unsigned Opc = Op.getOpcode(); 8230 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8231 "Unexpected conversion type"); 8232 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8233 "Supports conversions to v2f64/v4f32 only."); 8234 8235 bool SignedConv = Opc == ISD::SINT_TO_FP; 8236 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8237 8238 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8239 EVT WideVT = Wide.getValueType(); 8240 unsigned WideNumElts = WideVT.getVectorNumElements(); 8241 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8242 8243 SmallVector<int, 16> ShuffV; 8244 for (unsigned i = 0; i < WideNumElts; ++i) 8245 ShuffV.push_back(i + WideNumElts); 8246 8247 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8248 int SaveElts = FourEltRes ? 4 : 2; 8249 if (Subtarget.isLittleEndian()) 8250 for (int i = 0; i < SaveElts; i++) 8251 ShuffV[i * Stride] = i; 8252 else 8253 for (int i = 1; i <= SaveElts; i++) 8254 ShuffV[i * Stride - 1] = i - 1; 8255 8256 SDValue ShuffleSrc2 = 8257 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8258 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8259 8260 SDValue Extend; 8261 if (SignedConv) { 8262 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8263 EVT ExtVT = Op.getOperand(0).getValueType(); 8264 if (Subtarget.hasP9Altivec()) 8265 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8266 IntermediateVT.getVectorNumElements()); 8267 8268 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8269 DAG.getValueType(ExtVT)); 8270 } else 8271 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8272 8273 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8274 } 8275 8276 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8277 SelectionDAG &DAG) const { 8278 SDLoc dl(Op); 8279 SDValue Src = Op.getOperand(0); 8280 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP; 8281 8282 EVT InVT = Src.getValueType(); 8283 EVT OutVT = Op.getValueType(); 8284 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8285 isOperationCustom(Op.getOpcode(), InVT)) 8286 return LowerINT_TO_FPVector(Op, DAG, dl); 8287 8288 // Conversions to f128 are legal. 8289 if (Op.getValueType() == MVT::f128) 8290 return Op; 8291 8292 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8293 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8294 return SDValue(); 8295 8296 if (Src.getValueType() == MVT::i1) 8297 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8298 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8299 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8300 8301 // If we have direct moves, we can do all the conversion, skip the store/load 8302 // however, without FPCVT we can't do most conversions. 8303 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8304 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8305 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8306 8307 assert((IsSigned || Subtarget.hasFPCVT()) && 8308 "UINT_TO_FP is supported only with FPCVT"); 8309 8310 if (Src.getValueType() == MVT::i64) { 8311 SDValue SINT = Src; 8312 // When converting to single-precision, we actually need to convert 8313 // to double-precision first and then round to single-precision. 8314 // To avoid double-rounding effects during that operation, we have 8315 // to prepare the input operand. Bits that might be truncated when 8316 // converting to double-precision are replaced by a bit that won't 8317 // be lost at this stage, but is below the single-precision rounding 8318 // position. 8319 // 8320 // However, if -enable-unsafe-fp-math is in effect, accept double 8321 // rounding to avoid the extra overhead. 8322 if (Op.getValueType() == MVT::f32 && 8323 !Subtarget.hasFPCVT() && 8324 !DAG.getTarget().Options.UnsafeFPMath) { 8325 8326 // Twiddle input to make sure the low 11 bits are zero. (If this 8327 // is the case, we are guaranteed the value will fit into the 53 bit 8328 // mantissa of an IEEE double-precision value without rounding.) 8329 // If any of those low 11 bits were not zero originally, make sure 8330 // bit 12 (value 2048) is set instead, so that the final rounding 8331 // to single-precision gets the correct result. 8332 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8333 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8334 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8335 Round, DAG.getConstant(2047, dl, MVT::i64)); 8336 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8337 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8338 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8339 8340 // However, we cannot use that value unconditionally: if the magnitude 8341 // of the input value is small, the bit-twiddling we did above might 8342 // end up visibly changing the output. Fortunately, in that case, we 8343 // don't need to twiddle bits since the original input will convert 8344 // exactly to double-precision floating-point already. Therefore, 8345 // construct a conditional to use the original value if the top 11 8346 // bits are all sign-bit copies, and use the rounded value computed 8347 // above otherwise. 8348 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8349 SINT, DAG.getConstant(53, dl, MVT::i32)); 8350 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8351 Cond, DAG.getConstant(1, dl, MVT::i64)); 8352 Cond = DAG.getSetCC( 8353 dl, 8354 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8355 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8356 8357 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8358 } 8359 8360 ReuseLoadInfo RLI; 8361 SDValue Bits; 8362 8363 MachineFunction &MF = DAG.getMachineFunction(); 8364 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8365 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8366 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8367 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8368 } else if (Subtarget.hasLFIWAX() && 8369 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8370 MachineMemOperand *MMO = 8371 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8372 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8373 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8374 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8375 DAG.getVTList(MVT::f64, MVT::Other), 8376 Ops, MVT::i32, MMO); 8377 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8378 } else if (Subtarget.hasFPCVT() && 8379 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8380 MachineMemOperand *MMO = 8381 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8382 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8383 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8384 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8385 DAG.getVTList(MVT::f64, MVT::Other), 8386 Ops, MVT::i32, MMO); 8387 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8388 } else if (((Subtarget.hasLFIWAX() && 8389 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8390 (Subtarget.hasFPCVT() && 8391 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8392 SINT.getOperand(0).getValueType() == MVT::i32) { 8393 MachineFrameInfo &MFI = MF.getFrameInfo(); 8394 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8395 8396 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8397 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8398 8399 SDValue Store = 8400 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8401 MachinePointerInfo::getFixedStack( 8402 DAG.getMachineFunction(), FrameIdx)); 8403 8404 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8405 "Expected an i32 store"); 8406 8407 RLI.Ptr = FIdx; 8408 RLI.Chain = Store; 8409 RLI.MPI = 8410 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8411 RLI.Alignment = Align(4); 8412 8413 MachineMemOperand *MMO = 8414 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8415 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8416 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8417 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8418 PPCISD::LFIWZX : PPCISD::LFIWAX, 8419 dl, DAG.getVTList(MVT::f64, MVT::Other), 8420 Ops, MVT::i32, MMO); 8421 } else 8422 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8423 8424 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget); 8425 8426 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8427 FP = DAG.getNode(ISD::FP_ROUND, dl, 8428 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8429 return FP; 8430 } 8431 8432 assert(Src.getValueType() == MVT::i32 && 8433 "Unhandled INT_TO_FP type in custom expander!"); 8434 // Since we only generate this in 64-bit mode, we can take advantage of 8435 // 64-bit registers. In particular, sign extend the input value into the 8436 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8437 // then lfd it and fcfid it. 8438 MachineFunction &MF = DAG.getMachineFunction(); 8439 MachineFrameInfo &MFI = MF.getFrameInfo(); 8440 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8441 8442 SDValue Ld; 8443 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8444 ReuseLoadInfo RLI; 8445 bool ReusingLoad; 8446 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8447 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8448 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8449 8450 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Src, FIdx, 8451 MachinePointerInfo::getFixedStack( 8452 DAG.getMachineFunction(), FrameIdx)); 8453 8454 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8455 "Expected an i32 store"); 8456 8457 RLI.Ptr = FIdx; 8458 RLI.Chain = Store; 8459 RLI.MPI = 8460 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8461 RLI.Alignment = Align(4); 8462 } 8463 8464 MachineMemOperand *MMO = 8465 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8466 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8467 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8468 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8469 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8470 MVT::i32, MMO); 8471 if (ReusingLoad) 8472 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8473 } else { 8474 assert(Subtarget.isPPC64() && 8475 "i32->FP without LFIWAX supported only on PPC64"); 8476 8477 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8478 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8479 8480 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8481 8482 // STD the extended value into the stack slot. 8483 SDValue Store = DAG.getStore( 8484 DAG.getEntryNode(), dl, Ext64, FIdx, 8485 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8486 8487 // Load the value as a double. 8488 Ld = DAG.getLoad( 8489 MVT::f64, dl, Store, FIdx, 8490 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8491 } 8492 8493 // FCFID it and return it. 8494 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget); 8495 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8496 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8497 DAG.getIntPtrConstant(0, dl)); 8498 return FP; 8499 } 8500 8501 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8502 SelectionDAG &DAG) const { 8503 SDLoc dl(Op); 8504 /* 8505 The rounding mode is in bits 30:31 of FPSR, and has the following 8506 settings: 8507 00 Round to nearest 8508 01 Round to 0 8509 10 Round to +inf 8510 11 Round to -inf 8511 8512 FLT_ROUNDS, on the other hand, expects the following: 8513 -1 Undefined 8514 0 Round to 0 8515 1 Round to nearest 8516 2 Round to +inf 8517 3 Round to -inf 8518 8519 To perform the conversion, we do: 8520 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8521 */ 8522 8523 MachineFunction &MF = DAG.getMachineFunction(); 8524 EVT VT = Op.getValueType(); 8525 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8526 8527 // Save FP Control Word to register 8528 SDValue Chain = Op.getOperand(0); 8529 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8530 Chain = MFFS.getValue(1); 8531 8532 // Save FP register to stack slot 8533 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8534 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8535 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8536 8537 // Load FP Control Word from low 32 bits of stack slot. 8538 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8539 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8540 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8541 Chain = CWD.getValue(1); 8542 8543 // Transform as necessary 8544 SDValue CWD1 = 8545 DAG.getNode(ISD::AND, dl, MVT::i32, 8546 CWD, DAG.getConstant(3, dl, MVT::i32)); 8547 SDValue CWD2 = 8548 DAG.getNode(ISD::SRL, dl, MVT::i32, 8549 DAG.getNode(ISD::AND, dl, MVT::i32, 8550 DAG.getNode(ISD::XOR, dl, MVT::i32, 8551 CWD, DAG.getConstant(3, dl, MVT::i32)), 8552 DAG.getConstant(3, dl, MVT::i32)), 8553 DAG.getConstant(1, dl, MVT::i32)); 8554 8555 SDValue RetVal = 8556 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8557 8558 RetVal = 8559 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8560 dl, VT, RetVal); 8561 8562 return DAG.getMergeValues({RetVal, Chain}, dl); 8563 } 8564 8565 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8566 EVT VT = Op.getValueType(); 8567 unsigned BitWidth = VT.getSizeInBits(); 8568 SDLoc dl(Op); 8569 assert(Op.getNumOperands() == 3 && 8570 VT == Op.getOperand(1).getValueType() && 8571 "Unexpected SHL!"); 8572 8573 // Expand into a bunch of logical ops. Note that these ops 8574 // depend on the PPC behavior for oversized shift amounts. 8575 SDValue Lo = Op.getOperand(0); 8576 SDValue Hi = Op.getOperand(1); 8577 SDValue Amt = Op.getOperand(2); 8578 EVT AmtVT = Amt.getValueType(); 8579 8580 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8581 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8582 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8583 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8584 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8585 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8586 DAG.getConstant(-BitWidth, dl, AmtVT)); 8587 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8588 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8589 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8590 SDValue OutOps[] = { OutLo, OutHi }; 8591 return DAG.getMergeValues(OutOps, dl); 8592 } 8593 8594 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8595 EVT VT = Op.getValueType(); 8596 SDLoc dl(Op); 8597 unsigned BitWidth = VT.getSizeInBits(); 8598 assert(Op.getNumOperands() == 3 && 8599 VT == Op.getOperand(1).getValueType() && 8600 "Unexpected SRL!"); 8601 8602 // Expand into a bunch of logical ops. Note that these ops 8603 // depend on the PPC behavior for oversized shift amounts. 8604 SDValue Lo = Op.getOperand(0); 8605 SDValue Hi = Op.getOperand(1); 8606 SDValue Amt = Op.getOperand(2); 8607 EVT AmtVT = Amt.getValueType(); 8608 8609 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8610 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8611 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8612 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8613 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8614 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8615 DAG.getConstant(-BitWidth, dl, AmtVT)); 8616 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8617 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8618 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8619 SDValue OutOps[] = { OutLo, OutHi }; 8620 return DAG.getMergeValues(OutOps, dl); 8621 } 8622 8623 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8624 SDLoc dl(Op); 8625 EVT VT = Op.getValueType(); 8626 unsigned BitWidth = VT.getSizeInBits(); 8627 assert(Op.getNumOperands() == 3 && 8628 VT == Op.getOperand(1).getValueType() && 8629 "Unexpected SRA!"); 8630 8631 // Expand into a bunch of logical ops, followed by a select_cc. 8632 SDValue Lo = Op.getOperand(0); 8633 SDValue Hi = Op.getOperand(1); 8634 SDValue Amt = Op.getOperand(2); 8635 EVT AmtVT = Amt.getValueType(); 8636 8637 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8638 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8639 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8640 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8641 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8642 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8643 DAG.getConstant(-BitWidth, dl, AmtVT)); 8644 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8645 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8646 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8647 Tmp4, Tmp6, ISD::SETLE); 8648 SDValue OutOps[] = { OutLo, OutHi }; 8649 return DAG.getMergeValues(OutOps, dl); 8650 } 8651 8652 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8653 SelectionDAG &DAG) const { 8654 SDLoc dl(Op); 8655 EVT VT = Op.getValueType(); 8656 unsigned BitWidth = VT.getSizeInBits(); 8657 8658 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8659 SDValue X = Op.getOperand(0); 8660 SDValue Y = Op.getOperand(1); 8661 SDValue Z = Op.getOperand(2); 8662 EVT AmtVT = Z.getValueType(); 8663 8664 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8665 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8666 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8667 // on PowerPC shift by BW being well defined. 8668 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8669 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8670 SDValue SubZ = 8671 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8672 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8673 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8674 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8675 } 8676 8677 //===----------------------------------------------------------------------===// 8678 // Vector related lowering. 8679 // 8680 8681 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8682 /// element size of SplatSize. Cast the result to VT. 8683 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8684 SelectionDAG &DAG, const SDLoc &dl) { 8685 static const MVT VTys[] = { // canonical VT to use for each size. 8686 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8687 }; 8688 8689 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8690 8691 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8692 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8693 SplatSize = 1; 8694 Val = 0xFF; 8695 } 8696 8697 EVT CanonicalVT = VTys[SplatSize-1]; 8698 8699 // Build a canonical splat for this value. 8700 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8701 } 8702 8703 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8704 /// specified intrinsic ID. 8705 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8706 const SDLoc &dl, EVT DestVT = MVT::Other) { 8707 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8708 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8709 DAG.getConstant(IID, dl, MVT::i32), Op); 8710 } 8711 8712 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8713 /// specified intrinsic ID. 8714 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8715 SelectionDAG &DAG, const SDLoc &dl, 8716 EVT DestVT = MVT::Other) { 8717 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8718 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8719 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8720 } 8721 8722 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8723 /// specified intrinsic ID. 8724 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8725 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8726 EVT DestVT = MVT::Other) { 8727 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8728 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8729 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8730 } 8731 8732 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8733 /// amount. The result has the specified value type. 8734 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8735 SelectionDAG &DAG, const SDLoc &dl) { 8736 // Force LHS/RHS to be the right type. 8737 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8738 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8739 8740 int Ops[16]; 8741 for (unsigned i = 0; i != 16; ++i) 8742 Ops[i] = i + Amt; 8743 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8744 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8745 } 8746 8747 /// Do we have an efficient pattern in a .td file for this node? 8748 /// 8749 /// \param V - pointer to the BuildVectorSDNode being matched 8750 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8751 /// 8752 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8753 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8754 /// the opposite is true (expansion is beneficial) are: 8755 /// - The node builds a vector out of integers that are not 32 or 64-bits 8756 /// - The node builds a vector out of constants 8757 /// - The node is a "load-and-splat" 8758 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8759 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8760 bool HasDirectMove, 8761 bool HasP8Vector) { 8762 EVT VecVT = V->getValueType(0); 8763 bool RightType = VecVT == MVT::v2f64 || 8764 (HasP8Vector && VecVT == MVT::v4f32) || 8765 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8766 if (!RightType) 8767 return false; 8768 8769 bool IsSplat = true; 8770 bool IsLoad = false; 8771 SDValue Op0 = V->getOperand(0); 8772 8773 // This function is called in a block that confirms the node is not a constant 8774 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8775 // different constants. 8776 if (V->isConstant()) 8777 return false; 8778 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8779 if (V->getOperand(i).isUndef()) 8780 return false; 8781 // We want to expand nodes that represent load-and-splat even if the 8782 // loaded value is a floating point truncation or conversion to int. 8783 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8784 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8785 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8786 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8787 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8788 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8789 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8790 IsLoad = true; 8791 // If the operands are different or the input is not a load and has more 8792 // uses than just this BV node, then it isn't a splat. 8793 if (V->getOperand(i) != Op0 || 8794 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8795 IsSplat = false; 8796 } 8797 return !(IsSplat && IsLoad); 8798 } 8799 8800 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8801 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8802 8803 SDLoc dl(Op); 8804 SDValue Op0 = Op->getOperand(0); 8805 8806 if ((Op.getValueType() != MVT::f128) || 8807 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8808 (Op0.getOperand(0).getValueType() != MVT::i64) || 8809 (Op0.getOperand(1).getValueType() != MVT::i64)) 8810 return SDValue(); 8811 8812 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8813 Op0.getOperand(1)); 8814 } 8815 8816 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8817 const SDValue *InputLoad = &Op; 8818 if (InputLoad->getOpcode() == ISD::BITCAST) 8819 InputLoad = &InputLoad->getOperand(0); 8820 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8821 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8822 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8823 InputLoad = &InputLoad->getOperand(0); 8824 } 8825 if (InputLoad->getOpcode() != ISD::LOAD) 8826 return nullptr; 8827 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8828 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8829 } 8830 8831 // Convert the argument APFloat to a single precision APFloat if there is no 8832 // loss in information during the conversion to single precision APFloat and the 8833 // resulting number is not a denormal number. Return true if successful. 8834 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8835 APFloat APFloatToConvert = ArgAPFloat; 8836 bool LosesInfo = true; 8837 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8838 &LosesInfo); 8839 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8840 if (Success) 8841 ArgAPFloat = APFloatToConvert; 8842 return Success; 8843 } 8844 8845 // Bitcast the argument APInt to a double and convert it to a single precision 8846 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8847 // argument if there is no loss in information during the conversion from 8848 // double to single precision APFloat and the resulting number is not a denormal 8849 // number. Return true if successful. 8850 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8851 double DpValue = ArgAPInt.bitsToDouble(); 8852 APFloat APFloatDp(DpValue); 8853 bool Success = convertToNonDenormSingle(APFloatDp); 8854 if (Success) 8855 ArgAPInt = APFloatDp.bitcastToAPInt(); 8856 return Success; 8857 } 8858 8859 // If this is a case we can't handle, return null and let the default 8860 // expansion code take care of it. If we CAN select this case, and if it 8861 // selects to a single instruction, return Op. Otherwise, if we can codegen 8862 // this case more efficiently than a constant pool load, lower it to the 8863 // sequence of ops that should be used. 8864 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8865 SelectionDAG &DAG) const { 8866 SDLoc dl(Op); 8867 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8868 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8869 8870 // Check if this is a splat of a constant value. 8871 APInt APSplatBits, APSplatUndef; 8872 unsigned SplatBitSize; 8873 bool HasAnyUndefs; 8874 bool BVNIsConstantSplat = 8875 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8876 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 8877 8878 // If it is a splat of a double, check if we can shrink it to a 32 bit 8879 // non-denormal float which when converted back to double gives us the same 8880 // double. This is to exploit the XXSPLTIDP instruction. 8881 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 8882 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 8883 convertToNonDenormSingle(APSplatBits)) { 8884 SDValue SplatNode = DAG.getNode( 8885 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 8886 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 8887 return DAG.getBitcast(Op.getValueType(), SplatNode); 8888 } 8889 8890 if (!BVNIsConstantSplat || SplatBitSize > 32) { 8891 8892 bool IsPermutedLoad = false; 8893 const SDValue *InputLoad = 8894 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 8895 // Handle load-and-splat patterns as we have instructions that will do this 8896 // in one go. 8897 if (InputLoad && DAG.isSplatValue(Op, true)) { 8898 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8899 8900 // We have handling for 4 and 8 byte elements. 8901 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8902 8903 // Checking for a single use of this load, we have to check for vector 8904 // width (128 bits) / ElementSize uses (since each operand of the 8905 // BUILD_VECTOR is a separate use of the value. 8906 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8907 ((Subtarget.hasVSX() && ElementSize == 64) || 8908 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8909 SDValue Ops[] = { 8910 LD->getChain(), // Chain 8911 LD->getBasePtr(), // Ptr 8912 DAG.getValueType(Op.getValueType()) // VT 8913 }; 8914 return 8915 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8916 DAG.getVTList(Op.getValueType(), MVT::Other), 8917 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8918 } 8919 } 8920 8921 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8922 // lowered to VSX instructions under certain conditions. 8923 // Without VSX, there is no pattern more efficient than expanding the node. 8924 if (Subtarget.hasVSX() && 8925 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8926 Subtarget.hasP8Vector())) 8927 return Op; 8928 return SDValue(); 8929 } 8930 8931 uint64_t SplatBits = APSplatBits.getZExtValue(); 8932 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 8933 unsigned SplatSize = SplatBitSize / 8; 8934 8935 // First, handle single instruction cases. 8936 8937 // All zeros? 8938 if (SplatBits == 0) { 8939 // Canonicalize all zero vectors to be v4i32. 8940 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8941 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8942 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8943 } 8944 return Op; 8945 } 8946 8947 // We have XXSPLTIW for constant splats four bytes wide. 8948 // Given vector length is a multiple of 4, 2-byte splats can be replaced 8949 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 8950 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 8951 // turned into a 4-byte splat of 0xABABABAB. 8952 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 8953 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 8954 Op.getValueType(), DAG, dl); 8955 8956 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 8957 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8958 dl); 8959 8960 // We have XXSPLTIB for constant splats one byte wide. 8961 if (Subtarget.hasP9Vector() && SplatSize == 1) 8962 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 8963 dl); 8964 8965 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8966 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8967 (32-SplatBitSize)); 8968 if (SextVal >= -16 && SextVal <= 15) 8969 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 8970 dl); 8971 8972 // Two instruction sequences. 8973 8974 // If this value is in the range [-32,30] and is even, use: 8975 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8976 // If this value is in the range [17,31] and is odd, use: 8977 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8978 // If this value is in the range [-31,-17] and is odd, use: 8979 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8980 // Note the last two are three-instruction sequences. 8981 if (SextVal >= -32 && SextVal <= 31) { 8982 // To avoid having these optimizations undone by constant folding, 8983 // we convert to a pseudo that will be expanded later into one of 8984 // the above forms. 8985 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8986 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8987 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8988 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8989 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8990 if (VT == Op.getValueType()) 8991 return RetVal; 8992 else 8993 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8994 } 8995 8996 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8997 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8998 // for fneg/fabs. 8999 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9000 // Make -1 and vspltisw -1: 9001 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9002 9003 // Make the VSLW intrinsic, computing 0x8000_0000. 9004 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9005 OnesV, DAG, dl); 9006 9007 // xor by OnesV to invert it. 9008 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9009 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9010 } 9011 9012 // Check to see if this is a wide variety of vsplti*, binop self cases. 9013 static const signed char SplatCsts[] = { 9014 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9015 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9016 }; 9017 9018 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9019 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9020 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9021 int i = SplatCsts[idx]; 9022 9023 // Figure out what shift amount will be used by altivec if shifted by i in 9024 // this splat size. 9025 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9026 9027 // vsplti + shl self. 9028 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9029 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9030 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9031 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9032 Intrinsic::ppc_altivec_vslw 9033 }; 9034 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9035 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9036 } 9037 9038 // vsplti + srl self. 9039 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9040 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9041 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9042 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9043 Intrinsic::ppc_altivec_vsrw 9044 }; 9045 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9046 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9047 } 9048 9049 // vsplti + sra self. 9050 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9051 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9052 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9053 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9054 Intrinsic::ppc_altivec_vsraw 9055 }; 9056 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9057 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9058 } 9059 9060 // vsplti + rol self. 9061 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9062 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9063 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9064 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9065 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9066 Intrinsic::ppc_altivec_vrlw 9067 }; 9068 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9069 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9070 } 9071 9072 // t = vsplti c, result = vsldoi t, t, 1 9073 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9074 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9075 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9076 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9077 } 9078 // t = vsplti c, result = vsldoi t, t, 2 9079 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9080 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9081 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9082 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9083 } 9084 // t = vsplti c, result = vsldoi t, t, 3 9085 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9086 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9087 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9088 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9089 } 9090 } 9091 9092 return SDValue(); 9093 } 9094 9095 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9096 /// the specified operations to build the shuffle. 9097 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9098 SDValue RHS, SelectionDAG &DAG, 9099 const SDLoc &dl) { 9100 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9101 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9102 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9103 9104 enum { 9105 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9106 OP_VMRGHW, 9107 OP_VMRGLW, 9108 OP_VSPLTISW0, 9109 OP_VSPLTISW1, 9110 OP_VSPLTISW2, 9111 OP_VSPLTISW3, 9112 OP_VSLDOI4, 9113 OP_VSLDOI8, 9114 OP_VSLDOI12 9115 }; 9116 9117 if (OpNum == OP_COPY) { 9118 if (LHSID == (1*9+2)*9+3) return LHS; 9119 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9120 return RHS; 9121 } 9122 9123 SDValue OpLHS, OpRHS; 9124 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9125 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9126 9127 int ShufIdxs[16]; 9128 switch (OpNum) { 9129 default: llvm_unreachable("Unknown i32 permute!"); 9130 case OP_VMRGHW: 9131 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9132 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9133 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9134 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9135 break; 9136 case OP_VMRGLW: 9137 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9138 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9139 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9140 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9141 break; 9142 case OP_VSPLTISW0: 9143 for (unsigned i = 0; i != 16; ++i) 9144 ShufIdxs[i] = (i&3)+0; 9145 break; 9146 case OP_VSPLTISW1: 9147 for (unsigned i = 0; i != 16; ++i) 9148 ShufIdxs[i] = (i&3)+4; 9149 break; 9150 case OP_VSPLTISW2: 9151 for (unsigned i = 0; i != 16; ++i) 9152 ShufIdxs[i] = (i&3)+8; 9153 break; 9154 case OP_VSPLTISW3: 9155 for (unsigned i = 0; i != 16; ++i) 9156 ShufIdxs[i] = (i&3)+12; 9157 break; 9158 case OP_VSLDOI4: 9159 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9160 case OP_VSLDOI8: 9161 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9162 case OP_VSLDOI12: 9163 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9164 } 9165 EVT VT = OpLHS.getValueType(); 9166 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9167 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9168 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9169 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9170 } 9171 9172 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9173 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9174 /// SDValue. 9175 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9176 SelectionDAG &DAG) const { 9177 const unsigned BytesInVector = 16; 9178 bool IsLE = Subtarget.isLittleEndian(); 9179 SDLoc dl(N); 9180 SDValue V1 = N->getOperand(0); 9181 SDValue V2 = N->getOperand(1); 9182 unsigned ShiftElts = 0, InsertAtByte = 0; 9183 bool Swap = false; 9184 9185 // Shifts required to get the byte we want at element 7. 9186 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9187 0, 15, 14, 13, 12, 11, 10, 9}; 9188 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9189 1, 2, 3, 4, 5, 6, 7, 8}; 9190 9191 ArrayRef<int> Mask = N->getMask(); 9192 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9193 9194 // For each mask element, find out if we're just inserting something 9195 // from V2 into V1 or vice versa. 9196 // Possible permutations inserting an element from V2 into V1: 9197 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9198 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9199 // ... 9200 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9201 // Inserting from V1 into V2 will be similar, except mask range will be 9202 // [16,31]. 9203 9204 bool FoundCandidate = false; 9205 // If both vector operands for the shuffle are the same vector, the mask 9206 // will contain only elements from the first one and the second one will be 9207 // undef. 9208 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9209 // Go through the mask of half-words to find an element that's being moved 9210 // from one vector to the other. 9211 for (unsigned i = 0; i < BytesInVector; ++i) { 9212 unsigned CurrentElement = Mask[i]; 9213 // If 2nd operand is undefined, we should only look for element 7 in the 9214 // Mask. 9215 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9216 continue; 9217 9218 bool OtherElementsInOrder = true; 9219 // Examine the other elements in the Mask to see if they're in original 9220 // order. 9221 for (unsigned j = 0; j < BytesInVector; ++j) { 9222 if (j == i) 9223 continue; 9224 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9225 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9226 // in which we always assume we're always picking from the 1st operand. 9227 int MaskOffset = 9228 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9229 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9230 OtherElementsInOrder = false; 9231 break; 9232 } 9233 } 9234 // If other elements are in original order, we record the number of shifts 9235 // we need to get the element we want into element 7. Also record which byte 9236 // in the vector we should insert into. 9237 if (OtherElementsInOrder) { 9238 // If 2nd operand is undefined, we assume no shifts and no swapping. 9239 if (V2.isUndef()) { 9240 ShiftElts = 0; 9241 Swap = false; 9242 } else { 9243 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9244 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9245 : BigEndianShifts[CurrentElement & 0xF]; 9246 Swap = CurrentElement < BytesInVector; 9247 } 9248 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9249 FoundCandidate = true; 9250 break; 9251 } 9252 } 9253 9254 if (!FoundCandidate) 9255 return SDValue(); 9256 9257 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9258 // optionally with VECSHL if shift is required. 9259 if (Swap) 9260 std::swap(V1, V2); 9261 if (V2.isUndef()) 9262 V2 = V1; 9263 if (ShiftElts) { 9264 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9265 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9266 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9267 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9268 } 9269 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9270 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9271 } 9272 9273 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9274 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9275 /// SDValue. 9276 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9277 SelectionDAG &DAG) const { 9278 const unsigned NumHalfWords = 8; 9279 const unsigned BytesInVector = NumHalfWords * 2; 9280 // Check that the shuffle is on half-words. 9281 if (!isNByteElemShuffleMask(N, 2, 1)) 9282 return SDValue(); 9283 9284 bool IsLE = Subtarget.isLittleEndian(); 9285 SDLoc dl(N); 9286 SDValue V1 = N->getOperand(0); 9287 SDValue V2 = N->getOperand(1); 9288 unsigned ShiftElts = 0, InsertAtByte = 0; 9289 bool Swap = false; 9290 9291 // Shifts required to get the half-word we want at element 3. 9292 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9293 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9294 9295 uint32_t Mask = 0; 9296 uint32_t OriginalOrderLow = 0x1234567; 9297 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9298 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9299 // 32-bit space, only need 4-bit nibbles per element. 9300 for (unsigned i = 0; i < NumHalfWords; ++i) { 9301 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9302 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9303 } 9304 9305 // For each mask element, find out if we're just inserting something 9306 // from V2 into V1 or vice versa. Possible permutations inserting an element 9307 // from V2 into V1: 9308 // X, 1, 2, 3, 4, 5, 6, 7 9309 // 0, X, 2, 3, 4, 5, 6, 7 9310 // 0, 1, X, 3, 4, 5, 6, 7 9311 // 0, 1, 2, X, 4, 5, 6, 7 9312 // 0, 1, 2, 3, X, 5, 6, 7 9313 // 0, 1, 2, 3, 4, X, 6, 7 9314 // 0, 1, 2, 3, 4, 5, X, 7 9315 // 0, 1, 2, 3, 4, 5, 6, X 9316 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9317 9318 bool FoundCandidate = false; 9319 // Go through the mask of half-words to find an element that's being moved 9320 // from one vector to the other. 9321 for (unsigned i = 0; i < NumHalfWords; ++i) { 9322 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9323 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9324 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9325 uint32_t TargetOrder = 0x0; 9326 9327 // If both vector operands for the shuffle are the same vector, the mask 9328 // will contain only elements from the first one and the second one will be 9329 // undef. 9330 if (V2.isUndef()) { 9331 ShiftElts = 0; 9332 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9333 TargetOrder = OriginalOrderLow; 9334 Swap = false; 9335 // Skip if not the correct element or mask of other elements don't equal 9336 // to our expected order. 9337 if (MaskOneElt == VINSERTHSrcElem && 9338 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9339 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9340 FoundCandidate = true; 9341 break; 9342 } 9343 } else { // If both operands are defined. 9344 // Target order is [8,15] if the current mask is between [0,7]. 9345 TargetOrder = 9346 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9347 // Skip if mask of other elements don't equal our expected order. 9348 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9349 // We only need the last 3 bits for the number of shifts. 9350 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9351 : BigEndianShifts[MaskOneElt & 0x7]; 9352 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9353 Swap = MaskOneElt < NumHalfWords; 9354 FoundCandidate = true; 9355 break; 9356 } 9357 } 9358 } 9359 9360 if (!FoundCandidate) 9361 return SDValue(); 9362 9363 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9364 // optionally with VECSHL if shift is required. 9365 if (Swap) 9366 std::swap(V1, V2); 9367 if (V2.isUndef()) 9368 V2 = V1; 9369 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9370 if (ShiftElts) { 9371 // Double ShiftElts because we're left shifting on v16i8 type. 9372 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9373 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9374 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9375 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9376 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9377 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9378 } 9379 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9380 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9381 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9382 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9383 } 9384 9385 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9386 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9387 /// return the default SDValue. 9388 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9389 SelectionDAG &DAG) const { 9390 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9391 // to v16i8. Peek through the bitcasts to get the actual operands. 9392 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9393 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9394 9395 auto ShuffleMask = SVN->getMask(); 9396 SDValue VecShuffle(SVN, 0); 9397 SDLoc DL(SVN); 9398 9399 // Check that we have a four byte shuffle. 9400 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9401 return SDValue(); 9402 9403 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9404 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9405 std::swap(LHS, RHS); 9406 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9407 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9408 } 9409 9410 // Ensure that the RHS is a vector of constants. 9411 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9412 if (!BVN) 9413 return SDValue(); 9414 9415 // Check if RHS is a splat of 4-bytes (or smaller). 9416 APInt APSplatValue, APSplatUndef; 9417 unsigned SplatBitSize; 9418 bool HasAnyUndefs; 9419 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9420 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9421 SplatBitSize > 32) 9422 return SDValue(); 9423 9424 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9425 // The instruction splats a constant C into two words of the source vector 9426 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9427 // Thus we check that the shuffle mask is the equivalent of 9428 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9429 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9430 // within each word are consecutive, so we only need to check the first byte. 9431 SDValue Index; 9432 bool IsLE = Subtarget.isLittleEndian(); 9433 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9434 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9435 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9436 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9437 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9438 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9439 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9440 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9441 else 9442 return SDValue(); 9443 9444 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9445 // for XXSPLTI32DX. 9446 unsigned SplatVal = APSplatValue.getZExtValue(); 9447 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9448 SplatVal |= (SplatVal << SplatBitSize); 9449 9450 SDValue SplatNode = DAG.getNode( 9451 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9452 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9453 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9454 } 9455 9456 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9457 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9458 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9459 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9460 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9461 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9462 assert(Op.getValueType() == MVT::v1i128 && 9463 "Only set v1i128 as custom, other type shouldn't reach here!"); 9464 SDLoc dl(Op); 9465 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9466 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9467 unsigned SHLAmt = N1.getConstantOperandVal(0); 9468 if (SHLAmt % 8 == 0) { 9469 SmallVector<int, 16> Mask(16, 0); 9470 std::iota(Mask.begin(), Mask.end(), 0); 9471 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9472 if (SDValue Shuffle = 9473 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9474 DAG.getUNDEF(MVT::v16i8), Mask)) 9475 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9476 } 9477 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9478 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9479 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9480 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9481 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9482 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9483 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9484 } 9485 9486 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9487 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9488 /// return the code it can be lowered into. Worst case, it can always be 9489 /// lowered into a vperm. 9490 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9491 SelectionDAG &DAG) const { 9492 SDLoc dl(Op); 9493 SDValue V1 = Op.getOperand(0); 9494 SDValue V2 = Op.getOperand(1); 9495 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9496 9497 // Any nodes that were combined in the target-independent combiner prior 9498 // to vector legalization will not be sent to the target combine. Try to 9499 // combine it here. 9500 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9501 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9502 return NewShuffle; 9503 Op = NewShuffle; 9504 SVOp = cast<ShuffleVectorSDNode>(Op); 9505 V1 = Op.getOperand(0); 9506 V2 = Op.getOperand(1); 9507 } 9508 EVT VT = Op.getValueType(); 9509 bool isLittleEndian = Subtarget.isLittleEndian(); 9510 9511 unsigned ShiftElts, InsertAtByte; 9512 bool Swap = false; 9513 9514 // If this is a load-and-splat, we can do that with a single instruction 9515 // in some cases. However if the load has multiple uses, we don't want to 9516 // combine it because that will just produce multiple loads. 9517 bool IsPermutedLoad = false; 9518 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9519 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9520 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9521 InputLoad->hasOneUse()) { 9522 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9523 int SplatIdx = 9524 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9525 9526 // The splat index for permuted loads will be in the left half of the vector 9527 // which is strictly wider than the loaded value by 8 bytes. So we need to 9528 // adjust the splat index to point to the correct address in memory. 9529 if (IsPermutedLoad) { 9530 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9531 SplatIdx += IsFourByte ? 2 : 1; 9532 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9533 "Splat of a value outside of the loaded memory"); 9534 } 9535 9536 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9537 // For 4-byte load-and-splat, we need Power9. 9538 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9539 uint64_t Offset = 0; 9540 if (IsFourByte) 9541 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9542 else 9543 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9544 9545 SDValue BasePtr = LD->getBasePtr(); 9546 if (Offset != 0) 9547 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9548 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9549 SDValue Ops[] = { 9550 LD->getChain(), // Chain 9551 BasePtr, // BasePtr 9552 DAG.getValueType(Op.getValueType()) // VT 9553 }; 9554 SDVTList VTL = 9555 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9556 SDValue LdSplt = 9557 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9558 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9559 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9560 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9561 return LdSplt; 9562 } 9563 } 9564 if (Subtarget.hasP9Vector() && 9565 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9566 isLittleEndian)) { 9567 if (Swap) 9568 std::swap(V1, V2); 9569 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9570 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9571 if (ShiftElts) { 9572 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9573 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9574 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9575 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9576 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9577 } 9578 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9579 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9580 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9581 } 9582 9583 if (Subtarget.hasPrefixInstrs()) { 9584 SDValue SplatInsertNode; 9585 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9586 return SplatInsertNode; 9587 } 9588 9589 if (Subtarget.hasP9Altivec()) { 9590 SDValue NewISDNode; 9591 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9592 return NewISDNode; 9593 9594 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9595 return NewISDNode; 9596 } 9597 9598 if (Subtarget.hasVSX() && 9599 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9600 if (Swap) 9601 std::swap(V1, V2); 9602 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9603 SDValue Conv2 = 9604 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9605 9606 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9607 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9608 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9609 } 9610 9611 if (Subtarget.hasVSX() && 9612 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9613 if (Swap) 9614 std::swap(V1, V2); 9615 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9616 SDValue Conv2 = 9617 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9618 9619 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9620 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9621 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9622 } 9623 9624 if (Subtarget.hasP9Vector()) { 9625 if (PPC::isXXBRHShuffleMask(SVOp)) { 9626 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9627 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9628 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9629 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9630 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9631 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9632 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9633 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9634 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9635 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9636 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9637 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9638 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9639 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9640 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9641 } 9642 } 9643 9644 if (Subtarget.hasVSX()) { 9645 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9646 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9647 9648 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9649 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9650 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9651 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9652 } 9653 9654 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9655 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9656 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9657 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9658 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9659 } 9660 } 9661 9662 // Cases that are handled by instructions that take permute immediates 9663 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9664 // selected by the instruction selector. 9665 if (V2.isUndef()) { 9666 if (PPC::isSplatShuffleMask(SVOp, 1) || 9667 PPC::isSplatShuffleMask(SVOp, 2) || 9668 PPC::isSplatShuffleMask(SVOp, 4) || 9669 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9670 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9671 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9672 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9673 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9674 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9675 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9676 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9677 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9678 (Subtarget.hasP8Altivec() && ( 9679 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9680 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9681 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9682 return Op; 9683 } 9684 } 9685 9686 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9687 // and produce a fixed permutation. If any of these match, do not lower to 9688 // VPERM. 9689 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9690 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9691 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9692 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9693 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9694 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9695 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9696 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9697 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9698 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9699 (Subtarget.hasP8Altivec() && ( 9700 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9701 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9702 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9703 return Op; 9704 9705 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9706 // perfect shuffle table to emit an optimal matching sequence. 9707 ArrayRef<int> PermMask = SVOp->getMask(); 9708 9709 unsigned PFIndexes[4]; 9710 bool isFourElementShuffle = true; 9711 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9712 unsigned EltNo = 8; // Start out undef. 9713 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9714 if (PermMask[i*4+j] < 0) 9715 continue; // Undef, ignore it. 9716 9717 unsigned ByteSource = PermMask[i*4+j]; 9718 if ((ByteSource & 3) != j) { 9719 isFourElementShuffle = false; 9720 break; 9721 } 9722 9723 if (EltNo == 8) { 9724 EltNo = ByteSource/4; 9725 } else if (EltNo != ByteSource/4) { 9726 isFourElementShuffle = false; 9727 break; 9728 } 9729 } 9730 PFIndexes[i] = EltNo; 9731 } 9732 9733 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9734 // perfect shuffle vector to determine if it is cost effective to do this as 9735 // discrete instructions, or whether we should use a vperm. 9736 // For now, we skip this for little endian until such time as we have a 9737 // little-endian perfect shuffle table. 9738 if (isFourElementShuffle && !isLittleEndian) { 9739 // Compute the index in the perfect shuffle table. 9740 unsigned PFTableIndex = 9741 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9742 9743 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9744 unsigned Cost = (PFEntry >> 30); 9745 9746 // Determining when to avoid vperm is tricky. Many things affect the cost 9747 // of vperm, particularly how many times the perm mask needs to be computed. 9748 // For example, if the perm mask can be hoisted out of a loop or is already 9749 // used (perhaps because there are multiple permutes with the same shuffle 9750 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9751 // the loop requires an extra register. 9752 // 9753 // As a compromise, we only emit discrete instructions if the shuffle can be 9754 // generated in 3 or fewer operations. When we have loop information 9755 // available, if this block is within a loop, we should avoid using vperm 9756 // for 3-operation perms and use a constant pool load instead. 9757 if (Cost < 3) 9758 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9759 } 9760 9761 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9762 // vector that will get spilled to the constant pool. 9763 if (V2.isUndef()) V2 = V1; 9764 9765 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9766 // that it is in input element units, not in bytes. Convert now. 9767 9768 // For little endian, the order of the input vectors is reversed, and 9769 // the permutation mask is complemented with respect to 31. This is 9770 // necessary to produce proper semantics with the big-endian-biased vperm 9771 // instruction. 9772 EVT EltVT = V1.getValueType().getVectorElementType(); 9773 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9774 9775 SmallVector<SDValue, 16> ResultMask; 9776 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9777 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9778 9779 for (unsigned j = 0; j != BytesPerElement; ++j) 9780 if (isLittleEndian) 9781 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9782 dl, MVT::i32)); 9783 else 9784 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9785 MVT::i32)); 9786 } 9787 9788 ShufflesHandledWithVPERM++; 9789 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9790 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9791 LLVM_DEBUG(SVOp->dump()); 9792 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9793 LLVM_DEBUG(VPermMask.dump()); 9794 9795 if (isLittleEndian) 9796 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9797 V2, V1, VPermMask); 9798 else 9799 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9800 V1, V2, VPermMask); 9801 } 9802 9803 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9804 /// vector comparison. If it is, return true and fill in Opc/isDot with 9805 /// information about the intrinsic. 9806 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9807 bool &isDot, const PPCSubtarget &Subtarget) { 9808 unsigned IntrinsicID = 9809 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9810 CompareOpc = -1; 9811 isDot = false; 9812 switch (IntrinsicID) { 9813 default: 9814 return false; 9815 // Comparison predicates. 9816 case Intrinsic::ppc_altivec_vcmpbfp_p: 9817 CompareOpc = 966; 9818 isDot = true; 9819 break; 9820 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9821 CompareOpc = 198; 9822 isDot = true; 9823 break; 9824 case Intrinsic::ppc_altivec_vcmpequb_p: 9825 CompareOpc = 6; 9826 isDot = true; 9827 break; 9828 case Intrinsic::ppc_altivec_vcmpequh_p: 9829 CompareOpc = 70; 9830 isDot = true; 9831 break; 9832 case Intrinsic::ppc_altivec_vcmpequw_p: 9833 CompareOpc = 134; 9834 isDot = true; 9835 break; 9836 case Intrinsic::ppc_altivec_vcmpequd_p: 9837 if (Subtarget.hasP8Altivec()) { 9838 CompareOpc = 199; 9839 isDot = true; 9840 } else 9841 return false; 9842 break; 9843 case Intrinsic::ppc_altivec_vcmpneb_p: 9844 case Intrinsic::ppc_altivec_vcmpneh_p: 9845 case Intrinsic::ppc_altivec_vcmpnew_p: 9846 case Intrinsic::ppc_altivec_vcmpnezb_p: 9847 case Intrinsic::ppc_altivec_vcmpnezh_p: 9848 case Intrinsic::ppc_altivec_vcmpnezw_p: 9849 if (Subtarget.hasP9Altivec()) { 9850 switch (IntrinsicID) { 9851 default: 9852 llvm_unreachable("Unknown comparison intrinsic."); 9853 case Intrinsic::ppc_altivec_vcmpneb_p: 9854 CompareOpc = 7; 9855 break; 9856 case Intrinsic::ppc_altivec_vcmpneh_p: 9857 CompareOpc = 71; 9858 break; 9859 case Intrinsic::ppc_altivec_vcmpnew_p: 9860 CompareOpc = 135; 9861 break; 9862 case Intrinsic::ppc_altivec_vcmpnezb_p: 9863 CompareOpc = 263; 9864 break; 9865 case Intrinsic::ppc_altivec_vcmpnezh_p: 9866 CompareOpc = 327; 9867 break; 9868 case Intrinsic::ppc_altivec_vcmpnezw_p: 9869 CompareOpc = 391; 9870 break; 9871 } 9872 isDot = true; 9873 } else 9874 return false; 9875 break; 9876 case Intrinsic::ppc_altivec_vcmpgefp_p: 9877 CompareOpc = 454; 9878 isDot = true; 9879 break; 9880 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9881 CompareOpc = 710; 9882 isDot = true; 9883 break; 9884 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9885 CompareOpc = 774; 9886 isDot = true; 9887 break; 9888 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9889 CompareOpc = 838; 9890 isDot = true; 9891 break; 9892 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9893 CompareOpc = 902; 9894 isDot = true; 9895 break; 9896 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9897 if (Subtarget.hasP8Altivec()) { 9898 CompareOpc = 967; 9899 isDot = true; 9900 } else 9901 return false; 9902 break; 9903 case Intrinsic::ppc_altivec_vcmpgtub_p: 9904 CompareOpc = 518; 9905 isDot = true; 9906 break; 9907 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9908 CompareOpc = 582; 9909 isDot = true; 9910 break; 9911 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9912 CompareOpc = 646; 9913 isDot = true; 9914 break; 9915 case Intrinsic::ppc_altivec_vcmpgtud_p: 9916 if (Subtarget.hasP8Altivec()) { 9917 CompareOpc = 711; 9918 isDot = true; 9919 } else 9920 return false; 9921 break; 9922 9923 // VSX predicate comparisons use the same infrastructure 9924 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9925 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9926 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9927 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9928 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9929 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9930 if (Subtarget.hasVSX()) { 9931 switch (IntrinsicID) { 9932 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9933 CompareOpc = 99; 9934 break; 9935 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9936 CompareOpc = 115; 9937 break; 9938 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9939 CompareOpc = 107; 9940 break; 9941 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9942 CompareOpc = 67; 9943 break; 9944 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9945 CompareOpc = 83; 9946 break; 9947 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9948 CompareOpc = 75; 9949 break; 9950 } 9951 isDot = true; 9952 } else 9953 return false; 9954 break; 9955 9956 // Normal Comparisons. 9957 case Intrinsic::ppc_altivec_vcmpbfp: 9958 CompareOpc = 966; 9959 break; 9960 case Intrinsic::ppc_altivec_vcmpeqfp: 9961 CompareOpc = 198; 9962 break; 9963 case Intrinsic::ppc_altivec_vcmpequb: 9964 CompareOpc = 6; 9965 break; 9966 case Intrinsic::ppc_altivec_vcmpequh: 9967 CompareOpc = 70; 9968 break; 9969 case Intrinsic::ppc_altivec_vcmpequw: 9970 CompareOpc = 134; 9971 break; 9972 case Intrinsic::ppc_altivec_vcmpequd: 9973 if (Subtarget.hasP8Altivec()) 9974 CompareOpc = 199; 9975 else 9976 return false; 9977 break; 9978 case Intrinsic::ppc_altivec_vcmpneb: 9979 case Intrinsic::ppc_altivec_vcmpneh: 9980 case Intrinsic::ppc_altivec_vcmpnew: 9981 case Intrinsic::ppc_altivec_vcmpnezb: 9982 case Intrinsic::ppc_altivec_vcmpnezh: 9983 case Intrinsic::ppc_altivec_vcmpnezw: 9984 if (Subtarget.hasP9Altivec()) 9985 switch (IntrinsicID) { 9986 default: 9987 llvm_unreachable("Unknown comparison intrinsic."); 9988 case Intrinsic::ppc_altivec_vcmpneb: 9989 CompareOpc = 7; 9990 break; 9991 case Intrinsic::ppc_altivec_vcmpneh: 9992 CompareOpc = 71; 9993 break; 9994 case Intrinsic::ppc_altivec_vcmpnew: 9995 CompareOpc = 135; 9996 break; 9997 case Intrinsic::ppc_altivec_vcmpnezb: 9998 CompareOpc = 263; 9999 break; 10000 case Intrinsic::ppc_altivec_vcmpnezh: 10001 CompareOpc = 327; 10002 break; 10003 case Intrinsic::ppc_altivec_vcmpnezw: 10004 CompareOpc = 391; 10005 break; 10006 } 10007 else 10008 return false; 10009 break; 10010 case Intrinsic::ppc_altivec_vcmpgefp: 10011 CompareOpc = 454; 10012 break; 10013 case Intrinsic::ppc_altivec_vcmpgtfp: 10014 CompareOpc = 710; 10015 break; 10016 case Intrinsic::ppc_altivec_vcmpgtsb: 10017 CompareOpc = 774; 10018 break; 10019 case Intrinsic::ppc_altivec_vcmpgtsh: 10020 CompareOpc = 838; 10021 break; 10022 case Intrinsic::ppc_altivec_vcmpgtsw: 10023 CompareOpc = 902; 10024 break; 10025 case Intrinsic::ppc_altivec_vcmpgtsd: 10026 if (Subtarget.hasP8Altivec()) 10027 CompareOpc = 967; 10028 else 10029 return false; 10030 break; 10031 case Intrinsic::ppc_altivec_vcmpgtub: 10032 CompareOpc = 518; 10033 break; 10034 case Intrinsic::ppc_altivec_vcmpgtuh: 10035 CompareOpc = 582; 10036 break; 10037 case Intrinsic::ppc_altivec_vcmpgtuw: 10038 CompareOpc = 646; 10039 break; 10040 case Intrinsic::ppc_altivec_vcmpgtud: 10041 if (Subtarget.hasP8Altivec()) 10042 CompareOpc = 711; 10043 else 10044 return false; 10045 break; 10046 } 10047 return true; 10048 } 10049 10050 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10051 /// lower, do it, otherwise return null. 10052 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10053 SelectionDAG &DAG) const { 10054 unsigned IntrinsicID = 10055 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10056 10057 SDLoc dl(Op); 10058 10059 if (IntrinsicID == Intrinsic::thread_pointer) { 10060 // Reads the thread pointer register, used for __builtin_thread_pointer. 10061 if (Subtarget.isPPC64()) 10062 return DAG.getRegister(PPC::X13, MVT::i64); 10063 return DAG.getRegister(PPC::R2, MVT::i32); 10064 } 10065 10066 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10067 // opcode number of the comparison. 10068 int CompareOpc; 10069 bool isDot; 10070 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10071 return SDValue(); // Don't custom lower most intrinsics. 10072 10073 // If this is a non-dot comparison, make the VCMP node and we are done. 10074 if (!isDot) { 10075 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10076 Op.getOperand(1), Op.getOperand(2), 10077 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10078 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10079 } 10080 10081 // Create the PPCISD altivec 'dot' comparison node. 10082 SDValue Ops[] = { 10083 Op.getOperand(2), // LHS 10084 Op.getOperand(3), // RHS 10085 DAG.getConstant(CompareOpc, dl, MVT::i32) 10086 }; 10087 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10088 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10089 10090 // Now that we have the comparison, emit a copy from the CR to a GPR. 10091 // This is flagged to the above dot comparison. 10092 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10093 DAG.getRegister(PPC::CR6, MVT::i32), 10094 CompNode.getValue(1)); 10095 10096 // Unpack the result based on how the target uses it. 10097 unsigned BitNo; // Bit # of CR6. 10098 bool InvertBit; // Invert result? 10099 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10100 default: // Can't happen, don't crash on invalid number though. 10101 case 0: // Return the value of the EQ bit of CR6. 10102 BitNo = 0; InvertBit = false; 10103 break; 10104 case 1: // Return the inverted value of the EQ bit of CR6. 10105 BitNo = 0; InvertBit = true; 10106 break; 10107 case 2: // Return the value of the LT bit of CR6. 10108 BitNo = 2; InvertBit = false; 10109 break; 10110 case 3: // Return the inverted value of the LT bit of CR6. 10111 BitNo = 2; InvertBit = true; 10112 break; 10113 } 10114 10115 // Shift the bit into the low position. 10116 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10117 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10118 // Isolate the bit. 10119 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10120 DAG.getConstant(1, dl, MVT::i32)); 10121 10122 // If we are supposed to, toggle the bit. 10123 if (InvertBit) 10124 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10125 DAG.getConstant(1, dl, MVT::i32)); 10126 return Flags; 10127 } 10128 10129 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10130 SelectionDAG &DAG) const { 10131 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10132 // the beginning of the argument list. 10133 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10134 SDLoc DL(Op); 10135 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10136 case Intrinsic::ppc_cfence: { 10137 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10138 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10139 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10140 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10141 Op.getOperand(ArgStart + 1)), 10142 Op.getOperand(0)), 10143 0); 10144 } 10145 default: 10146 break; 10147 } 10148 return SDValue(); 10149 } 10150 10151 // Lower scalar BSWAP64 to xxbrd. 10152 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10153 SDLoc dl(Op); 10154 // MTVSRDD 10155 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10156 Op.getOperand(0)); 10157 // XXBRD 10158 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10159 // MFVSRD 10160 int VectorIndex = 0; 10161 if (Subtarget.isLittleEndian()) 10162 VectorIndex = 1; 10163 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10164 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10165 return Op; 10166 } 10167 10168 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10169 // compared to a value that is atomically loaded (atomic loads zero-extend). 10170 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10171 SelectionDAG &DAG) const { 10172 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10173 "Expecting an atomic compare-and-swap here."); 10174 SDLoc dl(Op); 10175 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10176 EVT MemVT = AtomicNode->getMemoryVT(); 10177 if (MemVT.getSizeInBits() >= 32) 10178 return Op; 10179 10180 SDValue CmpOp = Op.getOperand(2); 10181 // If this is already correctly zero-extended, leave it alone. 10182 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10183 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10184 return Op; 10185 10186 // Clear the high bits of the compare operand. 10187 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10188 SDValue NewCmpOp = 10189 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10190 DAG.getConstant(MaskVal, dl, MVT::i32)); 10191 10192 // Replace the existing compare operand with the properly zero-extended one. 10193 SmallVector<SDValue, 4> Ops; 10194 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10195 Ops.push_back(AtomicNode->getOperand(i)); 10196 Ops[2] = NewCmpOp; 10197 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10198 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10199 auto NodeTy = 10200 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10201 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10202 } 10203 10204 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10205 SelectionDAG &DAG) const { 10206 SDLoc dl(Op); 10207 // Create a stack slot that is 16-byte aligned. 10208 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10209 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10210 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10211 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10212 10213 // Store the input value into Value#0 of the stack slot. 10214 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10215 MachinePointerInfo()); 10216 // Load it out. 10217 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10218 } 10219 10220 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10221 SelectionDAG &DAG) const { 10222 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10223 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10224 10225 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10226 // We have legal lowering for constant indices but not for variable ones. 10227 if (!C) 10228 return SDValue(); 10229 10230 EVT VT = Op.getValueType(); 10231 SDLoc dl(Op); 10232 SDValue V1 = Op.getOperand(0); 10233 SDValue V2 = Op.getOperand(1); 10234 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10235 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10236 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10237 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10238 unsigned InsertAtElement = C->getZExtValue(); 10239 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10240 if (Subtarget.isLittleEndian()) { 10241 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10242 } 10243 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10244 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10245 } 10246 return Op; 10247 } 10248 10249 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10250 SDLoc dl(Op); 10251 if (Op.getValueType() == MVT::v4i32) { 10252 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10253 10254 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10255 // +16 as shift amt. 10256 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10257 SDValue RHSSwap = // = vrlw RHS, 16 10258 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10259 10260 // Shrinkify inputs to v8i16. 10261 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10262 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10263 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10264 10265 // Low parts multiplied together, generating 32-bit results (we ignore the 10266 // top parts). 10267 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10268 LHS, RHS, DAG, dl, MVT::v4i32); 10269 10270 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10271 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10272 // Shift the high parts up 16 bits. 10273 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10274 Neg16, DAG, dl); 10275 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10276 } else if (Op.getValueType() == MVT::v16i8) { 10277 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10278 bool isLittleEndian = Subtarget.isLittleEndian(); 10279 10280 // Multiply the even 8-bit parts, producing 16-bit sums. 10281 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10282 LHS, RHS, DAG, dl, MVT::v8i16); 10283 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10284 10285 // Multiply the odd 8-bit parts, producing 16-bit sums. 10286 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10287 LHS, RHS, DAG, dl, MVT::v8i16); 10288 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10289 10290 // Merge the results together. Because vmuleub and vmuloub are 10291 // instructions with a big-endian bias, we must reverse the 10292 // element numbering and reverse the meaning of "odd" and "even" 10293 // when generating little endian code. 10294 int Ops[16]; 10295 for (unsigned i = 0; i != 8; ++i) { 10296 if (isLittleEndian) { 10297 Ops[i*2 ] = 2*i; 10298 Ops[i*2+1] = 2*i+16; 10299 } else { 10300 Ops[i*2 ] = 2*i+1; 10301 Ops[i*2+1] = 2*i+1+16; 10302 } 10303 } 10304 if (isLittleEndian) 10305 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10306 else 10307 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10308 } else { 10309 llvm_unreachable("Unknown mul to lower!"); 10310 } 10311 } 10312 10313 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10314 10315 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10316 10317 EVT VT = Op.getValueType(); 10318 assert(VT.isVector() && 10319 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10320 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10321 VT == MVT::v16i8) && 10322 "Unexpected vector element type!"); 10323 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10324 "Current subtarget doesn't support smax v2i64!"); 10325 10326 // For vector abs, it can be lowered to: 10327 // abs x 10328 // ==> 10329 // y = -x 10330 // smax(x, y) 10331 10332 SDLoc dl(Op); 10333 SDValue X = Op.getOperand(0); 10334 SDValue Zero = DAG.getConstant(0, dl, VT); 10335 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10336 10337 // SMAX patch https://reviews.llvm.org/D47332 10338 // hasn't landed yet, so use intrinsic first here. 10339 // TODO: Should use SMAX directly once SMAX patch landed 10340 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10341 if (VT == MVT::v2i64) 10342 BifID = Intrinsic::ppc_altivec_vmaxsd; 10343 else if (VT == MVT::v8i16) 10344 BifID = Intrinsic::ppc_altivec_vmaxsh; 10345 else if (VT == MVT::v16i8) 10346 BifID = Intrinsic::ppc_altivec_vmaxsb; 10347 10348 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10349 } 10350 10351 // Custom lowering for fpext vf32 to v2f64 10352 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10353 10354 assert(Op.getOpcode() == ISD::FP_EXTEND && 10355 "Should only be called for ISD::FP_EXTEND"); 10356 10357 // FIXME: handle extends from half precision float vectors on P9. 10358 // We only want to custom lower an extend from v2f32 to v2f64. 10359 if (Op.getValueType() != MVT::v2f64 || 10360 Op.getOperand(0).getValueType() != MVT::v2f32) 10361 return SDValue(); 10362 10363 SDLoc dl(Op); 10364 SDValue Op0 = Op.getOperand(0); 10365 10366 switch (Op0.getOpcode()) { 10367 default: 10368 return SDValue(); 10369 case ISD::EXTRACT_SUBVECTOR: { 10370 assert(Op0.getNumOperands() == 2 && 10371 isa<ConstantSDNode>(Op0->getOperand(1)) && 10372 "Node should have 2 operands with second one being a constant!"); 10373 10374 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10375 return SDValue(); 10376 10377 // Custom lower is only done for high or low doubleword. 10378 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10379 if (Idx % 2 != 0) 10380 return SDValue(); 10381 10382 // Since input is v4f32, at this point Idx is either 0 or 2. 10383 // Shift to get the doubleword position we want. 10384 int DWord = Idx >> 1; 10385 10386 // High and low word positions are different on little endian. 10387 if (Subtarget.isLittleEndian()) 10388 DWord ^= 0x1; 10389 10390 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10391 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10392 } 10393 case ISD::FADD: 10394 case ISD::FMUL: 10395 case ISD::FSUB: { 10396 SDValue NewLoad[2]; 10397 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10398 // Ensure both input are loads. 10399 SDValue LdOp = Op0.getOperand(i); 10400 if (LdOp.getOpcode() != ISD::LOAD) 10401 return SDValue(); 10402 // Generate new load node. 10403 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10404 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10405 NewLoad[i] = DAG.getMemIntrinsicNode( 10406 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10407 LD->getMemoryVT(), LD->getMemOperand()); 10408 } 10409 SDValue NewOp = 10410 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10411 NewLoad[1], Op0.getNode()->getFlags()); 10412 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10413 DAG.getConstant(0, dl, MVT::i32)); 10414 } 10415 case ISD::LOAD: { 10416 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10417 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10418 SDValue NewLd = DAG.getMemIntrinsicNode( 10419 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10420 LD->getMemoryVT(), LD->getMemOperand()); 10421 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10422 DAG.getConstant(0, dl, MVT::i32)); 10423 } 10424 } 10425 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10426 } 10427 10428 /// LowerOperation - Provide custom lowering hooks for some operations. 10429 /// 10430 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10431 switch (Op.getOpcode()) { 10432 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10433 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10434 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10435 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10436 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10437 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10438 case ISD::SETCC: return LowerSETCC(Op, DAG); 10439 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10440 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10441 10442 // Variable argument lowering. 10443 case ISD::VASTART: return LowerVASTART(Op, DAG); 10444 case ISD::VAARG: return LowerVAARG(Op, DAG); 10445 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10446 10447 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10448 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10449 case ISD::GET_DYNAMIC_AREA_OFFSET: 10450 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10451 10452 // Exception handling lowering. 10453 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10454 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10455 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10456 10457 case ISD::LOAD: return LowerLOAD(Op, DAG); 10458 case ISD::STORE: return LowerSTORE(Op, DAG); 10459 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10460 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10461 case ISD::FP_TO_UINT: 10462 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10463 case ISD::UINT_TO_FP: 10464 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10465 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10466 10467 // Lower 64-bit shifts. 10468 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10469 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10470 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10471 10472 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10473 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10474 10475 // Vector-related lowering. 10476 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10477 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10478 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10479 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10480 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10481 case ISD::MUL: return LowerMUL(Op, DAG); 10482 case ISD::ABS: return LowerABS(Op, DAG); 10483 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10484 case ISD::ROTL: return LowerROTL(Op, DAG); 10485 10486 // For counter-based loop handling. 10487 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10488 10489 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10490 10491 // Frame & Return address. 10492 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10493 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10494 10495 case ISD::INTRINSIC_VOID: 10496 return LowerINTRINSIC_VOID(Op, DAG); 10497 case ISD::BSWAP: 10498 return LowerBSWAP(Op, DAG); 10499 case ISD::ATOMIC_CMP_SWAP: 10500 return LowerATOMIC_CMP_SWAP(Op, DAG); 10501 } 10502 } 10503 10504 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10505 SmallVectorImpl<SDValue>&Results, 10506 SelectionDAG &DAG) const { 10507 SDLoc dl(N); 10508 switch (N->getOpcode()) { 10509 default: 10510 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10511 case ISD::READCYCLECOUNTER: { 10512 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10513 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10514 10515 Results.push_back( 10516 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10517 Results.push_back(RTB.getValue(2)); 10518 break; 10519 } 10520 case ISD::INTRINSIC_W_CHAIN: { 10521 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10522 Intrinsic::loop_decrement) 10523 break; 10524 10525 assert(N->getValueType(0) == MVT::i1 && 10526 "Unexpected result type for CTR decrement intrinsic"); 10527 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10528 N->getValueType(0)); 10529 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10530 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10531 N->getOperand(1)); 10532 10533 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10534 Results.push_back(NewInt.getValue(1)); 10535 break; 10536 } 10537 case ISD::VAARG: { 10538 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10539 return; 10540 10541 EVT VT = N->getValueType(0); 10542 10543 if (VT == MVT::i64) { 10544 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10545 10546 Results.push_back(NewNode); 10547 Results.push_back(NewNode.getValue(1)); 10548 } 10549 return; 10550 } 10551 case ISD::FP_TO_SINT: 10552 case ISD::FP_TO_UINT: 10553 // LowerFP_TO_INT() can only handle f32 and f64. 10554 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10555 return; 10556 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10557 return; 10558 case ISD::TRUNCATE: { 10559 EVT TrgVT = N->getValueType(0); 10560 EVT OpVT = N->getOperand(0).getValueType(); 10561 if (TrgVT.isVector() && 10562 isOperationCustom(N->getOpcode(), TrgVT) && 10563 OpVT.getSizeInBits() <= 128 && 10564 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10565 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10566 return; 10567 } 10568 case ISD::BITCAST: 10569 // Don't handle bitcast here. 10570 return; 10571 case ISD::FP_EXTEND: 10572 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10573 if (Lowered) 10574 Results.push_back(Lowered); 10575 return; 10576 } 10577 } 10578 10579 //===----------------------------------------------------------------------===// 10580 // Other Lowering Code 10581 //===----------------------------------------------------------------------===// 10582 10583 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10584 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10585 Function *Func = Intrinsic::getDeclaration(M, Id); 10586 return Builder.CreateCall(Func, {}); 10587 } 10588 10589 // The mappings for emitLeading/TrailingFence is taken from 10590 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10591 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10592 Instruction *Inst, 10593 AtomicOrdering Ord) const { 10594 if (Ord == AtomicOrdering::SequentiallyConsistent) 10595 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10596 if (isReleaseOrStronger(Ord)) 10597 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10598 return nullptr; 10599 } 10600 10601 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10602 Instruction *Inst, 10603 AtomicOrdering Ord) const { 10604 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10605 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10606 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10607 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10608 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10609 return Builder.CreateCall( 10610 Intrinsic::getDeclaration( 10611 Builder.GetInsertBlock()->getParent()->getParent(), 10612 Intrinsic::ppc_cfence, {Inst->getType()}), 10613 {Inst}); 10614 // FIXME: Can use isync for rmw operation. 10615 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10616 } 10617 return nullptr; 10618 } 10619 10620 MachineBasicBlock * 10621 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10622 unsigned AtomicSize, 10623 unsigned BinOpcode, 10624 unsigned CmpOpcode, 10625 unsigned CmpPred) const { 10626 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10627 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10628 10629 auto LoadMnemonic = PPC::LDARX; 10630 auto StoreMnemonic = PPC::STDCX; 10631 switch (AtomicSize) { 10632 default: 10633 llvm_unreachable("Unexpected size of atomic entity"); 10634 case 1: 10635 LoadMnemonic = PPC::LBARX; 10636 StoreMnemonic = PPC::STBCX; 10637 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10638 break; 10639 case 2: 10640 LoadMnemonic = PPC::LHARX; 10641 StoreMnemonic = PPC::STHCX; 10642 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10643 break; 10644 case 4: 10645 LoadMnemonic = PPC::LWARX; 10646 StoreMnemonic = PPC::STWCX; 10647 break; 10648 case 8: 10649 LoadMnemonic = PPC::LDARX; 10650 StoreMnemonic = PPC::STDCX; 10651 break; 10652 } 10653 10654 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10655 MachineFunction *F = BB->getParent(); 10656 MachineFunction::iterator It = ++BB->getIterator(); 10657 10658 Register dest = MI.getOperand(0).getReg(); 10659 Register ptrA = MI.getOperand(1).getReg(); 10660 Register ptrB = MI.getOperand(2).getReg(); 10661 Register incr = MI.getOperand(3).getReg(); 10662 DebugLoc dl = MI.getDebugLoc(); 10663 10664 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10665 MachineBasicBlock *loop2MBB = 10666 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10667 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10668 F->insert(It, loopMBB); 10669 if (CmpOpcode) 10670 F->insert(It, loop2MBB); 10671 F->insert(It, exitMBB); 10672 exitMBB->splice(exitMBB->begin(), BB, 10673 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10674 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10675 10676 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10677 Register TmpReg = (!BinOpcode) ? incr : 10678 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10679 : &PPC::GPRCRegClass); 10680 10681 // thisMBB: 10682 // ... 10683 // fallthrough --> loopMBB 10684 BB->addSuccessor(loopMBB); 10685 10686 // loopMBB: 10687 // l[wd]arx dest, ptr 10688 // add r0, dest, incr 10689 // st[wd]cx. r0, ptr 10690 // bne- loopMBB 10691 // fallthrough --> exitMBB 10692 10693 // For max/min... 10694 // loopMBB: 10695 // l[wd]arx dest, ptr 10696 // cmpl?[wd] incr, dest 10697 // bgt exitMBB 10698 // loop2MBB: 10699 // st[wd]cx. dest, ptr 10700 // bne- loopMBB 10701 // fallthrough --> exitMBB 10702 10703 BB = loopMBB; 10704 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10705 .addReg(ptrA).addReg(ptrB); 10706 if (BinOpcode) 10707 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10708 if (CmpOpcode) { 10709 // Signed comparisons of byte or halfword values must be sign-extended. 10710 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10711 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10712 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10713 ExtReg).addReg(dest); 10714 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10715 .addReg(incr).addReg(ExtReg); 10716 } else 10717 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10718 .addReg(incr).addReg(dest); 10719 10720 BuildMI(BB, dl, TII->get(PPC::BCC)) 10721 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10722 BB->addSuccessor(loop2MBB); 10723 BB->addSuccessor(exitMBB); 10724 BB = loop2MBB; 10725 } 10726 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10727 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10728 BuildMI(BB, dl, TII->get(PPC::BCC)) 10729 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10730 BB->addSuccessor(loopMBB); 10731 BB->addSuccessor(exitMBB); 10732 10733 // exitMBB: 10734 // ... 10735 BB = exitMBB; 10736 return BB; 10737 } 10738 10739 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10740 MachineInstr &MI, MachineBasicBlock *BB, 10741 bool is8bit, // operation 10742 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10743 // If we support part-word atomic mnemonics, just use them 10744 if (Subtarget.hasPartwordAtomics()) 10745 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10746 CmpPred); 10747 10748 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10749 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10750 // In 64 bit mode we have to use 64 bits for addresses, even though the 10751 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10752 // registers without caring whether they're 32 or 64, but here we're 10753 // doing actual arithmetic on the addresses. 10754 bool is64bit = Subtarget.isPPC64(); 10755 bool isLittleEndian = Subtarget.isLittleEndian(); 10756 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10757 10758 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10759 MachineFunction *F = BB->getParent(); 10760 MachineFunction::iterator It = ++BB->getIterator(); 10761 10762 Register dest = MI.getOperand(0).getReg(); 10763 Register ptrA = MI.getOperand(1).getReg(); 10764 Register ptrB = MI.getOperand(2).getReg(); 10765 Register incr = MI.getOperand(3).getReg(); 10766 DebugLoc dl = MI.getDebugLoc(); 10767 10768 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10769 MachineBasicBlock *loop2MBB = 10770 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10771 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10772 F->insert(It, loopMBB); 10773 if (CmpOpcode) 10774 F->insert(It, loop2MBB); 10775 F->insert(It, exitMBB); 10776 exitMBB->splice(exitMBB->begin(), BB, 10777 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10778 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10779 10780 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10781 const TargetRegisterClass *RC = 10782 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10783 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10784 10785 Register PtrReg = RegInfo.createVirtualRegister(RC); 10786 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10787 Register ShiftReg = 10788 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10789 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10790 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10791 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10792 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10793 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10794 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10795 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10796 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10797 Register Ptr1Reg; 10798 Register TmpReg = 10799 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10800 10801 // thisMBB: 10802 // ... 10803 // fallthrough --> loopMBB 10804 BB->addSuccessor(loopMBB); 10805 10806 // The 4-byte load must be aligned, while a char or short may be 10807 // anywhere in the word. Hence all this nasty bookkeeping code. 10808 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10809 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10810 // xori shift, shift1, 24 [16] 10811 // rlwinm ptr, ptr1, 0, 0, 29 10812 // slw incr2, incr, shift 10813 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10814 // slw mask, mask2, shift 10815 // loopMBB: 10816 // lwarx tmpDest, ptr 10817 // add tmp, tmpDest, incr2 10818 // andc tmp2, tmpDest, mask 10819 // and tmp3, tmp, mask 10820 // or tmp4, tmp3, tmp2 10821 // stwcx. tmp4, ptr 10822 // bne- loopMBB 10823 // fallthrough --> exitMBB 10824 // srw dest, tmpDest, shift 10825 if (ptrA != ZeroReg) { 10826 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10827 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10828 .addReg(ptrA) 10829 .addReg(ptrB); 10830 } else { 10831 Ptr1Reg = ptrB; 10832 } 10833 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10834 // mode. 10835 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10836 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10837 .addImm(3) 10838 .addImm(27) 10839 .addImm(is8bit ? 28 : 27); 10840 if (!isLittleEndian) 10841 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10842 .addReg(Shift1Reg) 10843 .addImm(is8bit ? 24 : 16); 10844 if (is64bit) 10845 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10846 .addReg(Ptr1Reg) 10847 .addImm(0) 10848 .addImm(61); 10849 else 10850 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10851 .addReg(Ptr1Reg) 10852 .addImm(0) 10853 .addImm(0) 10854 .addImm(29); 10855 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10856 if (is8bit) 10857 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10858 else { 10859 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10860 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10861 .addReg(Mask3Reg) 10862 .addImm(65535); 10863 } 10864 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10865 .addReg(Mask2Reg) 10866 .addReg(ShiftReg); 10867 10868 BB = loopMBB; 10869 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10870 .addReg(ZeroReg) 10871 .addReg(PtrReg); 10872 if (BinOpcode) 10873 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10874 .addReg(Incr2Reg) 10875 .addReg(TmpDestReg); 10876 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10877 .addReg(TmpDestReg) 10878 .addReg(MaskReg); 10879 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10880 if (CmpOpcode) { 10881 // For unsigned comparisons, we can directly compare the shifted values. 10882 // For signed comparisons we shift and sign extend. 10883 Register SReg = RegInfo.createVirtualRegister(GPRC); 10884 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10885 .addReg(TmpDestReg) 10886 .addReg(MaskReg); 10887 unsigned ValueReg = SReg; 10888 unsigned CmpReg = Incr2Reg; 10889 if (CmpOpcode == PPC::CMPW) { 10890 ValueReg = RegInfo.createVirtualRegister(GPRC); 10891 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10892 .addReg(SReg) 10893 .addReg(ShiftReg); 10894 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10895 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10896 .addReg(ValueReg); 10897 ValueReg = ValueSReg; 10898 CmpReg = incr; 10899 } 10900 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10901 .addReg(CmpReg) 10902 .addReg(ValueReg); 10903 BuildMI(BB, dl, TII->get(PPC::BCC)) 10904 .addImm(CmpPred) 10905 .addReg(PPC::CR0) 10906 .addMBB(exitMBB); 10907 BB->addSuccessor(loop2MBB); 10908 BB->addSuccessor(exitMBB); 10909 BB = loop2MBB; 10910 } 10911 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10912 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10913 .addReg(Tmp4Reg) 10914 .addReg(ZeroReg) 10915 .addReg(PtrReg); 10916 BuildMI(BB, dl, TII->get(PPC::BCC)) 10917 .addImm(PPC::PRED_NE) 10918 .addReg(PPC::CR0) 10919 .addMBB(loopMBB); 10920 BB->addSuccessor(loopMBB); 10921 BB->addSuccessor(exitMBB); 10922 10923 // exitMBB: 10924 // ... 10925 BB = exitMBB; 10926 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10927 .addReg(TmpDestReg) 10928 .addReg(ShiftReg); 10929 return BB; 10930 } 10931 10932 llvm::MachineBasicBlock * 10933 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10934 MachineBasicBlock *MBB) const { 10935 DebugLoc DL = MI.getDebugLoc(); 10936 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10937 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10938 10939 MachineFunction *MF = MBB->getParent(); 10940 MachineRegisterInfo &MRI = MF->getRegInfo(); 10941 10942 const BasicBlock *BB = MBB->getBasicBlock(); 10943 MachineFunction::iterator I = ++MBB->getIterator(); 10944 10945 Register DstReg = MI.getOperand(0).getReg(); 10946 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10947 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10948 Register mainDstReg = MRI.createVirtualRegister(RC); 10949 Register restoreDstReg = MRI.createVirtualRegister(RC); 10950 10951 MVT PVT = getPointerTy(MF->getDataLayout()); 10952 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10953 "Invalid Pointer Size!"); 10954 // For v = setjmp(buf), we generate 10955 // 10956 // thisMBB: 10957 // SjLjSetup mainMBB 10958 // bl mainMBB 10959 // v_restore = 1 10960 // b sinkMBB 10961 // 10962 // mainMBB: 10963 // buf[LabelOffset] = LR 10964 // v_main = 0 10965 // 10966 // sinkMBB: 10967 // v = phi(main, restore) 10968 // 10969 10970 MachineBasicBlock *thisMBB = MBB; 10971 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10972 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10973 MF->insert(I, mainMBB); 10974 MF->insert(I, sinkMBB); 10975 10976 MachineInstrBuilder MIB; 10977 10978 // Transfer the remainder of BB and its successor edges to sinkMBB. 10979 sinkMBB->splice(sinkMBB->begin(), MBB, 10980 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10981 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10982 10983 // Note that the structure of the jmp_buf used here is not compatible 10984 // with that used by libc, and is not designed to be. Specifically, it 10985 // stores only those 'reserved' registers that LLVM does not otherwise 10986 // understand how to spill. Also, by convention, by the time this 10987 // intrinsic is called, Clang has already stored the frame address in the 10988 // first slot of the buffer and stack address in the third. Following the 10989 // X86 target code, we'll store the jump address in the second slot. We also 10990 // need to save the TOC pointer (R2) to handle jumps between shared 10991 // libraries, and that will be stored in the fourth slot. The thread 10992 // identifier (R13) is not affected. 10993 10994 // thisMBB: 10995 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10996 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10997 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10998 10999 // Prepare IP either in reg. 11000 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11001 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11002 Register BufReg = MI.getOperand(1).getReg(); 11003 11004 if (Subtarget.is64BitELFABI()) { 11005 setUsesTOCBasePtr(*MBB->getParent()); 11006 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11007 .addReg(PPC::X2) 11008 .addImm(TOCOffset) 11009 .addReg(BufReg) 11010 .cloneMemRefs(MI); 11011 } 11012 11013 // Naked functions never have a base pointer, and so we use r1. For all 11014 // other functions, this decision must be delayed until during PEI. 11015 unsigned BaseReg; 11016 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11017 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11018 else 11019 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11020 11021 MIB = BuildMI(*thisMBB, MI, DL, 11022 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11023 .addReg(BaseReg) 11024 .addImm(BPOffset) 11025 .addReg(BufReg) 11026 .cloneMemRefs(MI); 11027 11028 // Setup 11029 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11030 MIB.addRegMask(TRI->getNoPreservedMask()); 11031 11032 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11033 11034 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11035 .addMBB(mainMBB); 11036 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11037 11038 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11039 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11040 11041 // mainMBB: 11042 // mainDstReg = 0 11043 MIB = 11044 BuildMI(mainMBB, DL, 11045 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11046 11047 // Store IP 11048 if (Subtarget.isPPC64()) { 11049 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11050 .addReg(LabelReg) 11051 .addImm(LabelOffset) 11052 .addReg(BufReg); 11053 } else { 11054 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11055 .addReg(LabelReg) 11056 .addImm(LabelOffset) 11057 .addReg(BufReg); 11058 } 11059 MIB.cloneMemRefs(MI); 11060 11061 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11062 mainMBB->addSuccessor(sinkMBB); 11063 11064 // sinkMBB: 11065 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11066 TII->get(PPC::PHI), DstReg) 11067 .addReg(mainDstReg).addMBB(mainMBB) 11068 .addReg(restoreDstReg).addMBB(thisMBB); 11069 11070 MI.eraseFromParent(); 11071 return sinkMBB; 11072 } 11073 11074 MachineBasicBlock * 11075 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11076 MachineBasicBlock *MBB) const { 11077 DebugLoc DL = MI.getDebugLoc(); 11078 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11079 11080 MachineFunction *MF = MBB->getParent(); 11081 MachineRegisterInfo &MRI = MF->getRegInfo(); 11082 11083 MVT PVT = getPointerTy(MF->getDataLayout()); 11084 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11085 "Invalid Pointer Size!"); 11086 11087 const TargetRegisterClass *RC = 11088 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11089 Register Tmp = MRI.createVirtualRegister(RC); 11090 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11091 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11092 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11093 unsigned BP = 11094 (PVT == MVT::i64) 11095 ? PPC::X30 11096 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11097 : PPC::R30); 11098 11099 MachineInstrBuilder MIB; 11100 11101 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11102 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11103 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11104 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11105 11106 Register BufReg = MI.getOperand(0).getReg(); 11107 11108 // Reload FP (the jumped-to function may not have had a 11109 // frame pointer, and if so, then its r31 will be restored 11110 // as necessary). 11111 if (PVT == MVT::i64) { 11112 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11113 .addImm(0) 11114 .addReg(BufReg); 11115 } else { 11116 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11117 .addImm(0) 11118 .addReg(BufReg); 11119 } 11120 MIB.cloneMemRefs(MI); 11121 11122 // Reload IP 11123 if (PVT == MVT::i64) { 11124 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11125 .addImm(LabelOffset) 11126 .addReg(BufReg); 11127 } else { 11128 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11129 .addImm(LabelOffset) 11130 .addReg(BufReg); 11131 } 11132 MIB.cloneMemRefs(MI); 11133 11134 // Reload SP 11135 if (PVT == MVT::i64) { 11136 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11137 .addImm(SPOffset) 11138 .addReg(BufReg); 11139 } else { 11140 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11141 .addImm(SPOffset) 11142 .addReg(BufReg); 11143 } 11144 MIB.cloneMemRefs(MI); 11145 11146 // Reload BP 11147 if (PVT == MVT::i64) { 11148 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11149 .addImm(BPOffset) 11150 .addReg(BufReg); 11151 } else { 11152 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11153 .addImm(BPOffset) 11154 .addReg(BufReg); 11155 } 11156 MIB.cloneMemRefs(MI); 11157 11158 // Reload TOC 11159 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11160 setUsesTOCBasePtr(*MBB->getParent()); 11161 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11162 .addImm(TOCOffset) 11163 .addReg(BufReg) 11164 .cloneMemRefs(MI); 11165 } 11166 11167 // Jump 11168 BuildMI(*MBB, MI, DL, 11169 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11170 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11171 11172 MI.eraseFromParent(); 11173 return MBB; 11174 } 11175 11176 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11177 // If the function specifically requests inline stack probes, emit them. 11178 if (MF.getFunction().hasFnAttribute("probe-stack")) 11179 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11180 "inline-asm"; 11181 return false; 11182 } 11183 11184 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11185 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11186 unsigned StackAlign = TFI->getStackAlignment(); 11187 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11188 "Unexpected stack alignment"); 11189 // The default stack probe size is 4096 if the function has no 11190 // stack-probe-size attribute. 11191 unsigned StackProbeSize = 4096; 11192 const Function &Fn = MF.getFunction(); 11193 if (Fn.hasFnAttribute("stack-probe-size")) 11194 Fn.getFnAttribute("stack-probe-size") 11195 .getValueAsString() 11196 .getAsInteger(0, StackProbeSize); 11197 // Round down to the stack alignment. 11198 StackProbeSize &= ~(StackAlign - 1); 11199 return StackProbeSize ? StackProbeSize : StackAlign; 11200 } 11201 11202 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11203 // into three phases. In the first phase, it uses pseudo instruction 11204 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11205 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11206 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11207 // MaxCallFrameSize so that it can calculate correct data area pointer. 11208 MachineBasicBlock * 11209 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11210 MachineBasicBlock *MBB) const { 11211 const bool isPPC64 = Subtarget.isPPC64(); 11212 MachineFunction *MF = MBB->getParent(); 11213 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11214 DebugLoc DL = MI.getDebugLoc(); 11215 const unsigned ProbeSize = getStackProbeSize(*MF); 11216 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11217 MachineRegisterInfo &MRI = MF->getRegInfo(); 11218 // The CFG of probing stack looks as 11219 // +-----+ 11220 // | MBB | 11221 // +--+--+ 11222 // | 11223 // +----v----+ 11224 // +--->+ TestMBB +---+ 11225 // | +----+----+ | 11226 // | | | 11227 // | +-----v----+ | 11228 // +---+ BlockMBB | | 11229 // +----------+ | 11230 // | 11231 // +---------+ | 11232 // | TailMBB +<--+ 11233 // +---------+ 11234 // In MBB, calculate previous frame pointer and final stack pointer. 11235 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11236 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11237 // TailMBB is spliced via \p MI. 11238 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11239 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11240 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11241 11242 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11243 MF->insert(MBBIter, TestMBB); 11244 MF->insert(MBBIter, BlockMBB); 11245 MF->insert(MBBIter, TailMBB); 11246 11247 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11248 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11249 11250 Register DstReg = MI.getOperand(0).getReg(); 11251 Register NegSizeReg = MI.getOperand(1).getReg(); 11252 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11253 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11254 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11255 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11256 11257 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11258 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11259 // NegSize. 11260 unsigned ProbeOpc; 11261 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11262 ProbeOpc = 11263 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11264 else 11265 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11266 // and NegSizeReg will be allocated in the same phyreg to avoid 11267 // redundant copy when NegSizeReg has only one use which is current MI and 11268 // will be replaced by PREPARE_PROBED_ALLOCA then. 11269 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11270 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11271 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11272 .addDef(ActualNegSizeReg) 11273 .addReg(NegSizeReg) 11274 .add(MI.getOperand(2)) 11275 .add(MI.getOperand(3)); 11276 11277 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11278 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11279 FinalStackPtr) 11280 .addReg(SPReg) 11281 .addReg(ActualNegSizeReg); 11282 11283 // Materialize a scratch register for update. 11284 int64_t NegProbeSize = -(int64_t)ProbeSize; 11285 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11286 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11287 if (!isInt<16>(NegProbeSize)) { 11288 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11289 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11290 .addImm(NegProbeSize >> 16); 11291 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11292 ScratchReg) 11293 .addReg(TempReg) 11294 .addImm(NegProbeSize & 0xFFFF); 11295 } else 11296 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11297 .addImm(NegProbeSize); 11298 11299 { 11300 // Probing leading residual part. 11301 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11302 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11303 .addReg(ActualNegSizeReg) 11304 .addReg(ScratchReg); 11305 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11306 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11307 .addReg(Div) 11308 .addReg(ScratchReg); 11309 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11310 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11311 .addReg(Mul) 11312 .addReg(ActualNegSizeReg); 11313 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11314 .addReg(FramePointer) 11315 .addReg(SPReg) 11316 .addReg(NegMod); 11317 } 11318 11319 { 11320 // Remaining part should be multiple of ProbeSize. 11321 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11322 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11323 .addReg(SPReg) 11324 .addReg(FinalStackPtr); 11325 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11326 .addImm(PPC::PRED_EQ) 11327 .addReg(CmpResult) 11328 .addMBB(TailMBB); 11329 TestMBB->addSuccessor(BlockMBB); 11330 TestMBB->addSuccessor(TailMBB); 11331 } 11332 11333 { 11334 // Touch the block. 11335 // |P...|P...|P... 11336 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11337 .addReg(FramePointer) 11338 .addReg(SPReg) 11339 .addReg(ScratchReg); 11340 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11341 BlockMBB->addSuccessor(TestMBB); 11342 } 11343 11344 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11345 // DYNAREAOFFSET pseudo instruction to get the future result. 11346 Register MaxCallFrameSizeReg = 11347 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11348 BuildMI(TailMBB, DL, 11349 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11350 MaxCallFrameSizeReg) 11351 .add(MI.getOperand(2)) 11352 .add(MI.getOperand(3)); 11353 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11354 .addReg(SPReg) 11355 .addReg(MaxCallFrameSizeReg); 11356 11357 // Splice instructions after MI to TailMBB. 11358 TailMBB->splice(TailMBB->end(), MBB, 11359 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11360 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11361 MBB->addSuccessor(TestMBB); 11362 11363 // Delete the pseudo instruction. 11364 MI.eraseFromParent(); 11365 11366 ++NumDynamicAllocaProbed; 11367 return TailMBB; 11368 } 11369 11370 MachineBasicBlock * 11371 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11372 MachineBasicBlock *BB) const { 11373 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11374 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11375 if (Subtarget.is64BitELFABI() && 11376 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11377 !Subtarget.isUsingPCRelativeCalls()) { 11378 // Call lowering should have added an r2 operand to indicate a dependence 11379 // on the TOC base pointer value. It can't however, because there is no 11380 // way to mark the dependence as implicit there, and so the stackmap code 11381 // will confuse it with a regular operand. Instead, add the dependence 11382 // here. 11383 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11384 } 11385 11386 return emitPatchPoint(MI, BB); 11387 } 11388 11389 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11390 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11391 return emitEHSjLjSetJmp(MI, BB); 11392 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11393 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11394 return emitEHSjLjLongJmp(MI, BB); 11395 } 11396 11397 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11398 11399 // To "insert" these instructions we actually have to insert their 11400 // control-flow patterns. 11401 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11402 MachineFunction::iterator It = ++BB->getIterator(); 11403 11404 MachineFunction *F = BB->getParent(); 11405 11406 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11407 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11408 MI.getOpcode() == PPC::SELECT_I8) { 11409 SmallVector<MachineOperand, 2> Cond; 11410 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11411 MI.getOpcode() == PPC::SELECT_CC_I8) 11412 Cond.push_back(MI.getOperand(4)); 11413 else 11414 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11415 Cond.push_back(MI.getOperand(1)); 11416 11417 DebugLoc dl = MI.getDebugLoc(); 11418 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11419 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11420 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11421 MI.getOpcode() == PPC::SELECT_CC_F8 || 11422 MI.getOpcode() == PPC::SELECT_CC_F16 || 11423 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11424 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11425 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11426 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11427 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11428 MI.getOpcode() == PPC::SELECT_CC_SPE || 11429 MI.getOpcode() == PPC::SELECT_F4 || 11430 MI.getOpcode() == PPC::SELECT_F8 || 11431 MI.getOpcode() == PPC::SELECT_F16 || 11432 MI.getOpcode() == PPC::SELECT_SPE || 11433 MI.getOpcode() == PPC::SELECT_SPE4 || 11434 MI.getOpcode() == PPC::SELECT_VRRC || 11435 MI.getOpcode() == PPC::SELECT_VSFRC || 11436 MI.getOpcode() == PPC::SELECT_VSSRC || 11437 MI.getOpcode() == PPC::SELECT_VSRC) { 11438 // The incoming instruction knows the destination vreg to set, the 11439 // condition code register to branch on, the true/false values to 11440 // select between, and a branch opcode to use. 11441 11442 // thisMBB: 11443 // ... 11444 // TrueVal = ... 11445 // cmpTY ccX, r1, r2 11446 // bCC copy1MBB 11447 // fallthrough --> copy0MBB 11448 MachineBasicBlock *thisMBB = BB; 11449 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11450 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11451 DebugLoc dl = MI.getDebugLoc(); 11452 F->insert(It, copy0MBB); 11453 F->insert(It, sinkMBB); 11454 11455 // Transfer the remainder of BB and its successor edges to sinkMBB. 11456 sinkMBB->splice(sinkMBB->begin(), BB, 11457 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11458 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11459 11460 // Next, add the true and fallthrough blocks as its successors. 11461 BB->addSuccessor(copy0MBB); 11462 BB->addSuccessor(sinkMBB); 11463 11464 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11465 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11466 MI.getOpcode() == PPC::SELECT_F16 || 11467 MI.getOpcode() == PPC::SELECT_SPE4 || 11468 MI.getOpcode() == PPC::SELECT_SPE || 11469 MI.getOpcode() == PPC::SELECT_VRRC || 11470 MI.getOpcode() == PPC::SELECT_VSFRC || 11471 MI.getOpcode() == PPC::SELECT_VSSRC || 11472 MI.getOpcode() == PPC::SELECT_VSRC) { 11473 BuildMI(BB, dl, TII->get(PPC::BC)) 11474 .addReg(MI.getOperand(1).getReg()) 11475 .addMBB(sinkMBB); 11476 } else { 11477 unsigned SelectPred = MI.getOperand(4).getImm(); 11478 BuildMI(BB, dl, TII->get(PPC::BCC)) 11479 .addImm(SelectPred) 11480 .addReg(MI.getOperand(1).getReg()) 11481 .addMBB(sinkMBB); 11482 } 11483 11484 // copy0MBB: 11485 // %FalseValue = ... 11486 // # fallthrough to sinkMBB 11487 BB = copy0MBB; 11488 11489 // Update machine-CFG edges 11490 BB->addSuccessor(sinkMBB); 11491 11492 // sinkMBB: 11493 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11494 // ... 11495 BB = sinkMBB; 11496 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11497 .addReg(MI.getOperand(3).getReg()) 11498 .addMBB(copy0MBB) 11499 .addReg(MI.getOperand(2).getReg()) 11500 .addMBB(thisMBB); 11501 } else if (MI.getOpcode() == PPC::ReadTB) { 11502 // To read the 64-bit time-base register on a 32-bit target, we read the 11503 // two halves. Should the counter have wrapped while it was being read, we 11504 // need to try again. 11505 // ... 11506 // readLoop: 11507 // mfspr Rx,TBU # load from TBU 11508 // mfspr Ry,TB # load from TB 11509 // mfspr Rz,TBU # load from TBU 11510 // cmpw crX,Rx,Rz # check if 'old'='new' 11511 // bne readLoop # branch if they're not equal 11512 // ... 11513 11514 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11515 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11516 DebugLoc dl = MI.getDebugLoc(); 11517 F->insert(It, readMBB); 11518 F->insert(It, sinkMBB); 11519 11520 // Transfer the remainder of BB and its successor edges to sinkMBB. 11521 sinkMBB->splice(sinkMBB->begin(), BB, 11522 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11523 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11524 11525 BB->addSuccessor(readMBB); 11526 BB = readMBB; 11527 11528 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11529 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11530 Register LoReg = MI.getOperand(0).getReg(); 11531 Register HiReg = MI.getOperand(1).getReg(); 11532 11533 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11534 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11535 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11536 11537 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11538 11539 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11540 .addReg(HiReg) 11541 .addReg(ReadAgainReg); 11542 BuildMI(BB, dl, TII->get(PPC::BCC)) 11543 .addImm(PPC::PRED_NE) 11544 .addReg(CmpReg) 11545 .addMBB(readMBB); 11546 11547 BB->addSuccessor(readMBB); 11548 BB->addSuccessor(sinkMBB); 11549 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11550 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11552 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11553 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11554 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11556 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11557 11558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11559 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11560 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11561 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11562 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11563 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11564 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11565 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11566 11567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11568 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11569 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11570 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11571 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11572 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11573 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11574 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11575 11576 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11577 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11578 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11579 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11580 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11581 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11582 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11583 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11584 11585 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11586 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11587 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11588 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11589 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11590 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11591 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11592 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11593 11594 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11595 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11596 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11597 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11598 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11599 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11600 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11601 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11602 11603 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11604 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11605 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11606 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11607 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11608 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11609 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11610 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11611 11612 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11613 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11614 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11615 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11616 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11617 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11618 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11619 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11620 11621 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11622 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11624 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11625 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11626 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11627 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11628 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11629 11630 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11631 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11632 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11633 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11634 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11635 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11636 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11637 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11638 11639 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11640 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11641 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11642 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11643 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11644 BB = EmitAtomicBinary(MI, BB, 4, 0); 11645 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11646 BB = EmitAtomicBinary(MI, BB, 8, 0); 11647 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11648 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11649 (Subtarget.hasPartwordAtomics() && 11650 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11651 (Subtarget.hasPartwordAtomics() && 11652 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11653 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11654 11655 auto LoadMnemonic = PPC::LDARX; 11656 auto StoreMnemonic = PPC::STDCX; 11657 switch (MI.getOpcode()) { 11658 default: 11659 llvm_unreachable("Compare and swap of unknown size"); 11660 case PPC::ATOMIC_CMP_SWAP_I8: 11661 LoadMnemonic = PPC::LBARX; 11662 StoreMnemonic = PPC::STBCX; 11663 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11664 break; 11665 case PPC::ATOMIC_CMP_SWAP_I16: 11666 LoadMnemonic = PPC::LHARX; 11667 StoreMnemonic = PPC::STHCX; 11668 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11669 break; 11670 case PPC::ATOMIC_CMP_SWAP_I32: 11671 LoadMnemonic = PPC::LWARX; 11672 StoreMnemonic = PPC::STWCX; 11673 break; 11674 case PPC::ATOMIC_CMP_SWAP_I64: 11675 LoadMnemonic = PPC::LDARX; 11676 StoreMnemonic = PPC::STDCX; 11677 break; 11678 } 11679 Register dest = MI.getOperand(0).getReg(); 11680 Register ptrA = MI.getOperand(1).getReg(); 11681 Register ptrB = MI.getOperand(2).getReg(); 11682 Register oldval = MI.getOperand(3).getReg(); 11683 Register newval = MI.getOperand(4).getReg(); 11684 DebugLoc dl = MI.getDebugLoc(); 11685 11686 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11687 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11688 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11689 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11690 F->insert(It, loop1MBB); 11691 F->insert(It, loop2MBB); 11692 F->insert(It, midMBB); 11693 F->insert(It, exitMBB); 11694 exitMBB->splice(exitMBB->begin(), BB, 11695 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11696 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11697 11698 // thisMBB: 11699 // ... 11700 // fallthrough --> loopMBB 11701 BB->addSuccessor(loop1MBB); 11702 11703 // loop1MBB: 11704 // l[bhwd]arx dest, ptr 11705 // cmp[wd] dest, oldval 11706 // bne- midMBB 11707 // loop2MBB: 11708 // st[bhwd]cx. newval, ptr 11709 // bne- loopMBB 11710 // b exitBB 11711 // midMBB: 11712 // st[bhwd]cx. dest, ptr 11713 // exitBB: 11714 BB = loop1MBB; 11715 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11716 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11717 .addReg(oldval) 11718 .addReg(dest); 11719 BuildMI(BB, dl, TII->get(PPC::BCC)) 11720 .addImm(PPC::PRED_NE) 11721 .addReg(PPC::CR0) 11722 .addMBB(midMBB); 11723 BB->addSuccessor(loop2MBB); 11724 BB->addSuccessor(midMBB); 11725 11726 BB = loop2MBB; 11727 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11728 .addReg(newval) 11729 .addReg(ptrA) 11730 .addReg(ptrB); 11731 BuildMI(BB, dl, TII->get(PPC::BCC)) 11732 .addImm(PPC::PRED_NE) 11733 .addReg(PPC::CR0) 11734 .addMBB(loop1MBB); 11735 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11736 BB->addSuccessor(loop1MBB); 11737 BB->addSuccessor(exitMBB); 11738 11739 BB = midMBB; 11740 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11741 .addReg(dest) 11742 .addReg(ptrA) 11743 .addReg(ptrB); 11744 BB->addSuccessor(exitMBB); 11745 11746 // exitMBB: 11747 // ... 11748 BB = exitMBB; 11749 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11750 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11751 // We must use 64-bit registers for addresses when targeting 64-bit, 11752 // since we're actually doing arithmetic on them. Other registers 11753 // can be 32-bit. 11754 bool is64bit = Subtarget.isPPC64(); 11755 bool isLittleEndian = Subtarget.isLittleEndian(); 11756 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11757 11758 Register dest = MI.getOperand(0).getReg(); 11759 Register ptrA = MI.getOperand(1).getReg(); 11760 Register ptrB = MI.getOperand(2).getReg(); 11761 Register oldval = MI.getOperand(3).getReg(); 11762 Register newval = MI.getOperand(4).getReg(); 11763 DebugLoc dl = MI.getDebugLoc(); 11764 11765 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11766 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11767 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11768 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11769 F->insert(It, loop1MBB); 11770 F->insert(It, loop2MBB); 11771 F->insert(It, midMBB); 11772 F->insert(It, exitMBB); 11773 exitMBB->splice(exitMBB->begin(), BB, 11774 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11775 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11776 11777 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11778 const TargetRegisterClass *RC = 11779 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11780 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11781 11782 Register PtrReg = RegInfo.createVirtualRegister(RC); 11783 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11784 Register ShiftReg = 11785 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11786 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11787 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11788 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11789 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11790 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11791 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11792 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11793 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11794 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11795 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11796 Register Ptr1Reg; 11797 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11798 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11799 // thisMBB: 11800 // ... 11801 // fallthrough --> loopMBB 11802 BB->addSuccessor(loop1MBB); 11803 11804 // The 4-byte load must be aligned, while a char or short may be 11805 // anywhere in the word. Hence all this nasty bookkeeping code. 11806 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11807 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11808 // xori shift, shift1, 24 [16] 11809 // rlwinm ptr, ptr1, 0, 0, 29 11810 // slw newval2, newval, shift 11811 // slw oldval2, oldval,shift 11812 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11813 // slw mask, mask2, shift 11814 // and newval3, newval2, mask 11815 // and oldval3, oldval2, mask 11816 // loop1MBB: 11817 // lwarx tmpDest, ptr 11818 // and tmp, tmpDest, mask 11819 // cmpw tmp, oldval3 11820 // bne- midMBB 11821 // loop2MBB: 11822 // andc tmp2, tmpDest, mask 11823 // or tmp4, tmp2, newval3 11824 // stwcx. tmp4, ptr 11825 // bne- loop1MBB 11826 // b exitBB 11827 // midMBB: 11828 // stwcx. tmpDest, ptr 11829 // exitBB: 11830 // srw dest, tmpDest, shift 11831 if (ptrA != ZeroReg) { 11832 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11833 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11834 .addReg(ptrA) 11835 .addReg(ptrB); 11836 } else { 11837 Ptr1Reg = ptrB; 11838 } 11839 11840 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11841 // mode. 11842 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11843 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11844 .addImm(3) 11845 .addImm(27) 11846 .addImm(is8bit ? 28 : 27); 11847 if (!isLittleEndian) 11848 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11849 .addReg(Shift1Reg) 11850 .addImm(is8bit ? 24 : 16); 11851 if (is64bit) 11852 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11853 .addReg(Ptr1Reg) 11854 .addImm(0) 11855 .addImm(61); 11856 else 11857 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11858 .addReg(Ptr1Reg) 11859 .addImm(0) 11860 .addImm(0) 11861 .addImm(29); 11862 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11863 .addReg(newval) 11864 .addReg(ShiftReg); 11865 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11866 .addReg(oldval) 11867 .addReg(ShiftReg); 11868 if (is8bit) 11869 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11870 else { 11871 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11872 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11873 .addReg(Mask3Reg) 11874 .addImm(65535); 11875 } 11876 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11877 .addReg(Mask2Reg) 11878 .addReg(ShiftReg); 11879 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11880 .addReg(NewVal2Reg) 11881 .addReg(MaskReg); 11882 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11883 .addReg(OldVal2Reg) 11884 .addReg(MaskReg); 11885 11886 BB = loop1MBB; 11887 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11888 .addReg(ZeroReg) 11889 .addReg(PtrReg); 11890 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11891 .addReg(TmpDestReg) 11892 .addReg(MaskReg); 11893 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11894 .addReg(TmpReg) 11895 .addReg(OldVal3Reg); 11896 BuildMI(BB, dl, TII->get(PPC::BCC)) 11897 .addImm(PPC::PRED_NE) 11898 .addReg(PPC::CR0) 11899 .addMBB(midMBB); 11900 BB->addSuccessor(loop2MBB); 11901 BB->addSuccessor(midMBB); 11902 11903 BB = loop2MBB; 11904 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11905 .addReg(TmpDestReg) 11906 .addReg(MaskReg); 11907 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11908 .addReg(Tmp2Reg) 11909 .addReg(NewVal3Reg); 11910 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11911 .addReg(Tmp4Reg) 11912 .addReg(ZeroReg) 11913 .addReg(PtrReg); 11914 BuildMI(BB, dl, TII->get(PPC::BCC)) 11915 .addImm(PPC::PRED_NE) 11916 .addReg(PPC::CR0) 11917 .addMBB(loop1MBB); 11918 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11919 BB->addSuccessor(loop1MBB); 11920 BB->addSuccessor(exitMBB); 11921 11922 BB = midMBB; 11923 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11924 .addReg(TmpDestReg) 11925 .addReg(ZeroReg) 11926 .addReg(PtrReg); 11927 BB->addSuccessor(exitMBB); 11928 11929 // exitMBB: 11930 // ... 11931 BB = exitMBB; 11932 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11933 .addReg(TmpReg) 11934 .addReg(ShiftReg); 11935 } else if (MI.getOpcode() == PPC::FADDrtz) { 11936 // This pseudo performs an FADD with rounding mode temporarily forced 11937 // to round-to-zero. We emit this via custom inserter since the FPSCR 11938 // is not modeled at the SelectionDAG level. 11939 Register Dest = MI.getOperand(0).getReg(); 11940 Register Src1 = MI.getOperand(1).getReg(); 11941 Register Src2 = MI.getOperand(2).getReg(); 11942 DebugLoc dl = MI.getDebugLoc(); 11943 11944 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11945 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11946 11947 // Save FPSCR value. 11948 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11949 11950 // Set rounding mode to round-to-zero. 11951 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 11952 .addImm(31) 11953 .addReg(PPC::RM, RegState::ImplicitDefine); 11954 11955 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 11956 .addImm(30) 11957 .addReg(PPC::RM, RegState::ImplicitDefine); 11958 11959 // Perform addition. 11960 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11961 11962 // Restore FPSCR value. 11963 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11964 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11965 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 11966 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11967 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 11968 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11969 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 11970 ? PPC::ANDI8_rec 11971 : PPC::ANDI_rec; 11972 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11973 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 11974 11975 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11976 Register Dest = RegInfo.createVirtualRegister( 11977 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11978 11979 DebugLoc Dl = MI.getDebugLoc(); 11980 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 11981 .addReg(MI.getOperand(1).getReg()) 11982 .addImm(1); 11983 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11984 MI.getOperand(0).getReg()) 11985 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 11986 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11987 DebugLoc Dl = MI.getDebugLoc(); 11988 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11989 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11990 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11991 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11992 MI.getOperand(0).getReg()) 11993 .addReg(CRReg); 11994 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11995 DebugLoc Dl = MI.getDebugLoc(); 11996 unsigned Imm = MI.getOperand(1).getImm(); 11997 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11998 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11999 MI.getOperand(0).getReg()) 12000 .addReg(PPC::CR0EQ); 12001 } else if (MI.getOpcode() == PPC::SETRNDi) { 12002 DebugLoc dl = MI.getDebugLoc(); 12003 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12004 12005 // Save FPSCR value. 12006 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12007 12008 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12009 // the following settings: 12010 // 00 Round to nearest 12011 // 01 Round to 0 12012 // 10 Round to +inf 12013 // 11 Round to -inf 12014 12015 // When the operand is immediate, using the two least significant bits of 12016 // the immediate to set the bits 62:63 of FPSCR. 12017 unsigned Mode = MI.getOperand(1).getImm(); 12018 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12019 .addImm(31) 12020 .addReg(PPC::RM, RegState::ImplicitDefine); 12021 12022 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12023 .addImm(30) 12024 .addReg(PPC::RM, RegState::ImplicitDefine); 12025 } else if (MI.getOpcode() == PPC::SETRND) { 12026 DebugLoc dl = MI.getDebugLoc(); 12027 12028 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12029 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12030 // If the target doesn't have DirectMove, we should use stack to do the 12031 // conversion, because the target doesn't have the instructions like mtvsrd 12032 // or mfvsrd to do this conversion directly. 12033 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12034 if (Subtarget.hasDirectMove()) { 12035 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12036 .addReg(SrcReg); 12037 } else { 12038 // Use stack to do the register copy. 12039 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12040 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12041 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12042 if (RC == &PPC::F8RCRegClass) { 12043 // Copy register from F8RCRegClass to G8RCRegclass. 12044 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12045 "Unsupported RegClass."); 12046 12047 StoreOp = PPC::STFD; 12048 LoadOp = PPC::LD; 12049 } else { 12050 // Copy register from G8RCRegClass to F8RCRegclass. 12051 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12052 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12053 "Unsupported RegClass."); 12054 } 12055 12056 MachineFrameInfo &MFI = F->getFrameInfo(); 12057 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12058 12059 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12060 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12061 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12062 MFI.getObjectAlign(FrameIdx)); 12063 12064 // Store the SrcReg into the stack. 12065 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12066 .addReg(SrcReg) 12067 .addImm(0) 12068 .addFrameIndex(FrameIdx) 12069 .addMemOperand(MMOStore); 12070 12071 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12072 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12073 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12074 MFI.getObjectAlign(FrameIdx)); 12075 12076 // Load from the stack where SrcReg is stored, and save to DestReg, 12077 // so we have done the RegClass conversion from RegClass::SrcReg to 12078 // RegClass::DestReg. 12079 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12080 .addImm(0) 12081 .addFrameIndex(FrameIdx) 12082 .addMemOperand(MMOLoad); 12083 } 12084 }; 12085 12086 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12087 12088 // Save FPSCR value. 12089 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12090 12091 // When the operand is gprc register, use two least significant bits of the 12092 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12093 // 12094 // copy OldFPSCRTmpReg, OldFPSCRReg 12095 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12096 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12097 // copy NewFPSCRReg, NewFPSCRTmpReg 12098 // mtfsf 255, NewFPSCRReg 12099 MachineOperand SrcOp = MI.getOperand(1); 12100 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12101 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12102 12103 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12104 12105 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12106 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12107 12108 // The first operand of INSERT_SUBREG should be a register which has 12109 // subregisters, we only care about its RegClass, so we should use an 12110 // IMPLICIT_DEF register. 12111 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12112 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12113 .addReg(ImDefReg) 12114 .add(SrcOp) 12115 .addImm(1); 12116 12117 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12118 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12119 .addReg(OldFPSCRTmpReg) 12120 .addReg(ExtSrcReg) 12121 .addImm(0) 12122 .addImm(62); 12123 12124 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12125 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12126 12127 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12128 // bits of FPSCR. 12129 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12130 .addImm(255) 12131 .addReg(NewFPSCRReg) 12132 .addImm(0) 12133 .addImm(0); 12134 } else if (MI.getOpcode() == PPC::SETFLM) { 12135 DebugLoc Dl = MI.getDebugLoc(); 12136 12137 // Result of setflm is previous FPSCR content, so we need to save it first. 12138 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12139 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12140 12141 // Put bits in 32:63 to FPSCR. 12142 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12143 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12144 .addImm(255) 12145 .addReg(NewFPSCRReg) 12146 .addImm(0) 12147 .addImm(0); 12148 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12149 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12150 return emitProbedAlloca(MI, BB); 12151 } else { 12152 llvm_unreachable("Unexpected instr type to insert"); 12153 } 12154 12155 MI.eraseFromParent(); // The pseudo instruction is gone now. 12156 return BB; 12157 } 12158 12159 //===----------------------------------------------------------------------===// 12160 // Target Optimization Hooks 12161 //===----------------------------------------------------------------------===// 12162 12163 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12164 // For the estimates, convergence is quadratic, so we essentially double the 12165 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12166 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12167 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12168 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12169 if (VT.getScalarType() == MVT::f64) 12170 RefinementSteps++; 12171 return RefinementSteps; 12172 } 12173 12174 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12175 int Enabled, int &RefinementSteps, 12176 bool &UseOneConstNR, 12177 bool Reciprocal) const { 12178 EVT VT = Operand.getValueType(); 12179 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12180 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12181 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12182 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12183 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12184 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12185 12186 // The Newton-Raphson computation with a single constant does not provide 12187 // enough accuracy on some CPUs. 12188 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12189 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12190 } 12191 return SDValue(); 12192 } 12193 12194 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12195 int Enabled, 12196 int &RefinementSteps) const { 12197 EVT VT = Operand.getValueType(); 12198 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12199 (VT == MVT::f64 && Subtarget.hasFRE()) || 12200 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12201 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12202 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12203 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12204 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12205 } 12206 return SDValue(); 12207 } 12208 12209 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12210 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12211 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12212 // enabled for division), this functionality is redundant with the default 12213 // combiner logic (once the division -> reciprocal/multiply transformation 12214 // has taken place). As a result, this matters more for older cores than for 12215 // newer ones. 12216 12217 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12218 // reciprocal if there are two or more FDIVs (for embedded cores with only 12219 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12220 switch (Subtarget.getCPUDirective()) { 12221 default: 12222 return 3; 12223 case PPC::DIR_440: 12224 case PPC::DIR_A2: 12225 case PPC::DIR_E500: 12226 case PPC::DIR_E500mc: 12227 case PPC::DIR_E5500: 12228 return 2; 12229 } 12230 } 12231 12232 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12233 // collapsed, and so we need to look through chains of them. 12234 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12235 int64_t& Offset, SelectionDAG &DAG) { 12236 if (DAG.isBaseWithConstantOffset(Loc)) { 12237 Base = Loc.getOperand(0); 12238 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12239 12240 // The base might itself be a base plus an offset, and if so, accumulate 12241 // that as well. 12242 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12243 } 12244 } 12245 12246 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12247 unsigned Bytes, int Dist, 12248 SelectionDAG &DAG) { 12249 if (VT.getSizeInBits() / 8 != Bytes) 12250 return false; 12251 12252 SDValue BaseLoc = Base->getBasePtr(); 12253 if (Loc.getOpcode() == ISD::FrameIndex) { 12254 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12255 return false; 12256 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12257 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12258 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12259 int FS = MFI.getObjectSize(FI); 12260 int BFS = MFI.getObjectSize(BFI); 12261 if (FS != BFS || FS != (int)Bytes) return false; 12262 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12263 } 12264 12265 SDValue Base1 = Loc, Base2 = BaseLoc; 12266 int64_t Offset1 = 0, Offset2 = 0; 12267 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12268 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12269 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12270 return true; 12271 12272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12273 const GlobalValue *GV1 = nullptr; 12274 const GlobalValue *GV2 = nullptr; 12275 Offset1 = 0; 12276 Offset2 = 0; 12277 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12278 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12279 if (isGA1 && isGA2 && GV1 == GV2) 12280 return Offset1 == (Offset2 + Dist*Bytes); 12281 return false; 12282 } 12283 12284 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12285 // not enforce equality of the chain operands. 12286 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12287 unsigned Bytes, int Dist, 12288 SelectionDAG &DAG) { 12289 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12290 EVT VT = LS->getMemoryVT(); 12291 SDValue Loc = LS->getBasePtr(); 12292 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12293 } 12294 12295 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12296 EVT VT; 12297 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12298 default: return false; 12299 case Intrinsic::ppc_altivec_lvx: 12300 case Intrinsic::ppc_altivec_lvxl: 12301 case Intrinsic::ppc_vsx_lxvw4x: 12302 case Intrinsic::ppc_vsx_lxvw4x_be: 12303 VT = MVT::v4i32; 12304 break; 12305 case Intrinsic::ppc_vsx_lxvd2x: 12306 case Intrinsic::ppc_vsx_lxvd2x_be: 12307 VT = MVT::v2f64; 12308 break; 12309 case Intrinsic::ppc_altivec_lvebx: 12310 VT = MVT::i8; 12311 break; 12312 case Intrinsic::ppc_altivec_lvehx: 12313 VT = MVT::i16; 12314 break; 12315 case Intrinsic::ppc_altivec_lvewx: 12316 VT = MVT::i32; 12317 break; 12318 } 12319 12320 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12321 } 12322 12323 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12324 EVT VT; 12325 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12326 default: return false; 12327 case Intrinsic::ppc_altivec_stvx: 12328 case Intrinsic::ppc_altivec_stvxl: 12329 case Intrinsic::ppc_vsx_stxvw4x: 12330 VT = MVT::v4i32; 12331 break; 12332 case Intrinsic::ppc_vsx_stxvd2x: 12333 VT = MVT::v2f64; 12334 break; 12335 case Intrinsic::ppc_vsx_stxvw4x_be: 12336 VT = MVT::v4i32; 12337 break; 12338 case Intrinsic::ppc_vsx_stxvd2x_be: 12339 VT = MVT::v2f64; 12340 break; 12341 case Intrinsic::ppc_altivec_stvebx: 12342 VT = MVT::i8; 12343 break; 12344 case Intrinsic::ppc_altivec_stvehx: 12345 VT = MVT::i16; 12346 break; 12347 case Intrinsic::ppc_altivec_stvewx: 12348 VT = MVT::i32; 12349 break; 12350 } 12351 12352 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12353 } 12354 12355 return false; 12356 } 12357 12358 // Return true is there is a nearyby consecutive load to the one provided 12359 // (regardless of alignment). We search up and down the chain, looking though 12360 // token factors and other loads (but nothing else). As a result, a true result 12361 // indicates that it is safe to create a new consecutive load adjacent to the 12362 // load provided. 12363 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12364 SDValue Chain = LD->getChain(); 12365 EVT VT = LD->getMemoryVT(); 12366 12367 SmallSet<SDNode *, 16> LoadRoots; 12368 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12369 SmallSet<SDNode *, 16> Visited; 12370 12371 // First, search up the chain, branching to follow all token-factor operands. 12372 // If we find a consecutive load, then we're done, otherwise, record all 12373 // nodes just above the top-level loads and token factors. 12374 while (!Queue.empty()) { 12375 SDNode *ChainNext = Queue.pop_back_val(); 12376 if (!Visited.insert(ChainNext).second) 12377 continue; 12378 12379 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12380 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12381 return true; 12382 12383 if (!Visited.count(ChainLD->getChain().getNode())) 12384 Queue.push_back(ChainLD->getChain().getNode()); 12385 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12386 for (const SDUse &O : ChainNext->ops()) 12387 if (!Visited.count(O.getNode())) 12388 Queue.push_back(O.getNode()); 12389 } else 12390 LoadRoots.insert(ChainNext); 12391 } 12392 12393 // Second, search down the chain, starting from the top-level nodes recorded 12394 // in the first phase. These top-level nodes are the nodes just above all 12395 // loads and token factors. Starting with their uses, recursively look though 12396 // all loads (just the chain uses) and token factors to find a consecutive 12397 // load. 12398 Visited.clear(); 12399 Queue.clear(); 12400 12401 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12402 IE = LoadRoots.end(); I != IE; ++I) { 12403 Queue.push_back(*I); 12404 12405 while (!Queue.empty()) { 12406 SDNode *LoadRoot = Queue.pop_back_val(); 12407 if (!Visited.insert(LoadRoot).second) 12408 continue; 12409 12410 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12411 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12412 return true; 12413 12414 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12415 UE = LoadRoot->use_end(); UI != UE; ++UI) 12416 if (((isa<MemSDNode>(*UI) && 12417 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12418 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12419 Queue.push_back(*UI); 12420 } 12421 } 12422 12423 return false; 12424 } 12425 12426 /// This function is called when we have proved that a SETCC node can be replaced 12427 /// by subtraction (and other supporting instructions) so that the result of 12428 /// comparison is kept in a GPR instead of CR. This function is purely for 12429 /// codegen purposes and has some flags to guide the codegen process. 12430 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12431 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12432 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12433 12434 // Zero extend the operands to the largest legal integer. Originally, they 12435 // must be of a strictly smaller size. 12436 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12437 DAG.getConstant(Size, DL, MVT::i32)); 12438 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12439 DAG.getConstant(Size, DL, MVT::i32)); 12440 12441 // Swap if needed. Depends on the condition code. 12442 if (Swap) 12443 std::swap(Op0, Op1); 12444 12445 // Subtract extended integers. 12446 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12447 12448 // Move the sign bit to the least significant position and zero out the rest. 12449 // Now the least significant bit carries the result of original comparison. 12450 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12451 DAG.getConstant(Size - 1, DL, MVT::i32)); 12452 auto Final = Shifted; 12453 12454 // Complement the result if needed. Based on the condition code. 12455 if (Complement) 12456 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12457 DAG.getConstant(1, DL, MVT::i64)); 12458 12459 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12460 } 12461 12462 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12463 DAGCombinerInfo &DCI) const { 12464 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12465 12466 SelectionDAG &DAG = DCI.DAG; 12467 SDLoc DL(N); 12468 12469 // Size of integers being compared has a critical role in the following 12470 // analysis, so we prefer to do this when all types are legal. 12471 if (!DCI.isAfterLegalizeDAG()) 12472 return SDValue(); 12473 12474 // If all users of SETCC extend its value to a legal integer type 12475 // then we replace SETCC with a subtraction 12476 for (SDNode::use_iterator UI = N->use_begin(), 12477 UE = N->use_end(); UI != UE; ++UI) { 12478 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12479 return SDValue(); 12480 } 12481 12482 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12483 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12484 12485 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12486 12487 if (OpSize < Size) { 12488 switch (CC) { 12489 default: break; 12490 case ISD::SETULT: 12491 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12492 case ISD::SETULE: 12493 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12494 case ISD::SETUGT: 12495 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12496 case ISD::SETUGE: 12497 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12498 } 12499 } 12500 12501 return SDValue(); 12502 } 12503 12504 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12505 DAGCombinerInfo &DCI) const { 12506 SelectionDAG &DAG = DCI.DAG; 12507 SDLoc dl(N); 12508 12509 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12510 // If we're tracking CR bits, we need to be careful that we don't have: 12511 // trunc(binary-ops(zext(x), zext(y))) 12512 // or 12513 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12514 // such that we're unnecessarily moving things into GPRs when it would be 12515 // better to keep them in CR bits. 12516 12517 // Note that trunc here can be an actual i1 trunc, or can be the effective 12518 // truncation that comes from a setcc or select_cc. 12519 if (N->getOpcode() == ISD::TRUNCATE && 12520 N->getValueType(0) != MVT::i1) 12521 return SDValue(); 12522 12523 if (N->getOperand(0).getValueType() != MVT::i32 && 12524 N->getOperand(0).getValueType() != MVT::i64) 12525 return SDValue(); 12526 12527 if (N->getOpcode() == ISD::SETCC || 12528 N->getOpcode() == ISD::SELECT_CC) { 12529 // If we're looking at a comparison, then we need to make sure that the 12530 // high bits (all except for the first) don't matter the result. 12531 ISD::CondCode CC = 12532 cast<CondCodeSDNode>(N->getOperand( 12533 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12534 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12535 12536 if (ISD::isSignedIntSetCC(CC)) { 12537 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12538 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12539 return SDValue(); 12540 } else if (ISD::isUnsignedIntSetCC(CC)) { 12541 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12542 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12543 !DAG.MaskedValueIsZero(N->getOperand(1), 12544 APInt::getHighBitsSet(OpBits, OpBits-1))) 12545 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12546 : SDValue()); 12547 } else { 12548 // This is neither a signed nor an unsigned comparison, just make sure 12549 // that the high bits are equal. 12550 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12551 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12552 12553 // We don't really care about what is known about the first bit (if 12554 // anything), so clear it in all masks prior to comparing them. 12555 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12556 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12557 12558 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12559 return SDValue(); 12560 } 12561 } 12562 12563 // We now know that the higher-order bits are irrelevant, we just need to 12564 // make sure that all of the intermediate operations are bit operations, and 12565 // all inputs are extensions. 12566 if (N->getOperand(0).getOpcode() != ISD::AND && 12567 N->getOperand(0).getOpcode() != ISD::OR && 12568 N->getOperand(0).getOpcode() != ISD::XOR && 12569 N->getOperand(0).getOpcode() != ISD::SELECT && 12570 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12571 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12572 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12573 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12574 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12575 return SDValue(); 12576 12577 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12578 N->getOperand(1).getOpcode() != ISD::AND && 12579 N->getOperand(1).getOpcode() != ISD::OR && 12580 N->getOperand(1).getOpcode() != ISD::XOR && 12581 N->getOperand(1).getOpcode() != ISD::SELECT && 12582 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12583 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12584 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12585 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12586 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12587 return SDValue(); 12588 12589 SmallVector<SDValue, 4> Inputs; 12590 SmallVector<SDValue, 8> BinOps, PromOps; 12591 SmallPtrSet<SDNode *, 16> Visited; 12592 12593 for (unsigned i = 0; i < 2; ++i) { 12594 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12595 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12596 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12597 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12598 isa<ConstantSDNode>(N->getOperand(i))) 12599 Inputs.push_back(N->getOperand(i)); 12600 else 12601 BinOps.push_back(N->getOperand(i)); 12602 12603 if (N->getOpcode() == ISD::TRUNCATE) 12604 break; 12605 } 12606 12607 // Visit all inputs, collect all binary operations (and, or, xor and 12608 // select) that are all fed by extensions. 12609 while (!BinOps.empty()) { 12610 SDValue BinOp = BinOps.back(); 12611 BinOps.pop_back(); 12612 12613 if (!Visited.insert(BinOp.getNode()).second) 12614 continue; 12615 12616 PromOps.push_back(BinOp); 12617 12618 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12619 // The condition of the select is not promoted. 12620 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12621 continue; 12622 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12623 continue; 12624 12625 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12626 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12627 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12628 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12629 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12630 Inputs.push_back(BinOp.getOperand(i)); 12631 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12632 BinOp.getOperand(i).getOpcode() == ISD::OR || 12633 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12634 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12635 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12636 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12637 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12638 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12639 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12640 BinOps.push_back(BinOp.getOperand(i)); 12641 } else { 12642 // We have an input that is not an extension or another binary 12643 // operation; we'll abort this transformation. 12644 return SDValue(); 12645 } 12646 } 12647 } 12648 12649 // Make sure that this is a self-contained cluster of operations (which 12650 // is not quite the same thing as saying that everything has only one 12651 // use). 12652 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12653 if (isa<ConstantSDNode>(Inputs[i])) 12654 continue; 12655 12656 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12657 UE = Inputs[i].getNode()->use_end(); 12658 UI != UE; ++UI) { 12659 SDNode *User = *UI; 12660 if (User != N && !Visited.count(User)) 12661 return SDValue(); 12662 12663 // Make sure that we're not going to promote the non-output-value 12664 // operand(s) or SELECT or SELECT_CC. 12665 // FIXME: Although we could sometimes handle this, and it does occur in 12666 // practice that one of the condition inputs to the select is also one of 12667 // the outputs, we currently can't deal with this. 12668 if (User->getOpcode() == ISD::SELECT) { 12669 if (User->getOperand(0) == Inputs[i]) 12670 return SDValue(); 12671 } else if (User->getOpcode() == ISD::SELECT_CC) { 12672 if (User->getOperand(0) == Inputs[i] || 12673 User->getOperand(1) == Inputs[i]) 12674 return SDValue(); 12675 } 12676 } 12677 } 12678 12679 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12680 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12681 UE = PromOps[i].getNode()->use_end(); 12682 UI != UE; ++UI) { 12683 SDNode *User = *UI; 12684 if (User != N && !Visited.count(User)) 12685 return SDValue(); 12686 12687 // Make sure that we're not going to promote the non-output-value 12688 // operand(s) or SELECT or SELECT_CC. 12689 // FIXME: Although we could sometimes handle this, and it does occur in 12690 // practice that one of the condition inputs to the select is also one of 12691 // the outputs, we currently can't deal with this. 12692 if (User->getOpcode() == ISD::SELECT) { 12693 if (User->getOperand(0) == PromOps[i]) 12694 return SDValue(); 12695 } else if (User->getOpcode() == ISD::SELECT_CC) { 12696 if (User->getOperand(0) == PromOps[i] || 12697 User->getOperand(1) == PromOps[i]) 12698 return SDValue(); 12699 } 12700 } 12701 } 12702 12703 // Replace all inputs with the extension operand. 12704 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12705 // Constants may have users outside the cluster of to-be-promoted nodes, 12706 // and so we need to replace those as we do the promotions. 12707 if (isa<ConstantSDNode>(Inputs[i])) 12708 continue; 12709 else 12710 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12711 } 12712 12713 std::list<HandleSDNode> PromOpHandles; 12714 for (auto &PromOp : PromOps) 12715 PromOpHandles.emplace_back(PromOp); 12716 12717 // Replace all operations (these are all the same, but have a different 12718 // (i1) return type). DAG.getNode will validate that the types of 12719 // a binary operator match, so go through the list in reverse so that 12720 // we've likely promoted both operands first. Any intermediate truncations or 12721 // extensions disappear. 12722 while (!PromOpHandles.empty()) { 12723 SDValue PromOp = PromOpHandles.back().getValue(); 12724 PromOpHandles.pop_back(); 12725 12726 if (PromOp.getOpcode() == ISD::TRUNCATE || 12727 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12728 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12729 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12730 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12731 PromOp.getOperand(0).getValueType() != MVT::i1) { 12732 // The operand is not yet ready (see comment below). 12733 PromOpHandles.emplace_front(PromOp); 12734 continue; 12735 } 12736 12737 SDValue RepValue = PromOp.getOperand(0); 12738 if (isa<ConstantSDNode>(RepValue)) 12739 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12740 12741 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12742 continue; 12743 } 12744 12745 unsigned C; 12746 switch (PromOp.getOpcode()) { 12747 default: C = 0; break; 12748 case ISD::SELECT: C = 1; break; 12749 case ISD::SELECT_CC: C = 2; break; 12750 } 12751 12752 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12753 PromOp.getOperand(C).getValueType() != MVT::i1) || 12754 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12755 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12756 // The to-be-promoted operands of this node have not yet been 12757 // promoted (this should be rare because we're going through the 12758 // list backward, but if one of the operands has several users in 12759 // this cluster of to-be-promoted nodes, it is possible). 12760 PromOpHandles.emplace_front(PromOp); 12761 continue; 12762 } 12763 12764 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12765 PromOp.getNode()->op_end()); 12766 12767 // If there are any constant inputs, make sure they're replaced now. 12768 for (unsigned i = 0; i < 2; ++i) 12769 if (isa<ConstantSDNode>(Ops[C+i])) 12770 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12771 12772 DAG.ReplaceAllUsesOfValueWith(PromOp, 12773 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12774 } 12775 12776 // Now we're left with the initial truncation itself. 12777 if (N->getOpcode() == ISD::TRUNCATE) 12778 return N->getOperand(0); 12779 12780 // Otherwise, this is a comparison. The operands to be compared have just 12781 // changed type (to i1), but everything else is the same. 12782 return SDValue(N, 0); 12783 } 12784 12785 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12786 DAGCombinerInfo &DCI) const { 12787 SelectionDAG &DAG = DCI.DAG; 12788 SDLoc dl(N); 12789 12790 // If we're tracking CR bits, we need to be careful that we don't have: 12791 // zext(binary-ops(trunc(x), trunc(y))) 12792 // or 12793 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12794 // such that we're unnecessarily moving things into CR bits that can more 12795 // efficiently stay in GPRs. Note that if we're not certain that the high 12796 // bits are set as required by the final extension, we still may need to do 12797 // some masking to get the proper behavior. 12798 12799 // This same functionality is important on PPC64 when dealing with 12800 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12801 // the return values of functions. Because it is so similar, it is handled 12802 // here as well. 12803 12804 if (N->getValueType(0) != MVT::i32 && 12805 N->getValueType(0) != MVT::i64) 12806 return SDValue(); 12807 12808 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12809 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12810 return SDValue(); 12811 12812 if (N->getOperand(0).getOpcode() != ISD::AND && 12813 N->getOperand(0).getOpcode() != ISD::OR && 12814 N->getOperand(0).getOpcode() != ISD::XOR && 12815 N->getOperand(0).getOpcode() != ISD::SELECT && 12816 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12817 return SDValue(); 12818 12819 SmallVector<SDValue, 4> Inputs; 12820 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12821 SmallPtrSet<SDNode *, 16> Visited; 12822 12823 // Visit all inputs, collect all binary operations (and, or, xor and 12824 // select) that are all fed by truncations. 12825 while (!BinOps.empty()) { 12826 SDValue BinOp = BinOps.back(); 12827 BinOps.pop_back(); 12828 12829 if (!Visited.insert(BinOp.getNode()).second) 12830 continue; 12831 12832 PromOps.push_back(BinOp); 12833 12834 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12835 // The condition of the select is not promoted. 12836 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12837 continue; 12838 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12839 continue; 12840 12841 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12842 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12843 Inputs.push_back(BinOp.getOperand(i)); 12844 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12845 BinOp.getOperand(i).getOpcode() == ISD::OR || 12846 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12847 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12848 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12849 BinOps.push_back(BinOp.getOperand(i)); 12850 } else { 12851 // We have an input that is not a truncation or another binary 12852 // operation; we'll abort this transformation. 12853 return SDValue(); 12854 } 12855 } 12856 } 12857 12858 // The operands of a select that must be truncated when the select is 12859 // promoted because the operand is actually part of the to-be-promoted set. 12860 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12861 12862 // Make sure that this is a self-contained cluster of operations (which 12863 // is not quite the same thing as saying that everything has only one 12864 // use). 12865 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12866 if (isa<ConstantSDNode>(Inputs[i])) 12867 continue; 12868 12869 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12870 UE = Inputs[i].getNode()->use_end(); 12871 UI != UE; ++UI) { 12872 SDNode *User = *UI; 12873 if (User != N && !Visited.count(User)) 12874 return SDValue(); 12875 12876 // If we're going to promote the non-output-value operand(s) or SELECT or 12877 // SELECT_CC, record them for truncation. 12878 if (User->getOpcode() == ISD::SELECT) { 12879 if (User->getOperand(0) == Inputs[i]) 12880 SelectTruncOp[0].insert(std::make_pair(User, 12881 User->getOperand(0).getValueType())); 12882 } else if (User->getOpcode() == ISD::SELECT_CC) { 12883 if (User->getOperand(0) == Inputs[i]) 12884 SelectTruncOp[0].insert(std::make_pair(User, 12885 User->getOperand(0).getValueType())); 12886 if (User->getOperand(1) == Inputs[i]) 12887 SelectTruncOp[1].insert(std::make_pair(User, 12888 User->getOperand(1).getValueType())); 12889 } 12890 } 12891 } 12892 12893 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12894 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12895 UE = PromOps[i].getNode()->use_end(); 12896 UI != UE; ++UI) { 12897 SDNode *User = *UI; 12898 if (User != N && !Visited.count(User)) 12899 return SDValue(); 12900 12901 // If we're going to promote the non-output-value operand(s) or SELECT or 12902 // SELECT_CC, record them for truncation. 12903 if (User->getOpcode() == ISD::SELECT) { 12904 if (User->getOperand(0) == PromOps[i]) 12905 SelectTruncOp[0].insert(std::make_pair(User, 12906 User->getOperand(0).getValueType())); 12907 } else if (User->getOpcode() == ISD::SELECT_CC) { 12908 if (User->getOperand(0) == PromOps[i]) 12909 SelectTruncOp[0].insert(std::make_pair(User, 12910 User->getOperand(0).getValueType())); 12911 if (User->getOperand(1) == PromOps[i]) 12912 SelectTruncOp[1].insert(std::make_pair(User, 12913 User->getOperand(1).getValueType())); 12914 } 12915 } 12916 } 12917 12918 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12919 bool ReallyNeedsExt = false; 12920 if (N->getOpcode() != ISD::ANY_EXTEND) { 12921 // If all of the inputs are not already sign/zero extended, then 12922 // we'll still need to do that at the end. 12923 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12924 if (isa<ConstantSDNode>(Inputs[i])) 12925 continue; 12926 12927 unsigned OpBits = 12928 Inputs[i].getOperand(0).getValueSizeInBits(); 12929 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12930 12931 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12932 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12933 APInt::getHighBitsSet(OpBits, 12934 OpBits-PromBits))) || 12935 (N->getOpcode() == ISD::SIGN_EXTEND && 12936 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12937 (OpBits-(PromBits-1)))) { 12938 ReallyNeedsExt = true; 12939 break; 12940 } 12941 } 12942 } 12943 12944 // Replace all inputs, either with the truncation operand, or a 12945 // truncation or extension to the final output type. 12946 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12947 // Constant inputs need to be replaced with the to-be-promoted nodes that 12948 // use them because they might have users outside of the cluster of 12949 // promoted nodes. 12950 if (isa<ConstantSDNode>(Inputs[i])) 12951 continue; 12952 12953 SDValue InSrc = Inputs[i].getOperand(0); 12954 if (Inputs[i].getValueType() == N->getValueType(0)) 12955 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12956 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12957 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12958 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12959 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12960 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12961 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12962 else 12963 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12964 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12965 } 12966 12967 std::list<HandleSDNode> PromOpHandles; 12968 for (auto &PromOp : PromOps) 12969 PromOpHandles.emplace_back(PromOp); 12970 12971 // Replace all operations (these are all the same, but have a different 12972 // (promoted) return type). DAG.getNode will validate that the types of 12973 // a binary operator match, so go through the list in reverse so that 12974 // we've likely promoted both operands first. 12975 while (!PromOpHandles.empty()) { 12976 SDValue PromOp = PromOpHandles.back().getValue(); 12977 PromOpHandles.pop_back(); 12978 12979 unsigned C; 12980 switch (PromOp.getOpcode()) { 12981 default: C = 0; break; 12982 case ISD::SELECT: C = 1; break; 12983 case ISD::SELECT_CC: C = 2; break; 12984 } 12985 12986 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12987 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12988 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12989 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12990 // The to-be-promoted operands of this node have not yet been 12991 // promoted (this should be rare because we're going through the 12992 // list backward, but if one of the operands has several users in 12993 // this cluster of to-be-promoted nodes, it is possible). 12994 PromOpHandles.emplace_front(PromOp); 12995 continue; 12996 } 12997 12998 // For SELECT and SELECT_CC nodes, we do a similar check for any 12999 // to-be-promoted comparison inputs. 13000 if (PromOp.getOpcode() == ISD::SELECT || 13001 PromOp.getOpcode() == ISD::SELECT_CC) { 13002 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13003 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13004 (SelectTruncOp[1].count(PromOp.getNode()) && 13005 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13006 PromOpHandles.emplace_front(PromOp); 13007 continue; 13008 } 13009 } 13010 13011 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13012 PromOp.getNode()->op_end()); 13013 13014 // If this node has constant inputs, then they'll need to be promoted here. 13015 for (unsigned i = 0; i < 2; ++i) { 13016 if (!isa<ConstantSDNode>(Ops[C+i])) 13017 continue; 13018 if (Ops[C+i].getValueType() == N->getValueType(0)) 13019 continue; 13020 13021 if (N->getOpcode() == ISD::SIGN_EXTEND) 13022 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13023 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13024 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13025 else 13026 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13027 } 13028 13029 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13030 // truncate them again to the original value type. 13031 if (PromOp.getOpcode() == ISD::SELECT || 13032 PromOp.getOpcode() == ISD::SELECT_CC) { 13033 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13034 if (SI0 != SelectTruncOp[0].end()) 13035 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13036 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13037 if (SI1 != SelectTruncOp[1].end()) 13038 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13039 } 13040 13041 DAG.ReplaceAllUsesOfValueWith(PromOp, 13042 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13043 } 13044 13045 // Now we're left with the initial extension itself. 13046 if (!ReallyNeedsExt) 13047 return N->getOperand(0); 13048 13049 // To zero extend, just mask off everything except for the first bit (in the 13050 // i1 case). 13051 if (N->getOpcode() == ISD::ZERO_EXTEND) 13052 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13053 DAG.getConstant(APInt::getLowBitsSet( 13054 N->getValueSizeInBits(0), PromBits), 13055 dl, N->getValueType(0))); 13056 13057 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13058 "Invalid extension type"); 13059 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13060 SDValue ShiftCst = 13061 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13062 return DAG.getNode( 13063 ISD::SRA, dl, N->getValueType(0), 13064 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13065 ShiftCst); 13066 } 13067 13068 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13069 DAGCombinerInfo &DCI) const { 13070 assert(N->getOpcode() == ISD::SETCC && 13071 "Should be called with a SETCC node"); 13072 13073 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13074 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13075 SDValue LHS = N->getOperand(0); 13076 SDValue RHS = N->getOperand(1); 13077 13078 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13079 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13080 LHS.hasOneUse()) 13081 std::swap(LHS, RHS); 13082 13083 // x == 0-y --> x+y == 0 13084 // x != 0-y --> x+y != 0 13085 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13086 RHS.hasOneUse()) { 13087 SDLoc DL(N); 13088 SelectionDAG &DAG = DCI.DAG; 13089 EVT VT = N->getValueType(0); 13090 EVT OpVT = LHS.getValueType(); 13091 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13092 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13093 } 13094 } 13095 13096 return DAGCombineTruncBoolExt(N, DCI); 13097 } 13098 13099 // Is this an extending load from an f32 to an f64? 13100 static bool isFPExtLoad(SDValue Op) { 13101 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13102 return LD->getExtensionType() == ISD::EXTLOAD && 13103 Op.getValueType() == MVT::f64; 13104 return false; 13105 } 13106 13107 /// Reduces the number of fp-to-int conversion when building a vector. 13108 /// 13109 /// If this vector is built out of floating to integer conversions, 13110 /// transform it to a vector built out of floating point values followed by a 13111 /// single floating to integer conversion of the vector. 13112 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13113 /// becomes (fptosi (build_vector ($A, $B, ...))) 13114 SDValue PPCTargetLowering:: 13115 combineElementTruncationToVectorTruncation(SDNode *N, 13116 DAGCombinerInfo &DCI) const { 13117 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13118 "Should be called with a BUILD_VECTOR node"); 13119 13120 SelectionDAG &DAG = DCI.DAG; 13121 SDLoc dl(N); 13122 13123 SDValue FirstInput = N->getOperand(0); 13124 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13125 "The input operand must be an fp-to-int conversion."); 13126 13127 // This combine happens after legalization so the fp_to_[su]i nodes are 13128 // already converted to PPCSISD nodes. 13129 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13130 if (FirstConversion == PPCISD::FCTIDZ || 13131 FirstConversion == PPCISD::FCTIDUZ || 13132 FirstConversion == PPCISD::FCTIWZ || 13133 FirstConversion == PPCISD::FCTIWUZ) { 13134 bool IsSplat = true; 13135 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13136 FirstConversion == PPCISD::FCTIWUZ; 13137 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13138 SmallVector<SDValue, 4> Ops; 13139 EVT TargetVT = N->getValueType(0); 13140 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13141 SDValue NextOp = N->getOperand(i); 13142 if (NextOp.getOpcode() != PPCISD::MFVSR) 13143 return SDValue(); 13144 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13145 if (NextConversion != FirstConversion) 13146 return SDValue(); 13147 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13148 // This is not valid if the input was originally double precision. It is 13149 // also not profitable to do unless this is an extending load in which 13150 // case doing this combine will allow us to combine consecutive loads. 13151 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13152 return SDValue(); 13153 if (N->getOperand(i) != FirstInput) 13154 IsSplat = false; 13155 } 13156 13157 // If this is a splat, we leave it as-is since there will be only a single 13158 // fp-to-int conversion followed by a splat of the integer. This is better 13159 // for 32-bit and smaller ints and neutral for 64-bit ints. 13160 if (IsSplat) 13161 return SDValue(); 13162 13163 // Now that we know we have the right type of node, get its operands 13164 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13165 SDValue In = N->getOperand(i).getOperand(0); 13166 if (Is32Bit) { 13167 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13168 // here, we know that all inputs are extending loads so this is safe). 13169 if (In.isUndef()) 13170 Ops.push_back(DAG.getUNDEF(SrcVT)); 13171 else { 13172 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13173 MVT::f32, In.getOperand(0), 13174 DAG.getIntPtrConstant(1, dl)); 13175 Ops.push_back(Trunc); 13176 } 13177 } else 13178 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13179 } 13180 13181 unsigned Opcode; 13182 if (FirstConversion == PPCISD::FCTIDZ || 13183 FirstConversion == PPCISD::FCTIWZ) 13184 Opcode = ISD::FP_TO_SINT; 13185 else 13186 Opcode = ISD::FP_TO_UINT; 13187 13188 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13189 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13190 return DAG.getNode(Opcode, dl, TargetVT, BV); 13191 } 13192 return SDValue(); 13193 } 13194 13195 /// Reduce the number of loads when building a vector. 13196 /// 13197 /// Building a vector out of multiple loads can be converted to a load 13198 /// of the vector type if the loads are consecutive. If the loads are 13199 /// consecutive but in descending order, a shuffle is added at the end 13200 /// to reorder the vector. 13201 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13202 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13203 "Should be called with a BUILD_VECTOR node"); 13204 13205 SDLoc dl(N); 13206 13207 // Return early for non byte-sized type, as they can't be consecutive. 13208 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13209 return SDValue(); 13210 13211 bool InputsAreConsecutiveLoads = true; 13212 bool InputsAreReverseConsecutive = true; 13213 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13214 SDValue FirstInput = N->getOperand(0); 13215 bool IsRoundOfExtLoad = false; 13216 13217 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13218 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13219 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13220 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13221 } 13222 // Not a build vector of (possibly fp_rounded) loads. 13223 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13224 N->getNumOperands() == 1) 13225 return SDValue(); 13226 13227 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13228 // If any inputs are fp_round(extload), they all must be. 13229 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13230 return SDValue(); 13231 13232 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13233 N->getOperand(i); 13234 if (NextInput.getOpcode() != ISD::LOAD) 13235 return SDValue(); 13236 13237 SDValue PreviousInput = 13238 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13239 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13240 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13241 13242 // If any inputs are fp_round(extload), they all must be. 13243 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13244 return SDValue(); 13245 13246 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13247 InputsAreConsecutiveLoads = false; 13248 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13249 InputsAreReverseConsecutive = false; 13250 13251 // Exit early if the loads are neither consecutive nor reverse consecutive. 13252 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13253 return SDValue(); 13254 } 13255 13256 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13257 "The loads cannot be both consecutive and reverse consecutive."); 13258 13259 SDValue FirstLoadOp = 13260 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13261 SDValue LastLoadOp = 13262 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13263 N->getOperand(N->getNumOperands()-1); 13264 13265 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13266 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13267 if (InputsAreConsecutiveLoads) { 13268 assert(LD1 && "Input needs to be a LoadSDNode."); 13269 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13270 LD1->getBasePtr(), LD1->getPointerInfo(), 13271 LD1->getAlignment()); 13272 } 13273 if (InputsAreReverseConsecutive) { 13274 assert(LDL && "Input needs to be a LoadSDNode."); 13275 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13276 LDL->getBasePtr(), LDL->getPointerInfo(), 13277 LDL->getAlignment()); 13278 SmallVector<int, 16> Ops; 13279 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13280 Ops.push_back(i); 13281 13282 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13283 DAG.getUNDEF(N->getValueType(0)), Ops); 13284 } 13285 return SDValue(); 13286 } 13287 13288 // This function adds the required vector_shuffle needed to get 13289 // the elements of the vector extract in the correct position 13290 // as specified by the CorrectElems encoding. 13291 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13292 SDValue Input, uint64_t Elems, 13293 uint64_t CorrectElems) { 13294 SDLoc dl(N); 13295 13296 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13297 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13298 13299 // Knowing the element indices being extracted from the original 13300 // vector and the order in which they're being inserted, just put 13301 // them at element indices required for the instruction. 13302 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13303 if (DAG.getDataLayout().isLittleEndian()) 13304 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13305 else 13306 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13307 CorrectElems = CorrectElems >> 8; 13308 Elems = Elems >> 8; 13309 } 13310 13311 SDValue Shuffle = 13312 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13313 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13314 13315 EVT VT = N->getValueType(0); 13316 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13317 13318 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13319 Input.getValueType().getVectorElementType(), 13320 VT.getVectorNumElements()); 13321 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13322 DAG.getValueType(ExtVT)); 13323 } 13324 13325 // Look for build vector patterns where input operands come from sign 13326 // extended vector_extract elements of specific indices. If the correct indices 13327 // aren't used, add a vector shuffle to fix up the indices and create 13328 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13329 // during instruction selection. 13330 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13331 // This array encodes the indices that the vector sign extend instructions 13332 // extract from when extending from one type to another for both BE and LE. 13333 // The right nibble of each byte corresponds to the LE incides. 13334 // and the left nibble of each byte corresponds to the BE incides. 13335 // For example: 0x3074B8FC byte->word 13336 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13337 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13338 // For example: 0x000070F8 byte->double word 13339 // For LE: the allowed indices are: 0x0,0x8 13340 // For BE: the allowed indices are: 0x7,0xF 13341 uint64_t TargetElems[] = { 13342 0x3074B8FC, // b->w 13343 0x000070F8, // b->d 13344 0x10325476, // h->w 13345 0x00003074, // h->d 13346 0x00001032, // w->d 13347 }; 13348 13349 uint64_t Elems = 0; 13350 int Index; 13351 SDValue Input; 13352 13353 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13354 if (!Op) 13355 return false; 13356 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13357 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13358 return false; 13359 13360 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13361 // of the right width. 13362 SDValue Extract = Op.getOperand(0); 13363 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13364 Extract = Extract.getOperand(0); 13365 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13366 return false; 13367 13368 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13369 if (!ExtOp) 13370 return false; 13371 13372 Index = ExtOp->getZExtValue(); 13373 if (Input && Input != Extract.getOperand(0)) 13374 return false; 13375 13376 if (!Input) 13377 Input = Extract.getOperand(0); 13378 13379 Elems = Elems << 8; 13380 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13381 Elems |= Index; 13382 13383 return true; 13384 }; 13385 13386 // If the build vector operands aren't sign extended vector extracts, 13387 // of the same input vector, then return. 13388 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13389 if (!isSExtOfVecExtract(N->getOperand(i))) { 13390 return SDValue(); 13391 } 13392 } 13393 13394 // If the vector extract indicies are not correct, add the appropriate 13395 // vector_shuffle. 13396 int TgtElemArrayIdx; 13397 int InputSize = Input.getValueType().getScalarSizeInBits(); 13398 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13399 if (InputSize + OutputSize == 40) 13400 TgtElemArrayIdx = 0; 13401 else if (InputSize + OutputSize == 72) 13402 TgtElemArrayIdx = 1; 13403 else if (InputSize + OutputSize == 48) 13404 TgtElemArrayIdx = 2; 13405 else if (InputSize + OutputSize == 80) 13406 TgtElemArrayIdx = 3; 13407 else if (InputSize + OutputSize == 96) 13408 TgtElemArrayIdx = 4; 13409 else 13410 return SDValue(); 13411 13412 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13413 CorrectElems = DAG.getDataLayout().isLittleEndian() 13414 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13415 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13416 if (Elems != CorrectElems) { 13417 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13418 } 13419 13420 // Regular lowering will catch cases where a shuffle is not needed. 13421 return SDValue(); 13422 } 13423 13424 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13425 DAGCombinerInfo &DCI) const { 13426 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13427 "Should be called with a BUILD_VECTOR node"); 13428 13429 SelectionDAG &DAG = DCI.DAG; 13430 SDLoc dl(N); 13431 13432 if (!Subtarget.hasVSX()) 13433 return SDValue(); 13434 13435 // The target independent DAG combiner will leave a build_vector of 13436 // float-to-int conversions intact. We can generate MUCH better code for 13437 // a float-to-int conversion of a vector of floats. 13438 SDValue FirstInput = N->getOperand(0); 13439 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13440 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13441 if (Reduced) 13442 return Reduced; 13443 } 13444 13445 // If we're building a vector out of consecutive loads, just load that 13446 // vector type. 13447 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13448 if (Reduced) 13449 return Reduced; 13450 13451 // If we're building a vector out of extended elements from another vector 13452 // we have P9 vector integer extend instructions. The code assumes legal 13453 // input types (i.e. it can't handle things like v4i16) so do not run before 13454 // legalization. 13455 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13456 Reduced = combineBVOfVecSExt(N, DAG); 13457 if (Reduced) 13458 return Reduced; 13459 } 13460 13461 13462 if (N->getValueType(0) != MVT::v2f64) 13463 return SDValue(); 13464 13465 // Looking for: 13466 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13467 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13468 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13469 return SDValue(); 13470 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13471 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13472 return SDValue(); 13473 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13474 return SDValue(); 13475 13476 SDValue Ext1 = FirstInput.getOperand(0); 13477 SDValue Ext2 = N->getOperand(1).getOperand(0); 13478 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13479 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13480 return SDValue(); 13481 13482 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13483 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13484 if (!Ext1Op || !Ext2Op) 13485 return SDValue(); 13486 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13487 Ext1.getOperand(0) != Ext2.getOperand(0)) 13488 return SDValue(); 13489 13490 int FirstElem = Ext1Op->getZExtValue(); 13491 int SecondElem = Ext2Op->getZExtValue(); 13492 int SubvecIdx; 13493 if (FirstElem == 0 && SecondElem == 1) 13494 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13495 else if (FirstElem == 2 && SecondElem == 3) 13496 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13497 else 13498 return SDValue(); 13499 13500 SDValue SrcVec = Ext1.getOperand(0); 13501 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13502 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13503 return DAG.getNode(NodeType, dl, MVT::v2f64, 13504 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13505 } 13506 13507 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13508 DAGCombinerInfo &DCI) const { 13509 assert((N->getOpcode() == ISD::SINT_TO_FP || 13510 N->getOpcode() == ISD::UINT_TO_FP) && 13511 "Need an int -> FP conversion node here"); 13512 13513 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13514 return SDValue(); 13515 13516 SelectionDAG &DAG = DCI.DAG; 13517 SDLoc dl(N); 13518 SDValue Op(N, 0); 13519 13520 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13521 // from the hardware. 13522 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13523 return SDValue(); 13524 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13525 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13526 return SDValue(); 13527 13528 SDValue FirstOperand(Op.getOperand(0)); 13529 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13530 (FirstOperand.getValueType() == MVT::i8 || 13531 FirstOperand.getValueType() == MVT::i16); 13532 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13533 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13534 bool DstDouble = Op.getValueType() == MVT::f64; 13535 unsigned ConvOp = Signed ? 13536 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13537 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13538 SDValue WidthConst = 13539 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13540 dl, false); 13541 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13542 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13543 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13544 DAG.getVTList(MVT::f64, MVT::Other), 13545 Ops, MVT::i8, LDN->getMemOperand()); 13546 13547 // For signed conversion, we need to sign-extend the value in the VSR 13548 if (Signed) { 13549 SDValue ExtOps[] = { Ld, WidthConst }; 13550 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13551 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13552 } else 13553 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13554 } 13555 13556 13557 // For i32 intermediate values, unfortunately, the conversion functions 13558 // leave the upper 32 bits of the value are undefined. Within the set of 13559 // scalar instructions, we have no method for zero- or sign-extending the 13560 // value. Thus, we cannot handle i32 intermediate values here. 13561 if (Op.getOperand(0).getValueType() == MVT::i32) 13562 return SDValue(); 13563 13564 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13565 "UINT_TO_FP is supported only with FPCVT"); 13566 13567 // If we have FCFIDS, then use it when converting to single-precision. 13568 // Otherwise, convert to double-precision and then round. 13569 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13570 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13571 : PPCISD::FCFIDS) 13572 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13573 : PPCISD::FCFID); 13574 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13575 ? MVT::f32 13576 : MVT::f64; 13577 13578 // If we're converting from a float, to an int, and back to a float again, 13579 // then we don't need the store/load pair at all. 13580 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13581 Subtarget.hasFPCVT()) || 13582 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13583 SDValue Src = Op.getOperand(0).getOperand(0); 13584 if (Src.getValueType() == MVT::f32) { 13585 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13586 DCI.AddToWorklist(Src.getNode()); 13587 } else if (Src.getValueType() != MVT::f64) { 13588 // Make sure that we don't pick up a ppc_fp128 source value. 13589 return SDValue(); 13590 } 13591 13592 unsigned FCTOp = 13593 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13594 PPCISD::FCTIDUZ; 13595 13596 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13597 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13598 13599 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13600 FP = DAG.getNode(ISD::FP_ROUND, dl, 13601 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13602 DCI.AddToWorklist(FP.getNode()); 13603 } 13604 13605 return FP; 13606 } 13607 13608 return SDValue(); 13609 } 13610 13611 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13612 // builtins) into loads with swaps. 13613 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13614 DAGCombinerInfo &DCI) const { 13615 SelectionDAG &DAG = DCI.DAG; 13616 SDLoc dl(N); 13617 SDValue Chain; 13618 SDValue Base; 13619 MachineMemOperand *MMO; 13620 13621 switch (N->getOpcode()) { 13622 default: 13623 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13624 case ISD::LOAD: { 13625 LoadSDNode *LD = cast<LoadSDNode>(N); 13626 Chain = LD->getChain(); 13627 Base = LD->getBasePtr(); 13628 MMO = LD->getMemOperand(); 13629 // If the MMO suggests this isn't a load of a full vector, leave 13630 // things alone. For a built-in, we have to make the change for 13631 // correctness, so if there is a size problem that will be a bug. 13632 if (MMO->getSize() < 16) 13633 return SDValue(); 13634 break; 13635 } 13636 case ISD::INTRINSIC_W_CHAIN: { 13637 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13638 Chain = Intrin->getChain(); 13639 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13640 // us what we want. Get operand 2 instead. 13641 Base = Intrin->getOperand(2); 13642 MMO = Intrin->getMemOperand(); 13643 break; 13644 } 13645 } 13646 13647 MVT VecTy = N->getValueType(0).getSimpleVT(); 13648 13649 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13650 // aligned and the type is a vector with elements up to 4 bytes 13651 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13652 VecTy.getScalarSizeInBits() <= 32) { 13653 return SDValue(); 13654 } 13655 13656 SDValue LoadOps[] = { Chain, Base }; 13657 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13658 DAG.getVTList(MVT::v2f64, MVT::Other), 13659 LoadOps, MVT::v2f64, MMO); 13660 13661 DCI.AddToWorklist(Load.getNode()); 13662 Chain = Load.getValue(1); 13663 SDValue Swap = DAG.getNode( 13664 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13665 DCI.AddToWorklist(Swap.getNode()); 13666 13667 // Add a bitcast if the resulting load type doesn't match v2f64. 13668 if (VecTy != MVT::v2f64) { 13669 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13670 DCI.AddToWorklist(N.getNode()); 13671 // Package {bitcast value, swap's chain} to match Load's shape. 13672 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13673 N, Swap.getValue(1)); 13674 } 13675 13676 return Swap; 13677 } 13678 13679 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13680 // builtins) into stores with swaps. 13681 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13682 DAGCombinerInfo &DCI) const { 13683 SelectionDAG &DAG = DCI.DAG; 13684 SDLoc dl(N); 13685 SDValue Chain; 13686 SDValue Base; 13687 unsigned SrcOpnd; 13688 MachineMemOperand *MMO; 13689 13690 switch (N->getOpcode()) { 13691 default: 13692 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13693 case ISD::STORE: { 13694 StoreSDNode *ST = cast<StoreSDNode>(N); 13695 Chain = ST->getChain(); 13696 Base = ST->getBasePtr(); 13697 MMO = ST->getMemOperand(); 13698 SrcOpnd = 1; 13699 // If the MMO suggests this isn't a store of a full vector, leave 13700 // things alone. For a built-in, we have to make the change for 13701 // correctness, so if there is a size problem that will be a bug. 13702 if (MMO->getSize() < 16) 13703 return SDValue(); 13704 break; 13705 } 13706 case ISD::INTRINSIC_VOID: { 13707 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13708 Chain = Intrin->getChain(); 13709 // Intrin->getBasePtr() oddly does not get what we want. 13710 Base = Intrin->getOperand(3); 13711 MMO = Intrin->getMemOperand(); 13712 SrcOpnd = 2; 13713 break; 13714 } 13715 } 13716 13717 SDValue Src = N->getOperand(SrcOpnd); 13718 MVT VecTy = Src.getValueType().getSimpleVT(); 13719 13720 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13721 // aligned and the type is a vector with elements up to 4 bytes 13722 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13723 VecTy.getScalarSizeInBits() <= 32) { 13724 return SDValue(); 13725 } 13726 13727 // All stores are done as v2f64 and possible bit cast. 13728 if (VecTy != MVT::v2f64) { 13729 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13730 DCI.AddToWorklist(Src.getNode()); 13731 } 13732 13733 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13734 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13735 DCI.AddToWorklist(Swap.getNode()); 13736 Chain = Swap.getValue(1); 13737 SDValue StoreOps[] = { Chain, Swap, Base }; 13738 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13739 DAG.getVTList(MVT::Other), 13740 StoreOps, VecTy, MMO); 13741 DCI.AddToWorklist(Store.getNode()); 13742 return Store; 13743 } 13744 13745 // Handle DAG combine for STORE (FP_TO_INT F). 13746 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13747 DAGCombinerInfo &DCI) const { 13748 13749 SelectionDAG &DAG = DCI.DAG; 13750 SDLoc dl(N); 13751 unsigned Opcode = N->getOperand(1).getOpcode(); 13752 13753 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13754 && "Not a FP_TO_INT Instruction!"); 13755 13756 SDValue Val = N->getOperand(1).getOperand(0); 13757 EVT Op1VT = N->getOperand(1).getValueType(); 13758 EVT ResVT = Val.getValueType(); 13759 13760 // Floating point types smaller than 32 bits are not legal on Power. 13761 if (ResVT.getScalarSizeInBits() < 32) 13762 return SDValue(); 13763 13764 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13765 bool ValidTypeForStoreFltAsInt = 13766 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13767 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13768 13769 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13770 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13771 return SDValue(); 13772 13773 // Extend f32 values to f64 13774 if (ResVT.getScalarSizeInBits() == 32) { 13775 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13776 DCI.AddToWorklist(Val.getNode()); 13777 } 13778 13779 // Set signed or unsigned conversion opcode. 13780 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13781 PPCISD::FP_TO_SINT_IN_VSR : 13782 PPCISD::FP_TO_UINT_IN_VSR; 13783 13784 Val = DAG.getNode(ConvOpcode, 13785 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13786 DCI.AddToWorklist(Val.getNode()); 13787 13788 // Set number of bytes being converted. 13789 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13790 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13791 DAG.getIntPtrConstant(ByteSize, dl, false), 13792 DAG.getValueType(Op1VT) }; 13793 13794 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13795 DAG.getVTList(MVT::Other), Ops, 13796 cast<StoreSDNode>(N)->getMemoryVT(), 13797 cast<StoreSDNode>(N)->getMemOperand()); 13798 13799 DCI.AddToWorklist(Val.getNode()); 13800 return Val; 13801 } 13802 13803 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 13804 // Check that the source of the element keeps flipping 13805 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 13806 bool PrevElemFromFirstVec = Mask[0] < NumElts; 13807 for (int i = 1, e = Mask.size(); i < e; i++) { 13808 if (PrevElemFromFirstVec && Mask[i] < NumElts) 13809 return false; 13810 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 13811 return false; 13812 PrevElemFromFirstVec = !PrevElemFromFirstVec; 13813 } 13814 return true; 13815 } 13816 13817 static bool isSplatBV(SDValue Op) { 13818 if (Op.getOpcode() != ISD::BUILD_VECTOR) 13819 return false; 13820 SDValue FirstOp; 13821 13822 // Find first non-undef input. 13823 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 13824 FirstOp = Op.getOperand(i); 13825 if (!FirstOp.isUndef()) 13826 break; 13827 } 13828 13829 // All inputs are undef or the same as the first non-undef input. 13830 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 13831 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 13832 return false; 13833 return true; 13834 } 13835 13836 static SDValue isScalarToVec(SDValue Op) { 13837 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13838 return Op; 13839 if (Op.getOpcode() != ISD::BITCAST) 13840 return SDValue(); 13841 Op = Op.getOperand(0); 13842 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13843 return Op; 13844 return SDValue(); 13845 } 13846 13847 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 13848 int LHSMaxIdx, int RHSMinIdx, 13849 int RHSMaxIdx, int HalfVec) { 13850 for (int i = 0, e = ShuffV.size(); i < e; i++) { 13851 int Idx = ShuffV[i]; 13852 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 13853 ShuffV[i] += HalfVec; 13854 } 13855 return; 13856 } 13857 13858 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 13859 // the original is: 13860 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 13861 // In such a case, just change the shuffle mask to extract the element 13862 // from the permuted index. 13863 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 13864 SDLoc dl(OrigSToV); 13865 EVT VT = OrigSToV.getValueType(); 13866 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 13867 "Expecting a SCALAR_TO_VECTOR here"); 13868 SDValue Input = OrigSToV.getOperand(0); 13869 13870 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13871 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 13872 SDValue OrigVector = Input.getOperand(0); 13873 13874 // Can't handle non-const element indices or different vector types 13875 // for the input to the extract and the output of the scalar_to_vector. 13876 if (Idx && VT == OrigVector.getValueType()) { 13877 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 13878 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 13879 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 13880 } 13881 } 13882 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 13883 OrigSToV.getOperand(0)); 13884 } 13885 13886 // On little endian subtargets, combine shuffles such as: 13887 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 13888 // into: 13889 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 13890 // because the latter can be matched to a single instruction merge. 13891 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 13892 // to put the value into element zero. Adjust the shuffle mask so that the 13893 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 13894 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 13895 SelectionDAG &DAG) const { 13896 SDValue LHS = SVN->getOperand(0); 13897 SDValue RHS = SVN->getOperand(1); 13898 auto Mask = SVN->getMask(); 13899 int NumElts = LHS.getValueType().getVectorNumElements(); 13900 SDValue Res(SVN, 0); 13901 SDLoc dl(SVN); 13902 13903 // None of these combines are useful on big endian systems since the ISA 13904 // already has a big endian bias. 13905 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13906 return Res; 13907 13908 // If this is not a shuffle of a shuffle and the first element comes from 13909 // the second vector, canonicalize to the commuted form. This will make it 13910 // more likely to match one of the single instruction patterns. 13911 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 13912 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 13913 std::swap(LHS, RHS); 13914 Res = DAG.getCommutedVectorShuffle(*SVN); 13915 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 13916 } 13917 13918 // Adjust the shuffle mask if either input vector comes from a 13919 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 13920 // form (to prevent the need for a swap). 13921 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 13922 SDValue SToVLHS = isScalarToVec(LHS); 13923 SDValue SToVRHS = isScalarToVec(RHS); 13924 if (SToVLHS || SToVRHS) { 13925 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 13926 : SToVRHS.getValueType().getVectorNumElements(); 13927 int NumEltsOut = ShuffV.size(); 13928 13929 // Initially assume that neither input is permuted. These will be adjusted 13930 // accordingly if either input is. 13931 int LHSMaxIdx = -1; 13932 int RHSMinIdx = -1; 13933 int RHSMaxIdx = -1; 13934 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 13935 13936 // Get the permuted scalar to vector nodes for the source(s) that come from 13937 // ISD::SCALAR_TO_VECTOR. 13938 if (SToVLHS) { 13939 // Set up the values for the shuffle vector fixup. 13940 LHSMaxIdx = NumEltsOut / NumEltsIn; 13941 SToVLHS = getSToVPermuted(SToVLHS, DAG); 13942 if (SToVLHS.getValueType() != LHS.getValueType()) 13943 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 13944 LHS = SToVLHS; 13945 } 13946 if (SToVRHS) { 13947 RHSMinIdx = NumEltsOut; 13948 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 13949 SToVRHS = getSToVPermuted(SToVRHS, DAG); 13950 if (SToVRHS.getValueType() != RHS.getValueType()) 13951 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 13952 RHS = SToVRHS; 13953 } 13954 13955 // Fix up the shuffle mask to reflect where the desired element actually is. 13956 // The minimum and maximum indices that correspond to element zero for both 13957 // the LHS and RHS are computed and will control which shuffle mask entries 13958 // are to be changed. For example, if the RHS is permuted, any shuffle mask 13959 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 13960 // HalfVec to refer to the corresponding element in the permuted vector. 13961 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 13962 HalfVec); 13963 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 13964 13965 // We may have simplified away the shuffle. We won't be able to do anything 13966 // further with it here. 13967 if (!isa<ShuffleVectorSDNode>(Res)) 13968 return Res; 13969 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 13970 } 13971 13972 // The common case after we commuted the shuffle is that the RHS is a splat 13973 // and we have elements coming in from the splat at indices that are not 13974 // conducive to using a merge. 13975 // Example: 13976 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 13977 if (!isSplatBV(RHS)) 13978 return Res; 13979 13980 // We are looking for a mask such that all even elements are from 13981 // one vector and all odd elements from the other. 13982 if (!isAlternatingShuffMask(Mask, NumElts)) 13983 return Res; 13984 13985 // Adjust the mask so we are pulling in the same index from the splat 13986 // as the index from the interesting vector in consecutive elements. 13987 // Example (even elements from first vector): 13988 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 13989 if (Mask[0] < NumElts) 13990 for (int i = 1, e = Mask.size(); i < e; i += 2) 13991 ShuffV[i] = (ShuffV[i - 1] + NumElts); 13992 // Example (odd elements from first vector): 13993 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 13994 else 13995 for (int i = 0, e = Mask.size(); i < e; i += 2) 13996 ShuffV[i] = (ShuffV[i + 1] + NumElts); 13997 13998 // If the RHS has undefs, we need to remove them since we may have created 13999 // a shuffle that adds those instead of the splat value. 14000 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14001 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14002 14003 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14004 return Res; 14005 } 14006 14007 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14008 LSBaseSDNode *LSBase, 14009 DAGCombinerInfo &DCI) const { 14010 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14011 "Not a reverse memop pattern!"); 14012 14013 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14014 auto Mask = SVN->getMask(); 14015 int i = 0; 14016 auto I = Mask.rbegin(); 14017 auto E = Mask.rend(); 14018 14019 for (; I != E; ++I) { 14020 if (*I != i) 14021 return false; 14022 i++; 14023 } 14024 return true; 14025 }; 14026 14027 SelectionDAG &DAG = DCI.DAG; 14028 EVT VT = SVN->getValueType(0); 14029 14030 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14031 return SDValue(); 14032 14033 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14034 // See comment in PPCVSXSwapRemoval.cpp. 14035 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14036 if (!Subtarget.hasP9Vector()) 14037 return SDValue(); 14038 14039 if(!IsElementReverse(SVN)) 14040 return SDValue(); 14041 14042 if (LSBase->getOpcode() == ISD::LOAD) { 14043 SDLoc dl(SVN); 14044 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14045 return DAG.getMemIntrinsicNode( 14046 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14047 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14048 } 14049 14050 if (LSBase->getOpcode() == ISD::STORE) { 14051 SDLoc dl(LSBase); 14052 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14053 LSBase->getBasePtr()}; 14054 return DAG.getMemIntrinsicNode( 14055 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14056 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14057 } 14058 14059 llvm_unreachable("Expected a load or store node here"); 14060 } 14061 14062 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14063 DAGCombinerInfo &DCI) const { 14064 SelectionDAG &DAG = DCI.DAG; 14065 SDLoc dl(N); 14066 switch (N->getOpcode()) { 14067 default: break; 14068 case ISD::ADD: 14069 return combineADD(N, DCI); 14070 case ISD::SHL: 14071 return combineSHL(N, DCI); 14072 case ISD::SRA: 14073 return combineSRA(N, DCI); 14074 case ISD::SRL: 14075 return combineSRL(N, DCI); 14076 case ISD::MUL: 14077 return combineMUL(N, DCI); 14078 case ISD::FMA: 14079 case PPCISD::FNMSUB: 14080 return combineFMALike(N, DCI); 14081 case PPCISD::SHL: 14082 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14083 return N->getOperand(0); 14084 break; 14085 case PPCISD::SRL: 14086 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14087 return N->getOperand(0); 14088 break; 14089 case PPCISD::SRA: 14090 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14091 if (C->isNullValue() || // 0 >>s V -> 0. 14092 C->isAllOnesValue()) // -1 >>s V -> -1. 14093 return N->getOperand(0); 14094 } 14095 break; 14096 case ISD::SIGN_EXTEND: 14097 case ISD::ZERO_EXTEND: 14098 case ISD::ANY_EXTEND: 14099 return DAGCombineExtBoolTrunc(N, DCI); 14100 case ISD::TRUNCATE: 14101 return combineTRUNCATE(N, DCI); 14102 case ISD::SETCC: 14103 if (SDValue CSCC = combineSetCC(N, DCI)) 14104 return CSCC; 14105 LLVM_FALLTHROUGH; 14106 case ISD::SELECT_CC: 14107 return DAGCombineTruncBoolExt(N, DCI); 14108 case ISD::SINT_TO_FP: 14109 case ISD::UINT_TO_FP: 14110 return combineFPToIntToFP(N, DCI); 14111 case ISD::VECTOR_SHUFFLE: 14112 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14113 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14114 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14115 } 14116 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14117 case ISD::STORE: { 14118 14119 EVT Op1VT = N->getOperand(1).getValueType(); 14120 unsigned Opcode = N->getOperand(1).getOpcode(); 14121 14122 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14123 SDValue Val= combineStoreFPToInt(N, DCI); 14124 if (Val) 14125 return Val; 14126 } 14127 14128 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14129 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14130 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14131 if (Val) 14132 return Val; 14133 } 14134 14135 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14136 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14137 N->getOperand(1).getNode()->hasOneUse() && 14138 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14139 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14140 14141 // STBRX can only handle simple types and it makes no sense to store less 14142 // two bytes in byte-reversed order. 14143 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14144 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14145 break; 14146 14147 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14148 // Do an any-extend to 32-bits if this is a half-word input. 14149 if (BSwapOp.getValueType() == MVT::i16) 14150 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14151 14152 // If the type of BSWAP operand is wider than stored memory width 14153 // it need to be shifted to the right side before STBRX. 14154 if (Op1VT.bitsGT(mVT)) { 14155 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14156 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14157 DAG.getConstant(Shift, dl, MVT::i32)); 14158 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14159 if (Op1VT == MVT::i64) 14160 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14161 } 14162 14163 SDValue Ops[] = { 14164 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14165 }; 14166 return 14167 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14168 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14169 cast<StoreSDNode>(N)->getMemOperand()); 14170 } 14171 14172 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14173 // So it can increase the chance of CSE constant construction. 14174 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14175 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14176 // Need to sign-extended to 64-bits to handle negative values. 14177 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14178 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14179 MemVT.getSizeInBits()); 14180 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14181 14182 // DAG.getTruncStore() can't be used here because it doesn't accept 14183 // the general (base + offset) addressing mode. 14184 // So we use UpdateNodeOperands and setTruncatingStore instead. 14185 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14186 N->getOperand(3)); 14187 cast<StoreSDNode>(N)->setTruncatingStore(true); 14188 return SDValue(N, 0); 14189 } 14190 14191 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14192 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14193 if (Op1VT.isSimple()) { 14194 MVT StoreVT = Op1VT.getSimpleVT(); 14195 if (Subtarget.needsSwapsForVSXMemOps() && 14196 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14197 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14198 return expandVSXStoreForLE(N, DCI); 14199 } 14200 break; 14201 } 14202 case ISD::LOAD: { 14203 LoadSDNode *LD = cast<LoadSDNode>(N); 14204 EVT VT = LD->getValueType(0); 14205 14206 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14207 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14208 if (VT.isSimple()) { 14209 MVT LoadVT = VT.getSimpleVT(); 14210 if (Subtarget.needsSwapsForVSXMemOps() && 14211 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14212 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14213 return expandVSXLoadForLE(N, DCI); 14214 } 14215 14216 // We sometimes end up with a 64-bit integer load, from which we extract 14217 // two single-precision floating-point numbers. This happens with 14218 // std::complex<float>, and other similar structures, because of the way we 14219 // canonicalize structure copies. However, if we lack direct moves, 14220 // then the final bitcasts from the extracted integer values to the 14221 // floating-point numbers turn into store/load pairs. Even with direct moves, 14222 // just loading the two floating-point numbers is likely better. 14223 auto ReplaceTwoFloatLoad = [&]() { 14224 if (VT != MVT::i64) 14225 return false; 14226 14227 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14228 LD->isVolatile()) 14229 return false; 14230 14231 // We're looking for a sequence like this: 14232 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14233 // t16: i64 = srl t13, Constant:i32<32> 14234 // t17: i32 = truncate t16 14235 // t18: f32 = bitcast t17 14236 // t19: i32 = truncate t13 14237 // t20: f32 = bitcast t19 14238 14239 if (!LD->hasNUsesOfValue(2, 0)) 14240 return false; 14241 14242 auto UI = LD->use_begin(); 14243 while (UI.getUse().getResNo() != 0) ++UI; 14244 SDNode *Trunc = *UI++; 14245 while (UI.getUse().getResNo() != 0) ++UI; 14246 SDNode *RightShift = *UI; 14247 if (Trunc->getOpcode() != ISD::TRUNCATE) 14248 std::swap(Trunc, RightShift); 14249 14250 if (Trunc->getOpcode() != ISD::TRUNCATE || 14251 Trunc->getValueType(0) != MVT::i32 || 14252 !Trunc->hasOneUse()) 14253 return false; 14254 if (RightShift->getOpcode() != ISD::SRL || 14255 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14256 RightShift->getConstantOperandVal(1) != 32 || 14257 !RightShift->hasOneUse()) 14258 return false; 14259 14260 SDNode *Trunc2 = *RightShift->use_begin(); 14261 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14262 Trunc2->getValueType(0) != MVT::i32 || 14263 !Trunc2->hasOneUse()) 14264 return false; 14265 14266 SDNode *Bitcast = *Trunc->use_begin(); 14267 SDNode *Bitcast2 = *Trunc2->use_begin(); 14268 14269 if (Bitcast->getOpcode() != ISD::BITCAST || 14270 Bitcast->getValueType(0) != MVT::f32) 14271 return false; 14272 if (Bitcast2->getOpcode() != ISD::BITCAST || 14273 Bitcast2->getValueType(0) != MVT::f32) 14274 return false; 14275 14276 if (Subtarget.isLittleEndian()) 14277 std::swap(Bitcast, Bitcast2); 14278 14279 // Bitcast has the second float (in memory-layout order) and Bitcast2 14280 // has the first one. 14281 14282 SDValue BasePtr = LD->getBasePtr(); 14283 if (LD->isIndexed()) { 14284 assert(LD->getAddressingMode() == ISD::PRE_INC && 14285 "Non-pre-inc AM on PPC?"); 14286 BasePtr = 14287 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14288 LD->getOffset()); 14289 } 14290 14291 auto MMOFlags = 14292 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14293 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14294 LD->getPointerInfo(), LD->getAlignment(), 14295 MMOFlags, LD->getAAInfo()); 14296 SDValue AddPtr = 14297 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14298 BasePtr, DAG.getIntPtrConstant(4, dl)); 14299 SDValue FloatLoad2 = DAG.getLoad( 14300 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14301 LD->getPointerInfo().getWithOffset(4), 14302 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14303 14304 if (LD->isIndexed()) { 14305 // Note that DAGCombine should re-form any pre-increment load(s) from 14306 // what is produced here if that makes sense. 14307 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14308 } 14309 14310 DCI.CombineTo(Bitcast2, FloatLoad); 14311 DCI.CombineTo(Bitcast, FloatLoad2); 14312 14313 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14314 SDValue(FloatLoad2.getNode(), 1)); 14315 return true; 14316 }; 14317 14318 if (ReplaceTwoFloatLoad()) 14319 return SDValue(N, 0); 14320 14321 EVT MemVT = LD->getMemoryVT(); 14322 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14323 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14324 if (LD->isUnindexed() && VT.isVector() && 14325 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14326 // P8 and later hardware should just use LOAD. 14327 !Subtarget.hasP8Vector() && 14328 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14329 VT == MVT::v4f32))) && 14330 LD->getAlign() < ABIAlignment) { 14331 // This is a type-legal unaligned Altivec load. 14332 SDValue Chain = LD->getChain(); 14333 SDValue Ptr = LD->getBasePtr(); 14334 bool isLittleEndian = Subtarget.isLittleEndian(); 14335 14336 // This implements the loading of unaligned vectors as described in 14337 // the venerable Apple Velocity Engine overview. Specifically: 14338 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14339 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14340 // 14341 // The general idea is to expand a sequence of one or more unaligned 14342 // loads into an alignment-based permutation-control instruction (lvsl 14343 // or lvsr), a series of regular vector loads (which always truncate 14344 // their input address to an aligned address), and a series of 14345 // permutations. The results of these permutations are the requested 14346 // loaded values. The trick is that the last "extra" load is not taken 14347 // from the address you might suspect (sizeof(vector) bytes after the 14348 // last requested load), but rather sizeof(vector) - 1 bytes after the 14349 // last requested vector. The point of this is to avoid a page fault if 14350 // the base address happened to be aligned. This works because if the 14351 // base address is aligned, then adding less than a full vector length 14352 // will cause the last vector in the sequence to be (re)loaded. 14353 // Otherwise, the next vector will be fetched as you might suspect was 14354 // necessary. 14355 14356 // We might be able to reuse the permutation generation from 14357 // a different base address offset from this one by an aligned amount. 14358 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14359 // optimization later. 14360 Intrinsic::ID Intr, IntrLD, IntrPerm; 14361 MVT PermCntlTy, PermTy, LDTy; 14362 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14363 : Intrinsic::ppc_altivec_lvsl; 14364 IntrLD = Intrinsic::ppc_altivec_lvx; 14365 IntrPerm = Intrinsic::ppc_altivec_vperm; 14366 PermCntlTy = MVT::v16i8; 14367 PermTy = MVT::v4i32; 14368 LDTy = MVT::v4i32; 14369 14370 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14371 14372 // Create the new MMO for the new base load. It is like the original MMO, 14373 // but represents an area in memory almost twice the vector size centered 14374 // on the original address. If the address is unaligned, we might start 14375 // reading up to (sizeof(vector)-1) bytes below the address of the 14376 // original unaligned load. 14377 MachineFunction &MF = DAG.getMachineFunction(); 14378 MachineMemOperand *BaseMMO = 14379 MF.getMachineMemOperand(LD->getMemOperand(), 14380 -(long)MemVT.getStoreSize()+1, 14381 2*MemVT.getStoreSize()-1); 14382 14383 // Create the new base load. 14384 SDValue LDXIntID = 14385 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14386 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14387 SDValue BaseLoad = 14388 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14389 DAG.getVTList(PermTy, MVT::Other), 14390 BaseLoadOps, LDTy, BaseMMO); 14391 14392 // Note that the value of IncOffset (which is provided to the next 14393 // load's pointer info offset value, and thus used to calculate the 14394 // alignment), and the value of IncValue (which is actually used to 14395 // increment the pointer value) are different! This is because we 14396 // require the next load to appear to be aligned, even though it 14397 // is actually offset from the base pointer by a lesser amount. 14398 int IncOffset = VT.getSizeInBits() / 8; 14399 int IncValue = IncOffset; 14400 14401 // Walk (both up and down) the chain looking for another load at the real 14402 // (aligned) offset (the alignment of the other load does not matter in 14403 // this case). If found, then do not use the offset reduction trick, as 14404 // that will prevent the loads from being later combined (as they would 14405 // otherwise be duplicates). 14406 if (!findConsecutiveLoad(LD, DAG)) 14407 --IncValue; 14408 14409 SDValue Increment = 14410 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14411 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14412 14413 MachineMemOperand *ExtraMMO = 14414 MF.getMachineMemOperand(LD->getMemOperand(), 14415 1, 2*MemVT.getStoreSize()-1); 14416 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14417 SDValue ExtraLoad = 14418 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14419 DAG.getVTList(PermTy, MVT::Other), 14420 ExtraLoadOps, LDTy, ExtraMMO); 14421 14422 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14423 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14424 14425 // Because vperm has a big-endian bias, we must reverse the order 14426 // of the input vectors and complement the permute control vector 14427 // when generating little endian code. We have already handled the 14428 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14429 // and ExtraLoad here. 14430 SDValue Perm; 14431 if (isLittleEndian) 14432 Perm = BuildIntrinsicOp(IntrPerm, 14433 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14434 else 14435 Perm = BuildIntrinsicOp(IntrPerm, 14436 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14437 14438 if (VT != PermTy) 14439 Perm = Subtarget.hasAltivec() 14440 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14441 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14442 DAG.getTargetConstant(1, dl, MVT::i64)); 14443 // second argument is 1 because this rounding 14444 // is always exact. 14445 14446 // The output of the permutation is our loaded result, the TokenFactor is 14447 // our new chain. 14448 DCI.CombineTo(N, Perm, TF); 14449 return SDValue(N, 0); 14450 } 14451 } 14452 break; 14453 case ISD::INTRINSIC_WO_CHAIN: { 14454 bool isLittleEndian = Subtarget.isLittleEndian(); 14455 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14456 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14457 : Intrinsic::ppc_altivec_lvsl); 14458 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14459 SDValue Add = N->getOperand(1); 14460 14461 int Bits = 4 /* 16 byte alignment */; 14462 14463 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14464 APInt::getAllOnesValue(Bits /* alignment */) 14465 .zext(Add.getScalarValueSizeInBits()))) { 14466 SDNode *BasePtr = Add->getOperand(0).getNode(); 14467 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14468 UE = BasePtr->use_end(); 14469 UI != UE; ++UI) { 14470 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14471 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14472 IID) { 14473 // We've found another LVSL/LVSR, and this address is an aligned 14474 // multiple of that one. The results will be the same, so use the 14475 // one we've just found instead. 14476 14477 return SDValue(*UI, 0); 14478 } 14479 } 14480 } 14481 14482 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14483 SDNode *BasePtr = Add->getOperand(0).getNode(); 14484 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14485 UE = BasePtr->use_end(); UI != UE; ++UI) { 14486 if (UI->getOpcode() == ISD::ADD && 14487 isa<ConstantSDNode>(UI->getOperand(1)) && 14488 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14489 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14490 (1ULL << Bits) == 0) { 14491 SDNode *OtherAdd = *UI; 14492 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14493 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14494 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14495 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14496 return SDValue(*VI, 0); 14497 } 14498 } 14499 } 14500 } 14501 } 14502 } 14503 14504 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14505 // Expose the vabsduw/h/b opportunity for down stream 14506 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14507 (IID == Intrinsic::ppc_altivec_vmaxsw || 14508 IID == Intrinsic::ppc_altivec_vmaxsh || 14509 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14510 SDValue V1 = N->getOperand(1); 14511 SDValue V2 = N->getOperand(2); 14512 if ((V1.getSimpleValueType() == MVT::v4i32 || 14513 V1.getSimpleValueType() == MVT::v8i16 || 14514 V1.getSimpleValueType() == MVT::v16i8) && 14515 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14516 // (0-a, a) 14517 if (V1.getOpcode() == ISD::SUB && 14518 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14519 V1.getOperand(1) == V2) { 14520 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14521 } 14522 // (a, 0-a) 14523 if (V2.getOpcode() == ISD::SUB && 14524 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14525 V2.getOperand(1) == V1) { 14526 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14527 } 14528 // (x-y, y-x) 14529 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14530 V1.getOperand(0) == V2.getOperand(1) && 14531 V1.getOperand(1) == V2.getOperand(0)) { 14532 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14533 } 14534 } 14535 } 14536 } 14537 14538 break; 14539 case ISD::INTRINSIC_W_CHAIN: 14540 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14541 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14542 if (Subtarget.needsSwapsForVSXMemOps()) { 14543 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14544 default: 14545 break; 14546 case Intrinsic::ppc_vsx_lxvw4x: 14547 case Intrinsic::ppc_vsx_lxvd2x: 14548 return expandVSXLoadForLE(N, DCI); 14549 } 14550 } 14551 break; 14552 case ISD::INTRINSIC_VOID: 14553 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14554 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14555 if (Subtarget.needsSwapsForVSXMemOps()) { 14556 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14557 default: 14558 break; 14559 case Intrinsic::ppc_vsx_stxvw4x: 14560 case Intrinsic::ppc_vsx_stxvd2x: 14561 return expandVSXStoreForLE(N, DCI); 14562 } 14563 } 14564 break; 14565 case ISD::BSWAP: 14566 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14567 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14568 N->getOperand(0).hasOneUse() && 14569 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14570 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14571 N->getValueType(0) == MVT::i64))) { 14572 SDValue Load = N->getOperand(0); 14573 LoadSDNode *LD = cast<LoadSDNode>(Load); 14574 // Create the byte-swapping load. 14575 SDValue Ops[] = { 14576 LD->getChain(), // Chain 14577 LD->getBasePtr(), // Ptr 14578 DAG.getValueType(N->getValueType(0)) // VT 14579 }; 14580 SDValue BSLoad = 14581 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14582 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14583 MVT::i64 : MVT::i32, MVT::Other), 14584 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14585 14586 // If this is an i16 load, insert the truncate. 14587 SDValue ResVal = BSLoad; 14588 if (N->getValueType(0) == MVT::i16) 14589 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14590 14591 // First, combine the bswap away. This makes the value produced by the 14592 // load dead. 14593 DCI.CombineTo(N, ResVal); 14594 14595 // Next, combine the load away, we give it a bogus result value but a real 14596 // chain result. The result value is dead because the bswap is dead. 14597 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14598 14599 // Return N so it doesn't get rechecked! 14600 return SDValue(N, 0); 14601 } 14602 break; 14603 case PPCISD::VCMP: 14604 // If a VCMPo node already exists with exactly the same operands as this 14605 // node, use its result instead of this node (VCMPo computes both a CR6 and 14606 // a normal output). 14607 // 14608 if (!N->getOperand(0).hasOneUse() && 14609 !N->getOperand(1).hasOneUse() && 14610 !N->getOperand(2).hasOneUse()) { 14611 14612 // Scan all of the users of the LHS, looking for VCMPo's that match. 14613 SDNode *VCMPoNode = nullptr; 14614 14615 SDNode *LHSN = N->getOperand(0).getNode(); 14616 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14617 UI != E; ++UI) 14618 if (UI->getOpcode() == PPCISD::VCMPo && 14619 UI->getOperand(1) == N->getOperand(1) && 14620 UI->getOperand(2) == N->getOperand(2) && 14621 UI->getOperand(0) == N->getOperand(0)) { 14622 VCMPoNode = *UI; 14623 break; 14624 } 14625 14626 // If there is no VCMPo node, or if the flag value has a single use, don't 14627 // transform this. 14628 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14629 break; 14630 14631 // Look at the (necessarily single) use of the flag value. If it has a 14632 // chain, this transformation is more complex. Note that multiple things 14633 // could use the value result, which we should ignore. 14634 SDNode *FlagUser = nullptr; 14635 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14636 FlagUser == nullptr; ++UI) { 14637 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14638 SDNode *User = *UI; 14639 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14640 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14641 FlagUser = User; 14642 break; 14643 } 14644 } 14645 } 14646 14647 // If the user is a MFOCRF instruction, we know this is safe. 14648 // Otherwise we give up for right now. 14649 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14650 return SDValue(VCMPoNode, 0); 14651 } 14652 break; 14653 case ISD::BRCOND: { 14654 SDValue Cond = N->getOperand(1); 14655 SDValue Target = N->getOperand(2); 14656 14657 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14658 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14659 Intrinsic::loop_decrement) { 14660 14661 // We now need to make the intrinsic dead (it cannot be instruction 14662 // selected). 14663 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14664 assert(Cond.getNode()->hasOneUse() && 14665 "Counter decrement has more than one use"); 14666 14667 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14668 N->getOperand(0), Target); 14669 } 14670 } 14671 break; 14672 case ISD::BR_CC: { 14673 // If this is a branch on an altivec predicate comparison, lower this so 14674 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14675 // lowering is done pre-legalize, because the legalizer lowers the predicate 14676 // compare down to code that is difficult to reassemble. 14677 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14678 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14679 14680 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14681 // value. If so, pass-through the AND to get to the intrinsic. 14682 if (LHS.getOpcode() == ISD::AND && 14683 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14684 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14685 Intrinsic::loop_decrement && 14686 isa<ConstantSDNode>(LHS.getOperand(1)) && 14687 !isNullConstant(LHS.getOperand(1))) 14688 LHS = LHS.getOperand(0); 14689 14690 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14691 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14692 Intrinsic::loop_decrement && 14693 isa<ConstantSDNode>(RHS)) { 14694 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14695 "Counter decrement comparison is not EQ or NE"); 14696 14697 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14698 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14699 (CC == ISD::SETNE && !Val); 14700 14701 // We now need to make the intrinsic dead (it cannot be instruction 14702 // selected). 14703 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14704 assert(LHS.getNode()->hasOneUse() && 14705 "Counter decrement has more than one use"); 14706 14707 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14708 N->getOperand(0), N->getOperand(4)); 14709 } 14710 14711 int CompareOpc; 14712 bool isDot; 14713 14714 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14715 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14716 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14717 assert(isDot && "Can't compare against a vector result!"); 14718 14719 // If this is a comparison against something other than 0/1, then we know 14720 // that the condition is never/always true. 14721 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14722 if (Val != 0 && Val != 1) { 14723 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14724 return N->getOperand(0); 14725 // Always !=, turn it into an unconditional branch. 14726 return DAG.getNode(ISD::BR, dl, MVT::Other, 14727 N->getOperand(0), N->getOperand(4)); 14728 } 14729 14730 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14731 14732 // Create the PPCISD altivec 'dot' comparison node. 14733 SDValue Ops[] = { 14734 LHS.getOperand(2), // LHS of compare 14735 LHS.getOperand(3), // RHS of compare 14736 DAG.getConstant(CompareOpc, dl, MVT::i32) 14737 }; 14738 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14739 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14740 14741 // Unpack the result based on how the target uses it. 14742 PPC::Predicate CompOpc; 14743 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14744 default: // Can't happen, don't crash on invalid number though. 14745 case 0: // Branch on the value of the EQ bit of CR6. 14746 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14747 break; 14748 case 1: // Branch on the inverted value of the EQ bit of CR6. 14749 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14750 break; 14751 case 2: // Branch on the value of the LT bit of CR6. 14752 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14753 break; 14754 case 3: // Branch on the inverted value of the LT bit of CR6. 14755 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14756 break; 14757 } 14758 14759 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14760 DAG.getConstant(CompOpc, dl, MVT::i32), 14761 DAG.getRegister(PPC::CR6, MVT::i32), 14762 N->getOperand(4), CompNode.getValue(1)); 14763 } 14764 break; 14765 } 14766 case ISD::BUILD_VECTOR: 14767 return DAGCombineBuildVector(N, DCI); 14768 case ISD::ABS: 14769 return combineABS(N, DCI); 14770 case ISD::VSELECT: 14771 return combineVSelect(N, DCI); 14772 } 14773 14774 return SDValue(); 14775 } 14776 14777 SDValue 14778 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14779 SelectionDAG &DAG, 14780 SmallVectorImpl<SDNode *> &Created) const { 14781 // fold (sdiv X, pow2) 14782 EVT VT = N->getValueType(0); 14783 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14784 return SDValue(); 14785 if ((VT != MVT::i32 && VT != MVT::i64) || 14786 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14787 return SDValue(); 14788 14789 SDLoc DL(N); 14790 SDValue N0 = N->getOperand(0); 14791 14792 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14793 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14794 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14795 14796 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14797 Created.push_back(Op.getNode()); 14798 14799 if (IsNegPow2) { 14800 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14801 Created.push_back(Op.getNode()); 14802 } 14803 14804 return Op; 14805 } 14806 14807 //===----------------------------------------------------------------------===// 14808 // Inline Assembly Support 14809 //===----------------------------------------------------------------------===// 14810 14811 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14812 KnownBits &Known, 14813 const APInt &DemandedElts, 14814 const SelectionDAG &DAG, 14815 unsigned Depth) const { 14816 Known.resetAll(); 14817 switch (Op.getOpcode()) { 14818 default: break; 14819 case PPCISD::LBRX: { 14820 // lhbrx is known to have the top bits cleared out. 14821 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14822 Known.Zero = 0xFFFF0000; 14823 break; 14824 } 14825 case ISD::INTRINSIC_WO_CHAIN: { 14826 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14827 default: break; 14828 case Intrinsic::ppc_altivec_vcmpbfp_p: 14829 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14830 case Intrinsic::ppc_altivec_vcmpequb_p: 14831 case Intrinsic::ppc_altivec_vcmpequh_p: 14832 case Intrinsic::ppc_altivec_vcmpequw_p: 14833 case Intrinsic::ppc_altivec_vcmpequd_p: 14834 case Intrinsic::ppc_altivec_vcmpgefp_p: 14835 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14836 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14837 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14838 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14839 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14840 case Intrinsic::ppc_altivec_vcmpgtub_p: 14841 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14842 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14843 case Intrinsic::ppc_altivec_vcmpgtud_p: 14844 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14845 break; 14846 } 14847 } 14848 } 14849 } 14850 14851 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14852 switch (Subtarget.getCPUDirective()) { 14853 default: break; 14854 case PPC::DIR_970: 14855 case PPC::DIR_PWR4: 14856 case PPC::DIR_PWR5: 14857 case PPC::DIR_PWR5X: 14858 case PPC::DIR_PWR6: 14859 case PPC::DIR_PWR6X: 14860 case PPC::DIR_PWR7: 14861 case PPC::DIR_PWR8: 14862 case PPC::DIR_PWR9: 14863 case PPC::DIR_PWR10: 14864 case PPC::DIR_PWR_FUTURE: { 14865 if (!ML) 14866 break; 14867 14868 if (!DisableInnermostLoopAlign32) { 14869 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14870 // so that we can decrease cache misses and branch-prediction misses. 14871 // Actual alignment of the loop will depend on the hotness check and other 14872 // logic in alignBlocks. 14873 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14874 return Align(32); 14875 } 14876 14877 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14878 14879 // For small loops (between 5 and 8 instructions), align to a 32-byte 14880 // boundary so that the entire loop fits in one instruction-cache line. 14881 uint64_t LoopSize = 0; 14882 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14883 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14884 LoopSize += TII->getInstSizeInBytes(*J); 14885 if (LoopSize > 32) 14886 break; 14887 } 14888 14889 if (LoopSize > 16 && LoopSize <= 32) 14890 return Align(32); 14891 14892 break; 14893 } 14894 } 14895 14896 return TargetLowering::getPrefLoopAlignment(ML); 14897 } 14898 14899 /// getConstraintType - Given a constraint, return the type of 14900 /// constraint it is for this target. 14901 PPCTargetLowering::ConstraintType 14902 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14903 if (Constraint.size() == 1) { 14904 switch (Constraint[0]) { 14905 default: break; 14906 case 'b': 14907 case 'r': 14908 case 'f': 14909 case 'd': 14910 case 'v': 14911 case 'y': 14912 return C_RegisterClass; 14913 case 'Z': 14914 // FIXME: While Z does indicate a memory constraint, it specifically 14915 // indicates an r+r address (used in conjunction with the 'y' modifier 14916 // in the replacement string). Currently, we're forcing the base 14917 // register to be r0 in the asm printer (which is interpreted as zero) 14918 // and forming the complete address in the second register. This is 14919 // suboptimal. 14920 return C_Memory; 14921 } 14922 } else if (Constraint == "wc") { // individual CR bits. 14923 return C_RegisterClass; 14924 } else if (Constraint == "wa" || Constraint == "wd" || 14925 Constraint == "wf" || Constraint == "ws" || 14926 Constraint == "wi" || Constraint == "ww") { 14927 return C_RegisterClass; // VSX registers. 14928 } 14929 return TargetLowering::getConstraintType(Constraint); 14930 } 14931 14932 /// Examine constraint type and operand type and determine a weight value. 14933 /// This object must already have been set up with the operand type 14934 /// and the current alternative constraint selected. 14935 TargetLowering::ConstraintWeight 14936 PPCTargetLowering::getSingleConstraintMatchWeight( 14937 AsmOperandInfo &info, const char *constraint) const { 14938 ConstraintWeight weight = CW_Invalid; 14939 Value *CallOperandVal = info.CallOperandVal; 14940 // If we don't have a value, we can't do a match, 14941 // but allow it at the lowest weight. 14942 if (!CallOperandVal) 14943 return CW_Default; 14944 Type *type = CallOperandVal->getType(); 14945 14946 // Look at the constraint type. 14947 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14948 return CW_Register; // an individual CR bit. 14949 else if ((StringRef(constraint) == "wa" || 14950 StringRef(constraint) == "wd" || 14951 StringRef(constraint) == "wf") && 14952 type->isVectorTy()) 14953 return CW_Register; 14954 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14955 return CW_Register; // just hold 64-bit integers data. 14956 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14957 return CW_Register; 14958 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14959 return CW_Register; 14960 14961 switch (*constraint) { 14962 default: 14963 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14964 break; 14965 case 'b': 14966 if (type->isIntegerTy()) 14967 weight = CW_Register; 14968 break; 14969 case 'f': 14970 if (type->isFloatTy()) 14971 weight = CW_Register; 14972 break; 14973 case 'd': 14974 if (type->isDoubleTy()) 14975 weight = CW_Register; 14976 break; 14977 case 'v': 14978 if (type->isVectorTy()) 14979 weight = CW_Register; 14980 break; 14981 case 'y': 14982 weight = CW_Register; 14983 break; 14984 case 'Z': 14985 weight = CW_Memory; 14986 break; 14987 } 14988 return weight; 14989 } 14990 14991 std::pair<unsigned, const TargetRegisterClass *> 14992 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14993 StringRef Constraint, 14994 MVT VT) const { 14995 if (Constraint.size() == 1) { 14996 // GCC RS6000 Constraint Letters 14997 switch (Constraint[0]) { 14998 case 'b': // R1-R31 14999 if (VT == MVT::i64 && Subtarget.isPPC64()) 15000 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15001 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15002 case 'r': // R0-R31 15003 if (VT == MVT::i64 && Subtarget.isPPC64()) 15004 return std::make_pair(0U, &PPC::G8RCRegClass); 15005 return std::make_pair(0U, &PPC::GPRCRegClass); 15006 // 'd' and 'f' constraints are both defined to be "the floating point 15007 // registers", where one is for 32-bit and the other for 64-bit. We don't 15008 // really care overly much here so just give them all the same reg classes. 15009 case 'd': 15010 case 'f': 15011 if (Subtarget.hasSPE()) { 15012 if (VT == MVT::f32 || VT == MVT::i32) 15013 return std::make_pair(0U, &PPC::GPRCRegClass); 15014 if (VT == MVT::f64 || VT == MVT::i64) 15015 return std::make_pair(0U, &PPC::SPERCRegClass); 15016 } else { 15017 if (VT == MVT::f32 || VT == MVT::i32) 15018 return std::make_pair(0U, &PPC::F4RCRegClass); 15019 if (VT == MVT::f64 || VT == MVT::i64) 15020 return std::make_pair(0U, &PPC::F8RCRegClass); 15021 } 15022 break; 15023 case 'v': 15024 if (Subtarget.hasAltivec()) 15025 return std::make_pair(0U, &PPC::VRRCRegClass); 15026 break; 15027 case 'y': // crrc 15028 return std::make_pair(0U, &PPC::CRRCRegClass); 15029 } 15030 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15031 // An individual CR bit. 15032 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15033 } else if ((Constraint == "wa" || Constraint == "wd" || 15034 Constraint == "wf" || Constraint == "wi") && 15035 Subtarget.hasVSX()) { 15036 return std::make_pair(0U, &PPC::VSRCRegClass); 15037 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15038 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15039 return std::make_pair(0U, &PPC::VSSRCRegClass); 15040 else 15041 return std::make_pair(0U, &PPC::VSFRCRegClass); 15042 } 15043 15044 // If we name a VSX register, we can't defer to the base class because it 15045 // will not recognize the correct register (their names will be VSL{0-31} 15046 // and V{0-31} so they won't match). So we match them here. 15047 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15048 int VSNum = atoi(Constraint.data() + 3); 15049 assert(VSNum >= 0 && VSNum <= 63 && 15050 "Attempted to access a vsr out of range"); 15051 if (VSNum < 32) 15052 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15053 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15054 } 15055 std::pair<unsigned, const TargetRegisterClass *> R = 15056 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15057 15058 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15059 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15060 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15061 // register. 15062 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15063 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15064 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15065 PPC::GPRCRegClass.contains(R.first)) 15066 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15067 PPC::sub_32, &PPC::G8RCRegClass), 15068 &PPC::G8RCRegClass); 15069 15070 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15071 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15072 R.first = PPC::CR0; 15073 R.second = &PPC::CRRCRegClass; 15074 } 15075 15076 return R; 15077 } 15078 15079 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15080 /// vector. If it is invalid, don't add anything to Ops. 15081 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15082 std::string &Constraint, 15083 std::vector<SDValue>&Ops, 15084 SelectionDAG &DAG) const { 15085 SDValue Result; 15086 15087 // Only support length 1 constraints. 15088 if (Constraint.length() > 1) return; 15089 15090 char Letter = Constraint[0]; 15091 switch (Letter) { 15092 default: break; 15093 case 'I': 15094 case 'J': 15095 case 'K': 15096 case 'L': 15097 case 'M': 15098 case 'N': 15099 case 'O': 15100 case 'P': { 15101 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15102 if (!CST) return; // Must be an immediate to match. 15103 SDLoc dl(Op); 15104 int64_t Value = CST->getSExtValue(); 15105 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15106 // numbers are printed as such. 15107 switch (Letter) { 15108 default: llvm_unreachable("Unknown constraint letter!"); 15109 case 'I': // "I" is a signed 16-bit constant. 15110 if (isInt<16>(Value)) 15111 Result = DAG.getTargetConstant(Value, dl, TCVT); 15112 break; 15113 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15114 if (isShiftedUInt<16, 16>(Value)) 15115 Result = DAG.getTargetConstant(Value, dl, TCVT); 15116 break; 15117 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15118 if (isShiftedInt<16, 16>(Value)) 15119 Result = DAG.getTargetConstant(Value, dl, TCVT); 15120 break; 15121 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15122 if (isUInt<16>(Value)) 15123 Result = DAG.getTargetConstant(Value, dl, TCVT); 15124 break; 15125 case 'M': // "M" is a constant that is greater than 31. 15126 if (Value > 31) 15127 Result = DAG.getTargetConstant(Value, dl, TCVT); 15128 break; 15129 case 'N': // "N" is a positive constant that is an exact power of two. 15130 if (Value > 0 && isPowerOf2_64(Value)) 15131 Result = DAG.getTargetConstant(Value, dl, TCVT); 15132 break; 15133 case 'O': // "O" is the constant zero. 15134 if (Value == 0) 15135 Result = DAG.getTargetConstant(Value, dl, TCVT); 15136 break; 15137 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15138 if (isInt<16>(-Value)) 15139 Result = DAG.getTargetConstant(Value, dl, TCVT); 15140 break; 15141 } 15142 break; 15143 } 15144 } 15145 15146 if (Result.getNode()) { 15147 Ops.push_back(Result); 15148 return; 15149 } 15150 15151 // Handle standard constraint letters. 15152 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15153 } 15154 15155 // isLegalAddressingMode - Return true if the addressing mode represented 15156 // by AM is legal for this target, for a load/store of the specified type. 15157 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15158 const AddrMode &AM, Type *Ty, 15159 unsigned AS, 15160 Instruction *I) const { 15161 // Vector type r+i form is supported since power9 as DQ form. We don't check 15162 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15163 // imm form is preferred and the offset can be adjusted to use imm form later 15164 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15165 // max offset to check legal addressing mode, we should be a little aggressive 15166 // to contain other offsets for that LSRUse. 15167 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15168 return false; 15169 15170 // PPC allows a sign-extended 16-bit immediate field. 15171 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15172 return false; 15173 15174 // No global is ever allowed as a base. 15175 if (AM.BaseGV) 15176 return false; 15177 15178 // PPC only support r+r, 15179 switch (AM.Scale) { 15180 case 0: // "r+i" or just "i", depending on HasBaseReg. 15181 break; 15182 case 1: 15183 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15184 return false; 15185 // Otherwise we have r+r or r+i. 15186 break; 15187 case 2: 15188 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15189 return false; 15190 // Allow 2*r as r+r. 15191 break; 15192 default: 15193 // No other scales are supported. 15194 return false; 15195 } 15196 15197 return true; 15198 } 15199 15200 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15201 SelectionDAG &DAG) const { 15202 MachineFunction &MF = DAG.getMachineFunction(); 15203 MachineFrameInfo &MFI = MF.getFrameInfo(); 15204 MFI.setReturnAddressIsTaken(true); 15205 15206 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15207 return SDValue(); 15208 15209 SDLoc dl(Op); 15210 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15211 15212 // Make sure the function does not optimize away the store of the RA to 15213 // the stack. 15214 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15215 FuncInfo->setLRStoreRequired(); 15216 bool isPPC64 = Subtarget.isPPC64(); 15217 auto PtrVT = getPointerTy(MF.getDataLayout()); 15218 15219 if (Depth > 0) { 15220 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15221 SDValue Offset = 15222 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15223 isPPC64 ? MVT::i64 : MVT::i32); 15224 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15225 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15226 MachinePointerInfo()); 15227 } 15228 15229 // Just load the return address off the stack. 15230 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15231 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15232 MachinePointerInfo()); 15233 } 15234 15235 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15236 SelectionDAG &DAG) const { 15237 SDLoc dl(Op); 15238 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15239 15240 MachineFunction &MF = DAG.getMachineFunction(); 15241 MachineFrameInfo &MFI = MF.getFrameInfo(); 15242 MFI.setFrameAddressIsTaken(true); 15243 15244 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15245 bool isPPC64 = PtrVT == MVT::i64; 15246 15247 // Naked functions never have a frame pointer, and so we use r1. For all 15248 // other functions, this decision must be delayed until during PEI. 15249 unsigned FrameReg; 15250 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15251 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15252 else 15253 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15254 15255 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15256 PtrVT); 15257 while (Depth--) 15258 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15259 FrameAddr, MachinePointerInfo()); 15260 return FrameAddr; 15261 } 15262 15263 // FIXME? Maybe this could be a TableGen attribute on some registers and 15264 // this table could be generated automatically from RegInfo. 15265 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15266 const MachineFunction &MF) const { 15267 bool isPPC64 = Subtarget.isPPC64(); 15268 15269 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15270 if (!is64Bit && VT != LLT::scalar(32)) 15271 report_fatal_error("Invalid register global variable type"); 15272 15273 Register Reg = StringSwitch<Register>(RegName) 15274 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15275 .Case("r2", isPPC64 ? Register() : PPC::R2) 15276 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15277 .Default(Register()); 15278 15279 if (Reg) 15280 return Reg; 15281 report_fatal_error("Invalid register name global variable"); 15282 } 15283 15284 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15285 // 32-bit SVR4 ABI access everything as got-indirect. 15286 if (Subtarget.is32BitELFABI()) 15287 return true; 15288 15289 // AIX accesses everything indirectly through the TOC, which is similar to 15290 // the GOT. 15291 if (Subtarget.isAIXABI()) 15292 return true; 15293 15294 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15295 // If it is small or large code model, module locals are accessed 15296 // indirectly by loading their address from .toc/.got. 15297 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15298 return true; 15299 15300 // JumpTable and BlockAddress are accessed as got-indirect. 15301 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15302 return true; 15303 15304 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15305 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15306 15307 return false; 15308 } 15309 15310 bool 15311 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15312 // The PowerPC target isn't yet aware of offsets. 15313 return false; 15314 } 15315 15316 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15317 const CallInst &I, 15318 MachineFunction &MF, 15319 unsigned Intrinsic) const { 15320 switch (Intrinsic) { 15321 case Intrinsic::ppc_altivec_lvx: 15322 case Intrinsic::ppc_altivec_lvxl: 15323 case Intrinsic::ppc_altivec_lvebx: 15324 case Intrinsic::ppc_altivec_lvehx: 15325 case Intrinsic::ppc_altivec_lvewx: 15326 case Intrinsic::ppc_vsx_lxvd2x: 15327 case Intrinsic::ppc_vsx_lxvw4x: { 15328 EVT VT; 15329 switch (Intrinsic) { 15330 case Intrinsic::ppc_altivec_lvebx: 15331 VT = MVT::i8; 15332 break; 15333 case Intrinsic::ppc_altivec_lvehx: 15334 VT = MVT::i16; 15335 break; 15336 case Intrinsic::ppc_altivec_lvewx: 15337 VT = MVT::i32; 15338 break; 15339 case Intrinsic::ppc_vsx_lxvd2x: 15340 VT = MVT::v2f64; 15341 break; 15342 default: 15343 VT = MVT::v4i32; 15344 break; 15345 } 15346 15347 Info.opc = ISD::INTRINSIC_W_CHAIN; 15348 Info.memVT = VT; 15349 Info.ptrVal = I.getArgOperand(0); 15350 Info.offset = -VT.getStoreSize()+1; 15351 Info.size = 2*VT.getStoreSize()-1; 15352 Info.align = Align(1); 15353 Info.flags = MachineMemOperand::MOLoad; 15354 return true; 15355 } 15356 case Intrinsic::ppc_altivec_stvx: 15357 case Intrinsic::ppc_altivec_stvxl: 15358 case Intrinsic::ppc_altivec_stvebx: 15359 case Intrinsic::ppc_altivec_stvehx: 15360 case Intrinsic::ppc_altivec_stvewx: 15361 case Intrinsic::ppc_vsx_stxvd2x: 15362 case Intrinsic::ppc_vsx_stxvw4x: { 15363 EVT VT; 15364 switch (Intrinsic) { 15365 case Intrinsic::ppc_altivec_stvebx: 15366 VT = MVT::i8; 15367 break; 15368 case Intrinsic::ppc_altivec_stvehx: 15369 VT = MVT::i16; 15370 break; 15371 case Intrinsic::ppc_altivec_stvewx: 15372 VT = MVT::i32; 15373 break; 15374 case Intrinsic::ppc_vsx_stxvd2x: 15375 VT = MVT::v2f64; 15376 break; 15377 default: 15378 VT = MVT::v4i32; 15379 break; 15380 } 15381 15382 Info.opc = ISD::INTRINSIC_VOID; 15383 Info.memVT = VT; 15384 Info.ptrVal = I.getArgOperand(1); 15385 Info.offset = -VT.getStoreSize()+1; 15386 Info.size = 2*VT.getStoreSize()-1; 15387 Info.align = Align(1); 15388 Info.flags = MachineMemOperand::MOStore; 15389 return true; 15390 } 15391 default: 15392 break; 15393 } 15394 15395 return false; 15396 } 15397 15398 /// It returns EVT::Other if the type should be determined using generic 15399 /// target-independent logic. 15400 EVT PPCTargetLowering::getOptimalMemOpType( 15401 const MemOp &Op, const AttributeList &FuncAttributes) const { 15402 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15403 // We should use Altivec/VSX loads and stores when available. For unaligned 15404 // addresses, unaligned VSX loads are only fast starting with the P8. 15405 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15406 (Op.isAligned(Align(16)) || 15407 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15408 return MVT::v4i32; 15409 } 15410 15411 if (Subtarget.isPPC64()) { 15412 return MVT::i64; 15413 } 15414 15415 return MVT::i32; 15416 } 15417 15418 /// Returns true if it is beneficial to convert a load of a constant 15419 /// to just the constant itself. 15420 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15421 Type *Ty) const { 15422 assert(Ty->isIntegerTy()); 15423 15424 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15425 return !(BitSize == 0 || BitSize > 64); 15426 } 15427 15428 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15429 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15430 return false; 15431 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15432 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15433 return NumBits1 == 64 && NumBits2 == 32; 15434 } 15435 15436 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15437 if (!VT1.isInteger() || !VT2.isInteger()) 15438 return false; 15439 unsigned NumBits1 = VT1.getSizeInBits(); 15440 unsigned NumBits2 = VT2.getSizeInBits(); 15441 return NumBits1 == 64 && NumBits2 == 32; 15442 } 15443 15444 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15445 // Generally speaking, zexts are not free, but they are free when they can be 15446 // folded with other operations. 15447 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15448 EVT MemVT = LD->getMemoryVT(); 15449 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15450 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15451 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15452 LD->getExtensionType() == ISD::ZEXTLOAD)) 15453 return true; 15454 } 15455 15456 // FIXME: Add other cases... 15457 // - 32-bit shifts with a zext to i64 15458 // - zext after ctlz, bswap, etc. 15459 // - zext after and by a constant mask 15460 15461 return TargetLowering::isZExtFree(Val, VT2); 15462 } 15463 15464 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15465 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15466 "invalid fpext types"); 15467 // Extending to float128 is not free. 15468 if (DestVT == MVT::f128) 15469 return false; 15470 return true; 15471 } 15472 15473 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15474 return isInt<16>(Imm) || isUInt<16>(Imm); 15475 } 15476 15477 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15478 return isInt<16>(Imm) || isUInt<16>(Imm); 15479 } 15480 15481 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15482 unsigned, 15483 unsigned, 15484 MachineMemOperand::Flags, 15485 bool *Fast) const { 15486 if (DisablePPCUnaligned) 15487 return false; 15488 15489 // PowerPC supports unaligned memory access for simple non-vector types. 15490 // Although accessing unaligned addresses is not as efficient as accessing 15491 // aligned addresses, it is generally more efficient than manual expansion, 15492 // and generally only traps for software emulation when crossing page 15493 // boundaries. 15494 15495 if (!VT.isSimple()) 15496 return false; 15497 15498 if (VT.isFloatingPoint() && !VT.isVector() && 15499 !Subtarget.allowsUnalignedFPAccess()) 15500 return false; 15501 15502 if (VT.getSimpleVT().isVector()) { 15503 if (Subtarget.hasVSX()) { 15504 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15505 VT != MVT::v4f32 && VT != MVT::v4i32) 15506 return false; 15507 } else { 15508 return false; 15509 } 15510 } 15511 15512 if (VT == MVT::ppcf128) 15513 return false; 15514 15515 if (Fast) 15516 *Fast = true; 15517 15518 return true; 15519 } 15520 15521 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15522 EVT VT) const { 15523 return isFMAFasterThanFMulAndFAdd( 15524 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15525 } 15526 15527 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15528 Type *Ty) const { 15529 switch (Ty->getScalarType()->getTypeID()) { 15530 case Type::FloatTyID: 15531 case Type::DoubleTyID: 15532 return true; 15533 case Type::FP128TyID: 15534 return Subtarget.hasP9Vector(); 15535 default: 15536 return false; 15537 } 15538 } 15539 15540 // FIXME: add more patterns which are not profitable to hoist. 15541 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15542 if (!I->hasOneUse()) 15543 return true; 15544 15545 Instruction *User = I->user_back(); 15546 assert(User && "A single use instruction with no uses."); 15547 15548 switch (I->getOpcode()) { 15549 case Instruction::FMul: { 15550 // Don't break FMA, PowerPC prefers FMA. 15551 if (User->getOpcode() != Instruction::FSub && 15552 User->getOpcode() != Instruction::FAdd) 15553 return true; 15554 15555 const TargetOptions &Options = getTargetMachine().Options; 15556 const Function *F = I->getFunction(); 15557 const DataLayout &DL = F->getParent()->getDataLayout(); 15558 Type *Ty = User->getOperand(0)->getType(); 15559 15560 return !( 15561 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15562 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15563 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15564 } 15565 case Instruction::Load: { 15566 // Don't break "store (load float*)" pattern, this pattern will be combined 15567 // to "store (load int32)" in later InstCombine pass. See function 15568 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15569 // cycles than loading a 32 bit integer. 15570 LoadInst *LI = cast<LoadInst>(I); 15571 // For the loads that combineLoadToOperationType does nothing, like 15572 // ordered load, it should be profitable to hoist them. 15573 // For swifterror load, it can only be used for pointer to pointer type, so 15574 // later type check should get rid of this case. 15575 if (!LI->isUnordered()) 15576 return true; 15577 15578 if (User->getOpcode() != Instruction::Store) 15579 return true; 15580 15581 if (I->getType()->getTypeID() != Type::FloatTyID) 15582 return true; 15583 15584 return false; 15585 } 15586 default: 15587 return true; 15588 } 15589 return true; 15590 } 15591 15592 const MCPhysReg * 15593 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15594 // LR is a callee-save register, but we must treat it as clobbered by any call 15595 // site. Hence we include LR in the scratch registers, which are in turn added 15596 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15597 // to CTR, which is used by any indirect call. 15598 static const MCPhysReg ScratchRegs[] = { 15599 PPC::X12, PPC::LR8, PPC::CTR8, 0 15600 }; 15601 15602 return ScratchRegs; 15603 } 15604 15605 Register PPCTargetLowering::getExceptionPointerRegister( 15606 const Constant *PersonalityFn) const { 15607 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15608 } 15609 15610 Register PPCTargetLowering::getExceptionSelectorRegister( 15611 const Constant *PersonalityFn) const { 15612 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15613 } 15614 15615 bool 15616 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15617 EVT VT , unsigned DefinedValues) const { 15618 if (VT == MVT::v2i64) 15619 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15620 15621 if (Subtarget.hasVSX()) 15622 return true; 15623 15624 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15625 } 15626 15627 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15628 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15629 return TargetLowering::getSchedulingPreference(N); 15630 15631 return Sched::ILP; 15632 } 15633 15634 // Create a fast isel object. 15635 FastISel * 15636 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15637 const TargetLibraryInfo *LibInfo) const { 15638 return PPC::createFastISel(FuncInfo, LibInfo); 15639 } 15640 15641 // 'Inverted' means the FMA opcode after negating one multiplicand. 15642 // For example, (fma -a b c) = (fnmsub a b c) 15643 static unsigned invertFMAOpcode(unsigned Opc) { 15644 switch (Opc) { 15645 default: 15646 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15647 case ISD::FMA: 15648 return PPCISD::FNMSUB; 15649 case PPCISD::FNMSUB: 15650 return ISD::FMA; 15651 } 15652 } 15653 15654 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15655 bool LegalOps, bool OptForSize, 15656 NegatibleCost &Cost, 15657 unsigned Depth) const { 15658 if (Depth > SelectionDAG::MaxRecursionDepth) 15659 return SDValue(); 15660 15661 unsigned Opc = Op.getOpcode(); 15662 EVT VT = Op.getValueType(); 15663 SDNodeFlags Flags = Op.getNode()->getFlags(); 15664 15665 switch (Opc) { 15666 case PPCISD::FNMSUB: 15667 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15668 break; 15669 15670 const TargetOptions &Options = getTargetMachine().Options; 15671 SDValue N0 = Op.getOperand(0); 15672 SDValue N1 = Op.getOperand(1); 15673 SDValue N2 = Op.getOperand(2); 15674 SDLoc Loc(Op); 15675 15676 NegatibleCost N2Cost = NegatibleCost::Expensive; 15677 SDValue NegN2 = 15678 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15679 15680 if (!NegN2) 15681 return SDValue(); 15682 15683 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 15684 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 15685 // These transformations may change sign of zeroes. For example, 15686 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 15687 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 15688 // Try and choose the cheaper one to negate. 15689 NegatibleCost N0Cost = NegatibleCost::Expensive; 15690 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 15691 N0Cost, Depth + 1); 15692 15693 NegatibleCost N1Cost = NegatibleCost::Expensive; 15694 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 15695 N1Cost, Depth + 1); 15696 15697 if (NegN0 && N0Cost <= N1Cost) { 15698 Cost = std::min(N0Cost, N2Cost); 15699 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 15700 } else if (NegN1) { 15701 Cost = std::min(N1Cost, N2Cost); 15702 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 15703 } 15704 } 15705 15706 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 15707 if (isOperationLegal(ISD::FMA, VT)) { 15708 Cost = N2Cost; 15709 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 15710 } 15711 15712 break; 15713 } 15714 15715 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 15716 Cost, Depth); 15717 } 15718 15719 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15720 bool PPCTargetLowering::useLoadStackGuardNode() const { 15721 if (!Subtarget.isTargetLinux()) 15722 return TargetLowering::useLoadStackGuardNode(); 15723 return true; 15724 } 15725 15726 // Override to disable global variable loading on Linux. 15727 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15728 if (!Subtarget.isTargetLinux()) 15729 return TargetLowering::insertSSPDeclarations(M); 15730 } 15731 15732 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15733 bool ForCodeSize) const { 15734 if (!VT.isSimple() || !Subtarget.hasVSX()) 15735 return false; 15736 15737 switch(VT.getSimpleVT().SimpleTy) { 15738 default: 15739 // For FP types that are currently not supported by PPC backend, return 15740 // false. Examples: f16, f80. 15741 return false; 15742 case MVT::f32: 15743 case MVT::f64: 15744 if (Subtarget.hasPrefixInstrs()) { 15745 // With prefixed instructions, we can materialize anything that can be 15746 // represented with a 32-bit immediate, not just positive zero. 15747 APFloat APFloatOfImm = Imm; 15748 return convertToNonDenormSingle(APFloatOfImm); 15749 } 15750 LLVM_FALLTHROUGH; 15751 case MVT::ppcf128: 15752 return Imm.isPosZero(); 15753 } 15754 } 15755 15756 // For vector shift operation op, fold 15757 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15758 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15759 SelectionDAG &DAG) { 15760 SDValue N0 = N->getOperand(0); 15761 SDValue N1 = N->getOperand(1); 15762 EVT VT = N0.getValueType(); 15763 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15764 unsigned Opcode = N->getOpcode(); 15765 unsigned TargetOpcode; 15766 15767 switch (Opcode) { 15768 default: 15769 llvm_unreachable("Unexpected shift operation"); 15770 case ISD::SHL: 15771 TargetOpcode = PPCISD::SHL; 15772 break; 15773 case ISD::SRL: 15774 TargetOpcode = PPCISD::SRL; 15775 break; 15776 case ISD::SRA: 15777 TargetOpcode = PPCISD::SRA; 15778 break; 15779 } 15780 15781 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15782 N1->getOpcode() == ISD::AND) 15783 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15784 if (Mask->getZExtValue() == OpSizeInBits - 1) 15785 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15786 15787 return SDValue(); 15788 } 15789 15790 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15791 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15792 return Value; 15793 15794 SDValue N0 = N->getOperand(0); 15795 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15796 if (!Subtarget.isISA3_0() || 15797 N0.getOpcode() != ISD::SIGN_EXTEND || 15798 N0.getOperand(0).getValueType() != MVT::i32 || 15799 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15800 return SDValue(); 15801 15802 // We can't save an operation here if the value is already extended, and 15803 // the existing shift is easier to combine. 15804 SDValue ExtsSrc = N0.getOperand(0); 15805 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15806 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15807 return SDValue(); 15808 15809 SDLoc DL(N0); 15810 SDValue ShiftBy = SDValue(CN1, 0); 15811 // We want the shift amount to be i32 on the extswli, but the shift could 15812 // have an i64. 15813 if (ShiftBy.getValueType() == MVT::i64) 15814 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15815 15816 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15817 ShiftBy); 15818 } 15819 15820 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15821 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15822 return Value; 15823 15824 return SDValue(); 15825 } 15826 15827 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15828 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15829 return Value; 15830 15831 return SDValue(); 15832 } 15833 15834 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15835 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15836 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15837 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15838 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15839 const PPCSubtarget &Subtarget) { 15840 if (!Subtarget.isPPC64()) 15841 return SDValue(); 15842 15843 SDValue LHS = N->getOperand(0); 15844 SDValue RHS = N->getOperand(1); 15845 15846 auto isZextOfCompareWithConstant = [](SDValue Op) { 15847 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15848 Op.getValueType() != MVT::i64) 15849 return false; 15850 15851 SDValue Cmp = Op.getOperand(0); 15852 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15853 Cmp.getOperand(0).getValueType() != MVT::i64) 15854 return false; 15855 15856 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15857 int64_t NegConstant = 0 - Constant->getSExtValue(); 15858 // Due to the limitations of the addi instruction, 15859 // -C is required to be [-32768, 32767]. 15860 return isInt<16>(NegConstant); 15861 } 15862 15863 return false; 15864 }; 15865 15866 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15867 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15868 15869 // If there is a pattern, canonicalize a zext operand to the RHS. 15870 if (LHSHasPattern && !RHSHasPattern) 15871 std::swap(LHS, RHS); 15872 else if (!LHSHasPattern && !RHSHasPattern) 15873 return SDValue(); 15874 15875 SDLoc DL(N); 15876 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15877 SDValue Cmp = RHS.getOperand(0); 15878 SDValue Z = Cmp.getOperand(0); 15879 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15880 15881 assert(Constant && "Constant Should not be a null pointer."); 15882 int64_t NegConstant = 0 - Constant->getSExtValue(); 15883 15884 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15885 default: break; 15886 case ISD::SETNE: { 15887 // when C == 0 15888 // --> addze X, (addic Z, -1).carry 15889 // / 15890 // add X, (zext(setne Z, C))-- 15891 // \ when -32768 <= -C <= 32767 && C != 0 15892 // --> addze X, (addic (addi Z, -C), -1).carry 15893 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15894 DAG.getConstant(NegConstant, DL, MVT::i64)); 15895 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15896 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15897 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15898 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15899 SDValue(Addc.getNode(), 1)); 15900 } 15901 case ISD::SETEQ: { 15902 // when C == 0 15903 // --> addze X, (subfic Z, 0).carry 15904 // / 15905 // add X, (zext(sete Z, C))-- 15906 // \ when -32768 <= -C <= 32767 && C != 0 15907 // --> addze X, (subfic (addi Z, -C), 0).carry 15908 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15909 DAG.getConstant(NegConstant, DL, MVT::i64)); 15910 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15911 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15912 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15913 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15914 SDValue(Subc.getNode(), 1)); 15915 } 15916 } 15917 15918 return SDValue(); 15919 } 15920 15921 // Transform 15922 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 15923 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 15924 // In this case both C1 and C2 must be known constants. 15925 // C1+C2 must fit into a 34 bit signed integer. 15926 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 15927 const PPCSubtarget &Subtarget) { 15928 if (!Subtarget.isUsingPCRelativeCalls()) 15929 return SDValue(); 15930 15931 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 15932 // If we find that node try to cast the Global Address and the Constant. 15933 SDValue LHS = N->getOperand(0); 15934 SDValue RHS = N->getOperand(1); 15935 15936 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15937 std::swap(LHS, RHS); 15938 15939 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15940 return SDValue(); 15941 15942 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 15943 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 15944 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 15945 15946 // Check that both casts succeeded. 15947 if (!GSDN || !ConstNode) 15948 return SDValue(); 15949 15950 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 15951 SDLoc DL(GSDN); 15952 15953 // The signed int offset needs to fit in 34 bits. 15954 if (!isInt<34>(NewOffset)) 15955 return SDValue(); 15956 15957 // The new global address is a copy of the old global address except 15958 // that it has the updated Offset. 15959 SDValue GA = 15960 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 15961 NewOffset, GSDN->getTargetFlags()); 15962 SDValue MatPCRel = 15963 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 15964 return MatPCRel; 15965 } 15966 15967 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15968 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15969 return Value; 15970 15971 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 15972 return Value; 15973 15974 return SDValue(); 15975 } 15976 15977 // Detect TRUNCATE operations on bitcasts of float128 values. 15978 // What we are looking for here is the situtation where we extract a subset 15979 // of bits from a 128 bit float. 15980 // This can be of two forms: 15981 // 1) BITCAST of f128 feeding TRUNCATE 15982 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15983 // The reason this is required is because we do not have a legal i128 type 15984 // and so we want to prevent having to store the f128 and then reload part 15985 // of it. 15986 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15987 DAGCombinerInfo &DCI) const { 15988 // If we are using CRBits then try that first. 15989 if (Subtarget.useCRBits()) { 15990 // Check if CRBits did anything and return that if it did. 15991 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15992 return CRTruncValue; 15993 } 15994 15995 SDLoc dl(N); 15996 SDValue Op0 = N->getOperand(0); 15997 15998 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 15999 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16000 EVT VT = N->getValueType(0); 16001 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16002 return SDValue(); 16003 SDValue Sub = Op0.getOperand(0); 16004 if (Sub.getOpcode() == ISD::SUB) { 16005 SDValue SubOp0 = Sub.getOperand(0); 16006 SDValue SubOp1 = Sub.getOperand(1); 16007 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16008 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16009 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16010 SubOp1.getOperand(0), 16011 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16012 } 16013 } 16014 } 16015 16016 // Looking for a truncate of i128 to i64. 16017 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16018 return SDValue(); 16019 16020 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16021 16022 // SRL feeding TRUNCATE. 16023 if (Op0.getOpcode() == ISD::SRL) { 16024 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16025 // The right shift has to be by 64 bits. 16026 if (!ConstNode || ConstNode->getZExtValue() != 64) 16027 return SDValue(); 16028 16029 // Switch the element number to extract. 16030 EltToExtract = EltToExtract ? 0 : 1; 16031 // Update Op0 past the SRL. 16032 Op0 = Op0.getOperand(0); 16033 } 16034 16035 // BITCAST feeding a TRUNCATE possibly via SRL. 16036 if (Op0.getOpcode() == ISD::BITCAST && 16037 Op0.getValueType() == MVT::i128 && 16038 Op0.getOperand(0).getValueType() == MVT::f128) { 16039 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16040 return DCI.DAG.getNode( 16041 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16042 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16043 } 16044 return SDValue(); 16045 } 16046 16047 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16048 SelectionDAG &DAG = DCI.DAG; 16049 16050 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16051 if (!ConstOpOrElement) 16052 return SDValue(); 16053 16054 // An imul is usually smaller than the alternative sequence for legal type. 16055 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16056 isOperationLegal(ISD::MUL, N->getValueType(0))) 16057 return SDValue(); 16058 16059 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16060 switch (this->Subtarget.getCPUDirective()) { 16061 default: 16062 // TODO: enhance the condition for subtarget before pwr8 16063 return false; 16064 case PPC::DIR_PWR8: 16065 // type mul add shl 16066 // scalar 4 1 1 16067 // vector 7 2 2 16068 return true; 16069 case PPC::DIR_PWR9: 16070 case PPC::DIR_PWR10: 16071 case PPC::DIR_PWR_FUTURE: 16072 // type mul add shl 16073 // scalar 5 2 2 16074 // vector 7 2 2 16075 16076 // The cycle RATIO of related operations are showed as a table above. 16077 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16078 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16079 // are 4, it is always profitable; but for 3 instrs patterns 16080 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16081 // So we should only do it for vector type. 16082 return IsAddOne && IsNeg ? VT.isVector() : true; 16083 } 16084 }; 16085 16086 EVT VT = N->getValueType(0); 16087 SDLoc DL(N); 16088 16089 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16090 bool IsNeg = MulAmt.isNegative(); 16091 APInt MulAmtAbs = MulAmt.abs(); 16092 16093 if ((MulAmtAbs - 1).isPowerOf2()) { 16094 // (mul x, 2^N + 1) => (add (shl x, N), x) 16095 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16096 16097 if (!IsProfitable(IsNeg, true, VT)) 16098 return SDValue(); 16099 16100 SDValue Op0 = N->getOperand(0); 16101 SDValue Op1 = 16102 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16103 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16104 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16105 16106 if (!IsNeg) 16107 return Res; 16108 16109 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16110 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16111 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16112 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16113 16114 if (!IsProfitable(IsNeg, false, VT)) 16115 return SDValue(); 16116 16117 SDValue Op0 = N->getOperand(0); 16118 SDValue Op1 = 16119 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16120 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16121 16122 if (!IsNeg) 16123 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16124 else 16125 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16126 16127 } else { 16128 return SDValue(); 16129 } 16130 } 16131 16132 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16133 // in combiner since we need to check SD flags and other subtarget features. 16134 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16135 DAGCombinerInfo &DCI) const { 16136 SDValue N0 = N->getOperand(0); 16137 SDValue N1 = N->getOperand(1); 16138 SDValue N2 = N->getOperand(2); 16139 SDNodeFlags Flags = N->getFlags(); 16140 EVT VT = N->getValueType(0); 16141 SelectionDAG &DAG = DCI.DAG; 16142 const TargetOptions &Options = getTargetMachine().Options; 16143 unsigned Opc = N->getOpcode(); 16144 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16145 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16146 SDLoc Loc(N); 16147 16148 if (!isOperationLegal(ISD::FMA, VT)) 16149 return SDValue(); 16150 16151 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16152 // since (fnmsub a b c)=-0 while c-ab=+0. 16153 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16154 return SDValue(); 16155 16156 // (fma (fneg a) b c) => (fnmsub a b c) 16157 // (fnmsub (fneg a) b c) => (fma a b c) 16158 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16159 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16160 16161 // (fma a (fneg b) c) => (fnmsub a b c) 16162 // (fnmsub a (fneg b) c) => (fma a b c) 16163 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16164 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16165 16166 return SDValue(); 16167 } 16168 16169 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16170 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16171 if (!Subtarget.is64BitELFABI()) 16172 return false; 16173 16174 // If not a tail call then no need to proceed. 16175 if (!CI->isTailCall()) 16176 return false; 16177 16178 // If sibling calls have been disabled and tail-calls aren't guaranteed 16179 // there is no reason to duplicate. 16180 auto &TM = getTargetMachine(); 16181 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16182 return false; 16183 16184 // Can't tail call a function called indirectly, or if it has variadic args. 16185 const Function *Callee = CI->getCalledFunction(); 16186 if (!Callee || Callee->isVarArg()) 16187 return false; 16188 16189 // Make sure the callee and caller calling conventions are eligible for tco. 16190 const Function *Caller = CI->getParent()->getParent(); 16191 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16192 CI->getCallingConv())) 16193 return false; 16194 16195 // If the function is local then we have a good chance at tail-calling it 16196 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16197 } 16198 16199 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16200 if (!Subtarget.hasVSX()) 16201 return false; 16202 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16203 return true; 16204 return VT == MVT::f32 || VT == MVT::f64 || 16205 VT == MVT::v4f32 || VT == MVT::v2f64; 16206 } 16207 16208 bool PPCTargetLowering:: 16209 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16210 const Value *Mask = AndI.getOperand(1); 16211 // If the mask is suitable for andi. or andis. we should sink the and. 16212 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16213 // Can't handle constants wider than 64-bits. 16214 if (CI->getBitWidth() > 64) 16215 return false; 16216 int64_t ConstVal = CI->getZExtValue(); 16217 return isUInt<16>(ConstVal) || 16218 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16219 } 16220 16221 // For non-constant masks, we can always use the record-form and. 16222 return true; 16223 } 16224 16225 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16226 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16227 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16228 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16229 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16230 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16231 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16232 assert(Subtarget.hasP9Altivec() && 16233 "Only combine this when P9 altivec supported!"); 16234 EVT VT = N->getValueType(0); 16235 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16236 return SDValue(); 16237 16238 SelectionDAG &DAG = DCI.DAG; 16239 SDLoc dl(N); 16240 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16241 // Even for signed integers, if it's known to be positive (as signed 16242 // integer) due to zero-extended inputs. 16243 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16244 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16245 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16246 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16247 (SubOpcd1 == ISD::ZERO_EXTEND || 16248 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16249 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16250 N->getOperand(0)->getOperand(0), 16251 N->getOperand(0)->getOperand(1), 16252 DAG.getTargetConstant(0, dl, MVT::i32)); 16253 } 16254 16255 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16256 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16257 N->getOperand(0).hasOneUse()) { 16258 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16259 N->getOperand(0)->getOperand(0), 16260 N->getOperand(0)->getOperand(1), 16261 DAG.getTargetConstant(1, dl, MVT::i32)); 16262 } 16263 } 16264 16265 return SDValue(); 16266 } 16267 16268 // For type v4i32/v8ii16/v16i8, transform 16269 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16270 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16271 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16272 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16273 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16274 DAGCombinerInfo &DCI) const { 16275 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16276 assert(Subtarget.hasP9Altivec() && 16277 "Only combine this when P9 altivec supported!"); 16278 16279 SelectionDAG &DAG = DCI.DAG; 16280 SDLoc dl(N); 16281 SDValue Cond = N->getOperand(0); 16282 SDValue TrueOpnd = N->getOperand(1); 16283 SDValue FalseOpnd = N->getOperand(2); 16284 EVT VT = N->getOperand(1).getValueType(); 16285 16286 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16287 FalseOpnd.getOpcode() != ISD::SUB) 16288 return SDValue(); 16289 16290 // ABSD only available for type v4i32/v8i16/v16i8 16291 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16292 return SDValue(); 16293 16294 // At least to save one more dependent computation 16295 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16296 return SDValue(); 16297 16298 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16299 16300 // Can only handle unsigned comparison here 16301 switch (CC) { 16302 default: 16303 return SDValue(); 16304 case ISD::SETUGT: 16305 case ISD::SETUGE: 16306 break; 16307 case ISD::SETULT: 16308 case ISD::SETULE: 16309 std::swap(TrueOpnd, FalseOpnd); 16310 break; 16311 } 16312 16313 SDValue CmpOpnd1 = Cond.getOperand(0); 16314 SDValue CmpOpnd2 = Cond.getOperand(1); 16315 16316 // SETCC CmpOpnd1 CmpOpnd2 cond 16317 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16318 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16319 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16320 TrueOpnd.getOperand(1) == CmpOpnd2 && 16321 FalseOpnd.getOperand(0) == CmpOpnd2 && 16322 FalseOpnd.getOperand(1) == CmpOpnd1) { 16323 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16324 CmpOpnd1, CmpOpnd2, 16325 DAG.getTargetConstant(0, dl, MVT::i32)); 16326 } 16327 16328 return SDValue(); 16329 } 16330