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::STRICT_SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 232 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 233 isPPC64 ? MVT::i64 : MVT::i32); 234 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 235 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 236 isPPC64 ? MVT::i64 : MVT::i32); 237 } else { 238 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 239 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 240 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 241 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 242 } 243 244 // PowerPC does not support direct load/store of condition registers. 245 setOperationAction(ISD::LOAD, MVT::i1, Custom); 246 setOperationAction(ISD::STORE, MVT::i1, Custom); 247 248 // FIXME: Remove this once the ANDI glue bug is fixed: 249 if (ANDIGlueBug) 250 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 251 252 for (MVT VT : MVT::integer_valuetypes()) { 253 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 254 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 255 setTruncStoreAction(VT, MVT::i1, Expand); 256 } 257 258 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 259 } 260 261 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 262 // PPC (the libcall is not available). 263 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 264 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 265 266 // We do not currently implement these libm ops for PowerPC. 267 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 268 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 269 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 270 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 271 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 272 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 273 274 // PowerPC has no SREM/UREM instructions unless we are on P9 275 // On P9 we may use a hardware instruction to compute the remainder. 276 // When the result of both the remainder and the division is required it is 277 // more efficient to compute the remainder from the result of the division 278 // rather than use the remainder instruction. The instructions are legalized 279 // directly because the DivRemPairsPass performs the transformation at the IR 280 // level. 281 if (Subtarget.isISA3_0()) { 282 setOperationAction(ISD::SREM, MVT::i32, Legal); 283 setOperationAction(ISD::UREM, MVT::i32, Legal); 284 setOperationAction(ISD::SREM, MVT::i64, Legal); 285 setOperationAction(ISD::UREM, MVT::i64, Legal); 286 } else { 287 setOperationAction(ISD::SREM, MVT::i32, Expand); 288 setOperationAction(ISD::UREM, MVT::i32, Expand); 289 setOperationAction(ISD::SREM, MVT::i64, Expand); 290 setOperationAction(ISD::UREM, MVT::i64, Expand); 291 } 292 293 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 294 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 295 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 296 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 297 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 298 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 299 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 300 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 301 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 302 303 // Handle constrained floating-point operations of scalar. 304 // TODO: Handle SPE specific operation. 305 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 306 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 307 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 308 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 309 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 310 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 311 312 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 313 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 314 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 315 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 316 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 317 if (Subtarget.hasVSX()) 318 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 319 320 if (Subtarget.hasFSQRT()) { 321 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 322 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 323 } 324 325 if (Subtarget.hasFPRND()) { 326 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 327 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 328 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 329 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 330 331 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 332 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 333 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 334 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 335 } 336 337 // We don't support sin/cos/sqrt/fmod/pow 338 setOperationAction(ISD::FSIN , MVT::f64, Expand); 339 setOperationAction(ISD::FCOS , MVT::f64, Expand); 340 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 341 setOperationAction(ISD::FREM , MVT::f64, Expand); 342 setOperationAction(ISD::FPOW , MVT::f64, Expand); 343 setOperationAction(ISD::FSIN , MVT::f32, Expand); 344 setOperationAction(ISD::FCOS , MVT::f32, Expand); 345 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 346 setOperationAction(ISD::FREM , MVT::f32, Expand); 347 setOperationAction(ISD::FPOW , MVT::f32, Expand); 348 if (Subtarget.hasSPE()) { 349 setOperationAction(ISD::FMA , MVT::f64, Expand); 350 setOperationAction(ISD::FMA , MVT::f32, Expand); 351 } else { 352 setOperationAction(ISD::FMA , MVT::f64, Legal); 353 setOperationAction(ISD::FMA , MVT::f32, Legal); 354 } 355 356 if (Subtarget.hasSPE()) 357 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 358 359 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 360 361 // If we're enabling GP optimizations, use hardware square root 362 if (!Subtarget.hasFSQRT() && 363 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 364 Subtarget.hasFRE())) 365 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 366 367 if (!Subtarget.hasFSQRT() && 368 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 369 Subtarget.hasFRES())) 370 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 371 372 if (Subtarget.hasFCPSGN()) { 373 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 374 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 375 } else { 376 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 377 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 378 } 379 380 if (Subtarget.hasFPRND()) { 381 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 382 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 383 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 384 setOperationAction(ISD::FROUND, MVT::f64, Legal); 385 386 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 387 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 388 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 389 setOperationAction(ISD::FROUND, MVT::f32, Legal); 390 } 391 392 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 393 // to speed up scalar BSWAP64. 394 // CTPOP or CTTZ were introduced in P8/P9 respectively 395 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 396 if (Subtarget.hasP9Vector()) 397 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 398 else 399 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 400 if (Subtarget.isISA3_0()) { 401 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 402 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 403 } else { 404 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 405 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 406 } 407 408 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 409 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 410 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 411 } else { 412 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 413 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 414 } 415 416 // PowerPC does not have ROTR 417 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 418 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 419 420 if (!Subtarget.useCRBits()) { 421 // PowerPC does not have Select 422 setOperationAction(ISD::SELECT, MVT::i32, Expand); 423 setOperationAction(ISD::SELECT, MVT::i64, Expand); 424 setOperationAction(ISD::SELECT, MVT::f32, Expand); 425 setOperationAction(ISD::SELECT, MVT::f64, Expand); 426 } 427 428 // PowerPC wants to turn select_cc of FP into fsel when possible. 429 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 430 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 431 432 // PowerPC wants to optimize integer setcc a bit 433 if (!Subtarget.useCRBits()) 434 setOperationAction(ISD::SETCC, MVT::i32, Custom); 435 436 if (Subtarget.hasFPU()) { 437 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 438 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 439 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 440 441 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 442 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 443 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 444 } 445 446 // PowerPC does not have BRCOND which requires SetCC 447 if (!Subtarget.useCRBits()) 448 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 449 450 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 451 452 if (Subtarget.hasSPE()) { 453 // SPE has built-in conversions 454 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 455 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 456 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 457 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 458 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 459 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 460 } else { 461 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 462 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 463 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 464 465 // PowerPC does not have [U|S]INT_TO_FP 466 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 467 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 468 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 469 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 470 } 471 472 if (Subtarget.hasDirectMove() && isPPC64) { 473 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 474 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 475 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 476 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 477 if (TM.Options.UnsafeFPMath) { 478 setOperationAction(ISD::LRINT, MVT::f64, Legal); 479 setOperationAction(ISD::LRINT, MVT::f32, Legal); 480 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 481 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 482 setOperationAction(ISD::LROUND, MVT::f64, Legal); 483 setOperationAction(ISD::LROUND, MVT::f32, Legal); 484 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 485 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 486 } 487 } else { 488 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 489 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 490 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 491 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 492 } 493 494 // We cannot sextinreg(i1). Expand to shifts. 495 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 496 497 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 498 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 499 // support continuation, user-level threading, and etc.. As a result, no 500 // other SjLj exception interfaces are implemented and please don't build 501 // your own exception handling based on them. 502 // LLVM/Clang supports zero-cost DWARF exception handling. 503 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 504 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 505 506 // We want to legalize GlobalAddress and ConstantPool nodes into the 507 // appropriate instructions to materialize the address. 508 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 509 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 510 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 511 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 512 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 513 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 514 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 515 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 516 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 517 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 518 519 // TRAP is legal. 520 setOperationAction(ISD::TRAP, MVT::Other, Legal); 521 522 // TRAMPOLINE is custom lowered. 523 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 524 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 525 526 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 527 setOperationAction(ISD::VASTART , MVT::Other, Custom); 528 529 if (Subtarget.is64BitELFABI()) { 530 // VAARG always uses double-word chunks, so promote anything smaller. 531 setOperationAction(ISD::VAARG, MVT::i1, Promote); 532 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 533 setOperationAction(ISD::VAARG, MVT::i8, Promote); 534 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 535 setOperationAction(ISD::VAARG, MVT::i16, Promote); 536 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 537 setOperationAction(ISD::VAARG, MVT::i32, Promote); 538 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 539 setOperationAction(ISD::VAARG, MVT::Other, Expand); 540 } else if (Subtarget.is32BitELFABI()) { 541 // VAARG is custom lowered with the 32-bit SVR4 ABI. 542 setOperationAction(ISD::VAARG, MVT::Other, Custom); 543 setOperationAction(ISD::VAARG, MVT::i64, Custom); 544 } else 545 setOperationAction(ISD::VAARG, MVT::Other, Expand); 546 547 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 548 if (Subtarget.is32BitELFABI()) 549 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 550 else 551 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 552 553 // Use the default implementation. 554 setOperationAction(ISD::VAEND , MVT::Other, Expand); 555 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 556 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 557 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 558 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 559 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 560 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 561 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 562 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 563 564 // We want to custom lower some of our intrinsics. 565 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 566 567 // To handle counter-based loop conditions. 568 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 569 570 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 571 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 572 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 573 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 574 575 // Comparisons that require checking two conditions. 576 if (Subtarget.hasSPE()) { 577 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 578 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 579 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 580 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 581 } 582 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 583 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 584 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 585 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 586 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 587 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 588 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 589 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 590 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 591 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 592 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 593 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 594 595 if (Subtarget.has64BitSupport()) { 596 // They also have instructions for converting between i64 and fp. 597 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 598 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 599 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 600 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 601 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 602 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 603 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 604 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 605 // This is just the low 32 bits of a (signed) fp->i64 conversion. 606 // We cannot do this with Promote because i64 is not a legal type. 607 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 608 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 609 610 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 611 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 612 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 613 } 614 } else { 615 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 616 if (Subtarget.hasSPE()) { 617 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 618 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 619 } else { 620 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 621 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 622 } 623 } 624 625 // With the instructions enabled under FPCVT, we can do everything. 626 if (Subtarget.hasFPCVT()) { 627 if (Subtarget.has64BitSupport()) { 628 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 629 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 630 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 631 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 632 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 633 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 634 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 635 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 636 } 637 638 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 639 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 640 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 641 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 642 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 643 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 644 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 645 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 646 } 647 648 if (Subtarget.use64BitRegs()) { 649 // 64-bit PowerPC implementations can support i64 types directly 650 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 651 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 652 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 653 // 64-bit PowerPC wants to expand i128 shifts itself. 654 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 655 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 656 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 657 } else { 658 // 32-bit PowerPC wants to expand i64 shifts itself. 659 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 660 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 661 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 662 } 663 664 // PowerPC has better expansions for funnel shifts than the generic 665 // TargetLowering::expandFunnelShift. 666 if (Subtarget.has64BitSupport()) { 667 setOperationAction(ISD::FSHL, MVT::i64, Custom); 668 setOperationAction(ISD::FSHR, MVT::i64, Custom); 669 } 670 setOperationAction(ISD::FSHL, MVT::i32, Custom); 671 setOperationAction(ISD::FSHR, MVT::i32, Custom); 672 673 if (Subtarget.hasVSX()) { 674 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 675 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 676 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 677 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 678 } 679 680 if (Subtarget.hasAltivec()) { 681 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 682 setOperationAction(ISD::SADDSAT, VT, Legal); 683 setOperationAction(ISD::SSUBSAT, VT, Legal); 684 setOperationAction(ISD::UADDSAT, VT, Legal); 685 setOperationAction(ISD::USUBSAT, VT, Legal); 686 } 687 // First set operation action for all vector types to expand. Then we 688 // will selectively turn on ones that can be effectively codegen'd. 689 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 690 // add/sub are legal for all supported vector VT's. 691 setOperationAction(ISD::ADD, VT, Legal); 692 setOperationAction(ISD::SUB, VT, Legal); 693 694 // For v2i64, these are only valid with P8Vector. This is corrected after 695 // the loop. 696 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 697 setOperationAction(ISD::SMAX, VT, Legal); 698 setOperationAction(ISD::SMIN, VT, Legal); 699 setOperationAction(ISD::UMAX, VT, Legal); 700 setOperationAction(ISD::UMIN, VT, Legal); 701 } 702 else { 703 setOperationAction(ISD::SMAX, VT, Expand); 704 setOperationAction(ISD::SMIN, VT, Expand); 705 setOperationAction(ISD::UMAX, VT, Expand); 706 setOperationAction(ISD::UMIN, VT, Expand); 707 } 708 709 if (Subtarget.hasVSX()) { 710 setOperationAction(ISD::FMAXNUM, VT, Legal); 711 setOperationAction(ISD::FMINNUM, VT, Legal); 712 } 713 714 // Vector instructions introduced in P8 715 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 716 setOperationAction(ISD::CTPOP, VT, Legal); 717 setOperationAction(ISD::CTLZ, VT, Legal); 718 } 719 else { 720 setOperationAction(ISD::CTPOP, VT, Expand); 721 setOperationAction(ISD::CTLZ, VT, Expand); 722 } 723 724 // Vector instructions introduced in P9 725 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 726 setOperationAction(ISD::CTTZ, VT, Legal); 727 else 728 setOperationAction(ISD::CTTZ, VT, Expand); 729 730 // We promote all shuffles to v16i8. 731 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 732 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 733 734 // We promote all non-typed operations to v4i32. 735 setOperationAction(ISD::AND , VT, Promote); 736 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 737 setOperationAction(ISD::OR , VT, Promote); 738 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 739 setOperationAction(ISD::XOR , VT, Promote); 740 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 741 setOperationAction(ISD::LOAD , VT, Promote); 742 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 743 setOperationAction(ISD::SELECT, VT, Promote); 744 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 745 setOperationAction(ISD::VSELECT, VT, Legal); 746 setOperationAction(ISD::SELECT_CC, VT, Promote); 747 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 748 setOperationAction(ISD::STORE, VT, Promote); 749 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 750 751 // No other operations are legal. 752 setOperationAction(ISD::MUL , VT, Expand); 753 setOperationAction(ISD::SDIV, VT, Expand); 754 setOperationAction(ISD::SREM, VT, Expand); 755 setOperationAction(ISD::UDIV, VT, Expand); 756 setOperationAction(ISD::UREM, VT, Expand); 757 setOperationAction(ISD::FDIV, VT, Expand); 758 setOperationAction(ISD::FREM, VT, Expand); 759 setOperationAction(ISD::FNEG, VT, Expand); 760 setOperationAction(ISD::FSQRT, VT, Expand); 761 setOperationAction(ISD::FLOG, VT, Expand); 762 setOperationAction(ISD::FLOG10, VT, Expand); 763 setOperationAction(ISD::FLOG2, VT, Expand); 764 setOperationAction(ISD::FEXP, VT, Expand); 765 setOperationAction(ISD::FEXP2, VT, Expand); 766 setOperationAction(ISD::FSIN, VT, Expand); 767 setOperationAction(ISD::FCOS, VT, Expand); 768 setOperationAction(ISD::FABS, VT, Expand); 769 setOperationAction(ISD::FFLOOR, VT, Expand); 770 setOperationAction(ISD::FCEIL, VT, Expand); 771 setOperationAction(ISD::FTRUNC, VT, Expand); 772 setOperationAction(ISD::FRINT, VT, Expand); 773 setOperationAction(ISD::FNEARBYINT, VT, Expand); 774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 775 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 776 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 777 setOperationAction(ISD::MULHU, VT, Expand); 778 setOperationAction(ISD::MULHS, VT, Expand); 779 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 780 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 781 setOperationAction(ISD::UDIVREM, VT, Expand); 782 setOperationAction(ISD::SDIVREM, VT, Expand); 783 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 784 setOperationAction(ISD::FPOW, VT, Expand); 785 setOperationAction(ISD::BSWAP, VT, Expand); 786 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 787 setOperationAction(ISD::ROTL, VT, Expand); 788 setOperationAction(ISD::ROTR, VT, Expand); 789 790 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 791 setTruncStoreAction(VT, InnerVT, Expand); 792 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 793 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 794 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 795 } 796 } 797 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 798 if (!Subtarget.hasP8Vector()) { 799 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 800 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 801 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 802 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 803 } 804 805 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 806 setOperationAction(ISD::ABS, VT, Custom); 807 808 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 809 // with merges, splats, etc. 810 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 811 812 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 813 // are cheap, so handle them before they get expanded to scalar. 814 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 815 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 816 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 817 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 818 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 819 820 setOperationAction(ISD::AND , MVT::v4i32, Legal); 821 setOperationAction(ISD::OR , MVT::v4i32, Legal); 822 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 823 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 824 setOperationAction(ISD::SELECT, MVT::v4i32, 825 Subtarget.useCRBits() ? Legal : Expand); 826 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 827 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 828 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 829 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 830 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 831 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 832 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 833 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 834 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 835 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 836 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 837 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 838 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 839 840 // Without hasP8Altivec set, v2i64 SMAX isn't available. 841 // But ABS custom lowering requires SMAX support. 842 if (!Subtarget.hasP8Altivec()) 843 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 844 845 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 846 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 847 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 848 if (Subtarget.hasAltivec()) 849 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 850 setOperationAction(ISD::ROTL, VT, Legal); 851 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 852 if (Subtarget.hasP8Altivec()) 853 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 854 855 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 856 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 857 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 858 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 859 860 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 861 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 862 863 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 864 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 865 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 866 } 867 868 if (Subtarget.hasP8Altivec()) 869 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 870 else 871 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 872 873 if (Subtarget.isISA3_1()) { 874 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 875 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 876 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 877 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 878 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 879 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 880 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 881 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 882 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 883 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 884 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 885 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 886 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 887 } 888 889 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 890 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 891 892 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 894 895 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 896 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 897 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 898 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 899 900 // Altivec does not contain unordered floating-point compare instructions 901 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 902 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 903 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 904 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 905 906 if (Subtarget.hasVSX()) { 907 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 909 if (Subtarget.hasP8Vector()) { 910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 911 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 912 } 913 if (Subtarget.hasDirectMove() && isPPC64) { 914 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 915 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 916 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 917 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 919 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 920 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 922 } 923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 924 925 // The nearbyint variants are not allowed to raise the inexact exception 926 // so we can only code-gen them with unsafe math. 927 if (TM.Options.UnsafeFPMath) { 928 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 929 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 930 } 931 932 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 933 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 934 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 935 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 936 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 937 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 938 setOperationAction(ISD::FROUND, MVT::f64, Legal); 939 setOperationAction(ISD::FRINT, MVT::f64, Legal); 940 941 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 942 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 943 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 944 setOperationAction(ISD::FROUND, MVT::f32, Legal); 945 setOperationAction(ISD::FRINT, MVT::f32, Legal); 946 947 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 948 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 949 950 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 951 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 952 953 // Share the Altivec comparison restrictions. 954 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 955 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 956 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 957 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 958 959 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 960 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 961 962 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 963 964 if (Subtarget.hasP8Vector()) 965 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 966 967 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 968 969 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 970 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 971 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 972 973 if (Subtarget.hasP8Altivec()) { 974 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 975 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 976 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 977 978 // 128 bit shifts can be accomplished via 3 instructions for SHL and 979 // SRL, but not for SRA because of the instructions available: 980 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 981 // doing 982 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 983 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 984 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 985 986 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 987 } 988 else { 989 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 990 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 991 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 992 993 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 994 995 // VSX v2i64 only supports non-arithmetic operations. 996 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 997 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 998 } 999 1000 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1001 1002 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1003 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1004 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1005 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1006 1007 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 1008 1009 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1010 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1011 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1012 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1013 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1014 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1015 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1016 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1017 1018 // Custom handling for partial vectors of integers converted to 1019 // floating point. We already have optimal handling for v2i32 through 1020 // the DAG combine, so those aren't necessary. 1021 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1022 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1023 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1024 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1025 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1026 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1027 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1028 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1029 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1030 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1031 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1032 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1033 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1034 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1035 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1036 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1037 1038 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1039 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1040 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1041 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1042 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1043 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1044 1045 if (Subtarget.hasDirectMove()) 1046 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1047 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1048 1049 // Handle constrained floating-point operations of vector. 1050 // The predictor is `hasVSX` because altivec instruction has 1051 // no exception but VSX vector instruction has. 1052 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1053 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1054 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1055 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1056 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1057 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1058 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1059 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1060 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 1061 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1062 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1063 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1064 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1065 1066 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1067 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1068 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1069 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1070 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1071 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1072 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1073 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1074 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 1075 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1076 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1077 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1078 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1079 1080 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1081 } 1082 1083 if (Subtarget.hasP8Altivec()) { 1084 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1085 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1086 } 1087 1088 if (Subtarget.hasP9Vector()) { 1089 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1090 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1091 1092 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1093 // SRL, but not for SRA because of the instructions available: 1094 // VS{RL} and VS{RL}O. 1095 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1096 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1097 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1098 1099 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1100 setOperationAction(ISD::FADD, MVT::f128, Legal); 1101 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1102 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1103 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1104 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1105 // No extending loads to f128 on PPC. 1106 for (MVT FPT : MVT::fp_valuetypes()) 1107 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1108 setOperationAction(ISD::FMA, MVT::f128, Legal); 1109 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1110 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1111 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1112 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1113 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1114 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1115 1116 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1117 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1118 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1119 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1120 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1121 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1122 1123 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1124 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1125 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1126 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1127 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1128 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1129 // No implementation for these ops for PowerPC. 1130 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1131 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1132 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1133 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1134 setOperationAction(ISD::FREM, MVT::f128, Expand); 1135 1136 // Handle constrained floating-point operations of fp128 1137 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1138 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1139 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1140 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1141 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1142 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1143 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1144 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1145 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1146 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1147 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1148 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1149 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1150 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1151 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1152 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1153 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1154 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1155 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1156 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1157 } 1158 1159 if (Subtarget.hasP9Altivec()) { 1160 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1161 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1162 1163 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1164 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1165 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1166 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1167 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1168 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1169 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1170 } 1171 } 1172 1173 if (Subtarget.has64BitSupport()) 1174 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1175 1176 if (Subtarget.isISA3_1()) 1177 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1178 1179 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1180 1181 if (!isPPC64) { 1182 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1183 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1184 } 1185 1186 setBooleanContents(ZeroOrOneBooleanContent); 1187 1188 if (Subtarget.hasAltivec()) { 1189 // Altivec instructions set fields to all zeros or all ones. 1190 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1191 } 1192 1193 if (!isPPC64) { 1194 // These libcalls are not available in 32-bit. 1195 setLibcallName(RTLIB::SHL_I128, nullptr); 1196 setLibcallName(RTLIB::SRL_I128, nullptr); 1197 setLibcallName(RTLIB::SRA_I128, nullptr); 1198 } 1199 1200 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1201 1202 // We have target-specific dag combine patterns for the following nodes: 1203 setTargetDAGCombine(ISD::ADD); 1204 setTargetDAGCombine(ISD::SHL); 1205 setTargetDAGCombine(ISD::SRA); 1206 setTargetDAGCombine(ISD::SRL); 1207 setTargetDAGCombine(ISD::MUL); 1208 setTargetDAGCombine(ISD::FMA); 1209 setTargetDAGCombine(ISD::SINT_TO_FP); 1210 setTargetDAGCombine(ISD::BUILD_VECTOR); 1211 if (Subtarget.hasFPCVT()) 1212 setTargetDAGCombine(ISD::UINT_TO_FP); 1213 setTargetDAGCombine(ISD::LOAD); 1214 setTargetDAGCombine(ISD::STORE); 1215 setTargetDAGCombine(ISD::BR_CC); 1216 if (Subtarget.useCRBits()) 1217 setTargetDAGCombine(ISD::BRCOND); 1218 setTargetDAGCombine(ISD::BSWAP); 1219 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1220 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1221 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1222 1223 setTargetDAGCombine(ISD::SIGN_EXTEND); 1224 setTargetDAGCombine(ISD::ZERO_EXTEND); 1225 setTargetDAGCombine(ISD::ANY_EXTEND); 1226 1227 setTargetDAGCombine(ISD::TRUNCATE); 1228 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1229 1230 1231 if (Subtarget.useCRBits()) { 1232 setTargetDAGCombine(ISD::TRUNCATE); 1233 setTargetDAGCombine(ISD::SETCC); 1234 setTargetDAGCombine(ISD::SELECT_CC); 1235 } 1236 1237 // Use reciprocal estimates. 1238 if (TM.Options.UnsafeFPMath) { 1239 setTargetDAGCombine(ISD::FDIV); 1240 setTargetDAGCombine(ISD::FSQRT); 1241 } 1242 1243 if (Subtarget.hasP9Altivec()) { 1244 setTargetDAGCombine(ISD::ABS); 1245 setTargetDAGCombine(ISD::VSELECT); 1246 } 1247 1248 setLibcallName(RTLIB::LOG_F128, "logf128"); 1249 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1250 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1251 setLibcallName(RTLIB::EXP_F128, "expf128"); 1252 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1253 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1254 setLibcallName(RTLIB::COS_F128, "cosf128"); 1255 setLibcallName(RTLIB::POW_F128, "powf128"); 1256 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1257 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1258 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1259 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1260 1261 // With 32 condition bits, we don't need to sink (and duplicate) compares 1262 // aggressively in CodeGenPrep. 1263 if (Subtarget.useCRBits()) { 1264 setHasMultipleConditionRegisters(); 1265 setJumpIsExpensive(); 1266 } 1267 1268 setMinFunctionAlignment(Align(4)); 1269 1270 switch (Subtarget.getCPUDirective()) { 1271 default: break; 1272 case PPC::DIR_970: 1273 case PPC::DIR_A2: 1274 case PPC::DIR_E500: 1275 case PPC::DIR_E500mc: 1276 case PPC::DIR_E5500: 1277 case PPC::DIR_PWR4: 1278 case PPC::DIR_PWR5: 1279 case PPC::DIR_PWR5X: 1280 case PPC::DIR_PWR6: 1281 case PPC::DIR_PWR6X: 1282 case PPC::DIR_PWR7: 1283 case PPC::DIR_PWR8: 1284 case PPC::DIR_PWR9: 1285 case PPC::DIR_PWR10: 1286 case PPC::DIR_PWR_FUTURE: 1287 setPrefLoopAlignment(Align(16)); 1288 setPrefFunctionAlignment(Align(16)); 1289 break; 1290 } 1291 1292 if (Subtarget.enableMachineScheduler()) 1293 setSchedulingPreference(Sched::Source); 1294 else 1295 setSchedulingPreference(Sched::Hybrid); 1296 1297 computeRegisterProperties(STI.getRegisterInfo()); 1298 1299 // The Freescale cores do better with aggressive inlining of memcpy and 1300 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1301 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1302 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1303 MaxStoresPerMemset = 32; 1304 MaxStoresPerMemsetOptSize = 16; 1305 MaxStoresPerMemcpy = 32; 1306 MaxStoresPerMemcpyOptSize = 8; 1307 MaxStoresPerMemmove = 32; 1308 MaxStoresPerMemmoveOptSize = 8; 1309 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1310 // The A2 also benefits from (very) aggressive inlining of memcpy and 1311 // friends. The overhead of a the function call, even when warm, can be 1312 // over one hundred cycles. 1313 MaxStoresPerMemset = 128; 1314 MaxStoresPerMemcpy = 128; 1315 MaxStoresPerMemmove = 128; 1316 MaxLoadsPerMemcmp = 128; 1317 } else { 1318 MaxLoadsPerMemcmp = 8; 1319 MaxLoadsPerMemcmpOptSize = 4; 1320 } 1321 1322 // Let the subtarget (CPU) decide if a predictable select is more expensive 1323 // than the corresponding branch. This information is used in CGP to decide 1324 // when to convert selects into branches. 1325 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1326 } 1327 1328 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1329 /// the desired ByVal argument alignment. 1330 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1331 if (MaxAlign == MaxMaxAlign) 1332 return; 1333 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1334 if (MaxMaxAlign >= 32 && 1335 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1336 MaxAlign = Align(32); 1337 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1338 MaxAlign < 16) 1339 MaxAlign = Align(16); 1340 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1341 Align EltAlign; 1342 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1343 if (EltAlign > MaxAlign) 1344 MaxAlign = EltAlign; 1345 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1346 for (auto *EltTy : STy->elements()) { 1347 Align EltAlign; 1348 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1349 if (EltAlign > MaxAlign) 1350 MaxAlign = EltAlign; 1351 if (MaxAlign == MaxMaxAlign) 1352 break; 1353 } 1354 } 1355 } 1356 1357 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1358 /// function arguments in the caller parameter area. 1359 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1360 const DataLayout &DL) const { 1361 // 16byte and wider vectors are passed on 16byte boundary. 1362 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1363 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1364 if (Subtarget.hasAltivec()) 1365 getMaxByValAlign(Ty, Alignment, Align(16)); 1366 return Alignment.value(); 1367 } 1368 1369 bool PPCTargetLowering::useSoftFloat() const { 1370 return Subtarget.useSoftFloat(); 1371 } 1372 1373 bool PPCTargetLowering::hasSPE() const { 1374 return Subtarget.hasSPE(); 1375 } 1376 1377 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1378 return VT.isScalarInteger(); 1379 } 1380 1381 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1382 /// type is cheaper than a multiply followed by a shift. 1383 /// This is true for words and doublewords on 64-bit PowerPC. 1384 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1385 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1386 isOperationLegal(ISD::MULHU, Type))) 1387 return true; 1388 return TargetLowering::isMulhCheaperThanMulShift(Type); 1389 } 1390 1391 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1392 switch ((PPCISD::NodeType)Opcode) { 1393 case PPCISD::FIRST_NUMBER: break; 1394 case PPCISD::FSEL: return "PPCISD::FSEL"; 1395 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1396 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1397 case PPCISD::FCFID: return "PPCISD::FCFID"; 1398 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1399 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1400 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1401 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1402 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1403 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1404 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1405 case PPCISD::FP_TO_UINT_IN_VSR: 1406 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1407 case PPCISD::FP_TO_SINT_IN_VSR: 1408 return "PPCISD::FP_TO_SINT_IN_VSR"; 1409 case PPCISD::FRE: return "PPCISD::FRE"; 1410 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1411 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1412 case PPCISD::VPERM: return "PPCISD::VPERM"; 1413 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1414 case PPCISD::XXSPLTI_SP_TO_DP: 1415 return "PPCISD::XXSPLTI_SP_TO_DP"; 1416 case PPCISD::XXSPLTI32DX: 1417 return "PPCISD::XXSPLTI32DX"; 1418 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1419 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1420 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1421 case PPCISD::CMPB: return "PPCISD::CMPB"; 1422 case PPCISD::Hi: return "PPCISD::Hi"; 1423 case PPCISD::Lo: return "PPCISD::Lo"; 1424 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1425 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1426 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1427 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1428 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1429 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1430 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1431 case PPCISD::SRL: return "PPCISD::SRL"; 1432 case PPCISD::SRA: return "PPCISD::SRA"; 1433 case PPCISD::SHL: return "PPCISD::SHL"; 1434 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1435 case PPCISD::CALL: return "PPCISD::CALL"; 1436 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1437 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1438 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1439 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1440 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1441 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1442 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1443 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1444 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1445 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1446 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1447 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1448 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1449 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1450 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1451 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1452 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1453 case PPCISD::ANDI_rec_1_EQ_BIT: 1454 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1455 case PPCISD::ANDI_rec_1_GT_BIT: 1456 return "PPCISD::ANDI_rec_1_GT_BIT"; 1457 case PPCISD::VCMP: return "PPCISD::VCMP"; 1458 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1459 case PPCISD::LBRX: return "PPCISD::LBRX"; 1460 case PPCISD::STBRX: return "PPCISD::STBRX"; 1461 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1462 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1463 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1464 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1465 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1466 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1467 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1468 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1469 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1470 case PPCISD::ST_VSR_SCAL_INT: 1471 return "PPCISD::ST_VSR_SCAL_INT"; 1472 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1473 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1474 case PPCISD::BDZ: return "PPCISD::BDZ"; 1475 case PPCISD::MFFS: return "PPCISD::MFFS"; 1476 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1477 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1478 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1479 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1480 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1481 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1482 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1483 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1484 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1485 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1486 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1487 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1488 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1489 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1490 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1491 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1492 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1493 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1494 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1495 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1496 case PPCISD::SC: return "PPCISD::SC"; 1497 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1498 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1499 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1500 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1501 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1502 case PPCISD::VABSD: return "PPCISD::VABSD"; 1503 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1504 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1505 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1506 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1507 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1508 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1509 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1510 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1511 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1512 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1513 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1514 case PPCISD::STRICT_FCTIDZ: 1515 return "PPCISD::STRICT_FCTIDZ"; 1516 case PPCISD::STRICT_FCTIWZ: 1517 return "PPCISD::STRICT_FCTIWZ"; 1518 case PPCISD::STRICT_FCTIDUZ: 1519 return "PPCISD::STRICT_FCTIDUZ"; 1520 case PPCISD::STRICT_FCTIWUZ: 1521 return "PPCISD::STRICT_FCTIWUZ"; 1522 case PPCISD::STRICT_FCFID: 1523 return "PPCISD::STRICT_FCFID"; 1524 case PPCISD::STRICT_FCFIDU: 1525 return "PPCISD::STRICT_FCFIDU"; 1526 case PPCISD::STRICT_FCFIDS: 1527 return "PPCISD::STRICT_FCFIDS"; 1528 case PPCISD::STRICT_FCFIDUS: 1529 return "PPCISD::STRICT_FCFIDUS"; 1530 } 1531 return nullptr; 1532 } 1533 1534 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1535 EVT VT) const { 1536 if (!VT.isVector()) 1537 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1538 1539 return VT.changeVectorElementTypeToInteger(); 1540 } 1541 1542 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1543 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1544 return true; 1545 } 1546 1547 //===----------------------------------------------------------------------===// 1548 // Node matching predicates, for use by the tblgen matching code. 1549 //===----------------------------------------------------------------------===// 1550 1551 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1552 static bool isFloatingPointZero(SDValue Op) { 1553 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1554 return CFP->getValueAPF().isZero(); 1555 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1556 // Maybe this has already been legalized into the constant pool? 1557 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1558 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1559 return CFP->getValueAPF().isZero(); 1560 } 1561 return false; 1562 } 1563 1564 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1565 /// true if Op is undef or if it matches the specified value. 1566 static bool isConstantOrUndef(int Op, int Val) { 1567 return Op < 0 || Op == Val; 1568 } 1569 1570 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1571 /// VPKUHUM instruction. 1572 /// The ShuffleKind distinguishes between big-endian operations with 1573 /// two different inputs (0), either-endian operations with two identical 1574 /// inputs (1), and little-endian operations with two different inputs (2). 1575 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1576 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1577 SelectionDAG &DAG) { 1578 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1579 if (ShuffleKind == 0) { 1580 if (IsLE) 1581 return false; 1582 for (unsigned i = 0; i != 16; ++i) 1583 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1584 return false; 1585 } else if (ShuffleKind == 2) { 1586 if (!IsLE) 1587 return false; 1588 for (unsigned i = 0; i != 16; ++i) 1589 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1590 return false; 1591 } else if (ShuffleKind == 1) { 1592 unsigned j = IsLE ? 0 : 1; 1593 for (unsigned i = 0; i != 8; ++i) 1594 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1595 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1596 return false; 1597 } 1598 return true; 1599 } 1600 1601 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1602 /// VPKUWUM instruction. 1603 /// The ShuffleKind distinguishes between big-endian operations with 1604 /// two different inputs (0), either-endian operations with two identical 1605 /// inputs (1), and little-endian operations with two different inputs (2). 1606 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1607 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1608 SelectionDAG &DAG) { 1609 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1610 if (ShuffleKind == 0) { 1611 if (IsLE) 1612 return false; 1613 for (unsigned i = 0; i != 16; i += 2) 1614 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1615 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1616 return false; 1617 } else if (ShuffleKind == 2) { 1618 if (!IsLE) 1619 return false; 1620 for (unsigned i = 0; i != 16; i += 2) 1621 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1622 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1623 return false; 1624 } else if (ShuffleKind == 1) { 1625 unsigned j = IsLE ? 0 : 2; 1626 for (unsigned i = 0; i != 8; i += 2) 1627 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1628 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1629 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1630 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1631 return false; 1632 } 1633 return true; 1634 } 1635 1636 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1637 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1638 /// current subtarget. 1639 /// 1640 /// The ShuffleKind distinguishes between big-endian operations with 1641 /// two different inputs (0), either-endian operations with two identical 1642 /// inputs (1), and little-endian operations with two different inputs (2). 1643 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1644 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1645 SelectionDAG &DAG) { 1646 const PPCSubtarget& Subtarget = 1647 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1648 if (!Subtarget.hasP8Vector()) 1649 return false; 1650 1651 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1652 if (ShuffleKind == 0) { 1653 if (IsLE) 1654 return false; 1655 for (unsigned i = 0; i != 16; i += 4) 1656 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1657 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1658 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1659 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1660 return false; 1661 } else if (ShuffleKind == 2) { 1662 if (!IsLE) 1663 return false; 1664 for (unsigned i = 0; i != 16; i += 4) 1665 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1666 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1667 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1668 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1669 return false; 1670 } else if (ShuffleKind == 1) { 1671 unsigned j = IsLE ? 0 : 4; 1672 for (unsigned i = 0; i != 8; i += 4) 1673 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1674 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1675 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1676 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1677 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1678 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1679 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1680 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1681 return false; 1682 } 1683 return true; 1684 } 1685 1686 /// isVMerge - Common function, used to match vmrg* shuffles. 1687 /// 1688 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1689 unsigned LHSStart, unsigned RHSStart) { 1690 if (N->getValueType(0) != MVT::v16i8) 1691 return false; 1692 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1693 "Unsupported merge size!"); 1694 1695 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1696 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1697 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1698 LHSStart+j+i*UnitSize) || 1699 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1700 RHSStart+j+i*UnitSize)) 1701 return false; 1702 } 1703 return true; 1704 } 1705 1706 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1707 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1708 /// The ShuffleKind distinguishes between big-endian merges with two 1709 /// different inputs (0), either-endian merges with two identical inputs (1), 1710 /// and little-endian merges with two different inputs (2). For the latter, 1711 /// the input operands are swapped (see PPCInstrAltivec.td). 1712 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1713 unsigned ShuffleKind, SelectionDAG &DAG) { 1714 if (DAG.getDataLayout().isLittleEndian()) { 1715 if (ShuffleKind == 1) // unary 1716 return isVMerge(N, UnitSize, 0, 0); 1717 else if (ShuffleKind == 2) // swapped 1718 return isVMerge(N, UnitSize, 0, 16); 1719 else 1720 return false; 1721 } else { 1722 if (ShuffleKind == 1) // unary 1723 return isVMerge(N, UnitSize, 8, 8); 1724 else if (ShuffleKind == 0) // normal 1725 return isVMerge(N, UnitSize, 8, 24); 1726 else 1727 return false; 1728 } 1729 } 1730 1731 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1732 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1733 /// The ShuffleKind distinguishes between big-endian merges with two 1734 /// different inputs (0), either-endian merges with two identical inputs (1), 1735 /// and little-endian merges with two different inputs (2). For the latter, 1736 /// the input operands are swapped (see PPCInstrAltivec.td). 1737 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1738 unsigned ShuffleKind, SelectionDAG &DAG) { 1739 if (DAG.getDataLayout().isLittleEndian()) { 1740 if (ShuffleKind == 1) // unary 1741 return isVMerge(N, UnitSize, 8, 8); 1742 else if (ShuffleKind == 2) // swapped 1743 return isVMerge(N, UnitSize, 8, 24); 1744 else 1745 return false; 1746 } else { 1747 if (ShuffleKind == 1) // unary 1748 return isVMerge(N, UnitSize, 0, 0); 1749 else if (ShuffleKind == 0) // normal 1750 return isVMerge(N, UnitSize, 0, 16); 1751 else 1752 return false; 1753 } 1754 } 1755 1756 /** 1757 * Common function used to match vmrgew and vmrgow shuffles 1758 * 1759 * The indexOffset determines whether to look for even or odd words in 1760 * the shuffle mask. This is based on the of the endianness of the target 1761 * machine. 1762 * - Little Endian: 1763 * - Use offset of 0 to check for odd elements 1764 * - Use offset of 4 to check for even elements 1765 * - Big Endian: 1766 * - Use offset of 0 to check for even elements 1767 * - Use offset of 4 to check for odd elements 1768 * A detailed description of the vector element ordering for little endian and 1769 * big endian can be found at 1770 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1771 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1772 * compiler differences mean to you 1773 * 1774 * The mask to the shuffle vector instruction specifies the indices of the 1775 * elements from the two input vectors to place in the result. The elements are 1776 * numbered in array-access order, starting with the first vector. These vectors 1777 * are always of type v16i8, thus each vector will contain 16 elements of size 1778 * 8. More info on the shuffle vector can be found in the 1779 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1780 * Language Reference. 1781 * 1782 * The RHSStartValue indicates whether the same input vectors are used (unary) 1783 * or two different input vectors are used, based on the following: 1784 * - If the instruction uses the same vector for both inputs, the range of the 1785 * indices will be 0 to 15. In this case, the RHSStart value passed should 1786 * be 0. 1787 * - If the instruction has two different vectors then the range of the 1788 * indices will be 0 to 31. In this case, the RHSStart value passed should 1789 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1790 * to 31 specify elements in the second vector). 1791 * 1792 * \param[in] N The shuffle vector SD Node to analyze 1793 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1794 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1795 * vector to the shuffle_vector instruction 1796 * \return true iff this shuffle vector represents an even or odd word merge 1797 */ 1798 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1799 unsigned RHSStartValue) { 1800 if (N->getValueType(0) != MVT::v16i8) 1801 return false; 1802 1803 for (unsigned i = 0; i < 2; ++i) 1804 for (unsigned j = 0; j < 4; ++j) 1805 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1806 i*RHSStartValue+j+IndexOffset) || 1807 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1808 i*RHSStartValue+j+IndexOffset+8)) 1809 return false; 1810 return true; 1811 } 1812 1813 /** 1814 * Determine if the specified shuffle mask is suitable for the vmrgew or 1815 * vmrgow instructions. 1816 * 1817 * \param[in] N The shuffle vector SD Node to analyze 1818 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1819 * \param[in] ShuffleKind Identify the type of merge: 1820 * - 0 = big-endian merge with two different inputs; 1821 * - 1 = either-endian merge with two identical inputs; 1822 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1823 * little-endian merges). 1824 * \param[in] DAG The current SelectionDAG 1825 * \return true iff this shuffle mask 1826 */ 1827 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1828 unsigned ShuffleKind, SelectionDAG &DAG) { 1829 if (DAG.getDataLayout().isLittleEndian()) { 1830 unsigned indexOffset = CheckEven ? 4 : 0; 1831 if (ShuffleKind == 1) // Unary 1832 return isVMerge(N, indexOffset, 0); 1833 else if (ShuffleKind == 2) // swapped 1834 return isVMerge(N, indexOffset, 16); 1835 else 1836 return false; 1837 } 1838 else { 1839 unsigned indexOffset = CheckEven ? 0 : 4; 1840 if (ShuffleKind == 1) // Unary 1841 return isVMerge(N, indexOffset, 0); 1842 else if (ShuffleKind == 0) // Normal 1843 return isVMerge(N, indexOffset, 16); 1844 else 1845 return false; 1846 } 1847 return false; 1848 } 1849 1850 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1851 /// amount, otherwise return -1. 1852 /// The ShuffleKind distinguishes between big-endian operations with two 1853 /// different inputs (0), either-endian operations with two identical inputs 1854 /// (1), and little-endian operations with two different inputs (2). For the 1855 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1856 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1857 SelectionDAG &DAG) { 1858 if (N->getValueType(0) != MVT::v16i8) 1859 return -1; 1860 1861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1862 1863 // Find the first non-undef value in the shuffle mask. 1864 unsigned i; 1865 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1866 /*search*/; 1867 1868 if (i == 16) return -1; // all undef. 1869 1870 // Otherwise, check to see if the rest of the elements are consecutively 1871 // numbered from this value. 1872 unsigned ShiftAmt = SVOp->getMaskElt(i); 1873 if (ShiftAmt < i) return -1; 1874 1875 ShiftAmt -= i; 1876 bool isLE = DAG.getDataLayout().isLittleEndian(); 1877 1878 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1879 // Check the rest of the elements to see if they are consecutive. 1880 for (++i; i != 16; ++i) 1881 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1882 return -1; 1883 } else if (ShuffleKind == 1) { 1884 // Check the rest of the elements to see if they are consecutive. 1885 for (++i; i != 16; ++i) 1886 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1887 return -1; 1888 } else 1889 return -1; 1890 1891 if (isLE) 1892 ShiftAmt = 16 - ShiftAmt; 1893 1894 return ShiftAmt; 1895 } 1896 1897 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1898 /// specifies a splat of a single element that is suitable for input to 1899 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1900 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1901 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1902 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1903 1904 // The consecutive indices need to specify an element, not part of two 1905 // different elements. So abandon ship early if this isn't the case. 1906 if (N->getMaskElt(0) % EltSize != 0) 1907 return false; 1908 1909 // This is a splat operation if each element of the permute is the same, and 1910 // if the value doesn't reference the second vector. 1911 unsigned ElementBase = N->getMaskElt(0); 1912 1913 // FIXME: Handle UNDEF elements too! 1914 if (ElementBase >= 16) 1915 return false; 1916 1917 // Check that the indices are consecutive, in the case of a multi-byte element 1918 // splatted with a v16i8 mask. 1919 for (unsigned i = 1; i != EltSize; ++i) 1920 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1921 return false; 1922 1923 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1924 if (N->getMaskElt(i) < 0) continue; 1925 for (unsigned j = 0; j != EltSize; ++j) 1926 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1927 return false; 1928 } 1929 return true; 1930 } 1931 1932 /// Check that the mask is shuffling N byte elements. Within each N byte 1933 /// element of the mask, the indices could be either in increasing or 1934 /// decreasing order as long as they are consecutive. 1935 /// \param[in] N the shuffle vector SD Node to analyze 1936 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1937 /// Word/DoubleWord/QuadWord). 1938 /// \param[in] StepLen the delta indices number among the N byte element, if 1939 /// the mask is in increasing/decreasing order then it is 1/-1. 1940 /// \return true iff the mask is shuffling N byte elements. 1941 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1942 int StepLen) { 1943 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1944 "Unexpected element width."); 1945 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1946 1947 unsigned NumOfElem = 16 / Width; 1948 unsigned MaskVal[16]; // Width is never greater than 16 1949 for (unsigned i = 0; i < NumOfElem; ++i) { 1950 MaskVal[0] = N->getMaskElt(i * Width); 1951 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1952 return false; 1953 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1954 return false; 1955 } 1956 1957 for (unsigned int j = 1; j < Width; ++j) { 1958 MaskVal[j] = N->getMaskElt(i * Width + j); 1959 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1960 return false; 1961 } 1962 } 1963 } 1964 1965 return true; 1966 } 1967 1968 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1969 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1970 if (!isNByteElemShuffleMask(N, 4, 1)) 1971 return false; 1972 1973 // Now we look at mask elements 0,4,8,12 1974 unsigned M0 = N->getMaskElt(0) / 4; 1975 unsigned M1 = N->getMaskElt(4) / 4; 1976 unsigned M2 = N->getMaskElt(8) / 4; 1977 unsigned M3 = N->getMaskElt(12) / 4; 1978 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1979 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1980 1981 // Below, let H and L be arbitrary elements of the shuffle mask 1982 // where H is in the range [4,7] and L is in the range [0,3]. 1983 // H, 1, 2, 3 or L, 5, 6, 7 1984 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1985 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1986 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1987 InsertAtByte = IsLE ? 12 : 0; 1988 Swap = M0 < 4; 1989 return true; 1990 } 1991 // 0, H, 2, 3 or 4, L, 6, 7 1992 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1993 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1994 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1995 InsertAtByte = IsLE ? 8 : 4; 1996 Swap = M1 < 4; 1997 return true; 1998 } 1999 // 0, 1, H, 3 or 4, 5, L, 7 2000 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2001 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2002 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2003 InsertAtByte = IsLE ? 4 : 8; 2004 Swap = M2 < 4; 2005 return true; 2006 } 2007 // 0, 1, 2, H or 4, 5, 6, L 2008 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2009 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2010 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2011 InsertAtByte = IsLE ? 0 : 12; 2012 Swap = M3 < 4; 2013 return true; 2014 } 2015 2016 // If both vector operands for the shuffle are the same vector, the mask will 2017 // contain only elements from the first one and the second one will be undef. 2018 if (N->getOperand(1).isUndef()) { 2019 ShiftElts = 0; 2020 Swap = true; 2021 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2022 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2023 InsertAtByte = IsLE ? 12 : 0; 2024 return true; 2025 } 2026 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2027 InsertAtByte = IsLE ? 8 : 4; 2028 return true; 2029 } 2030 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2031 InsertAtByte = IsLE ? 4 : 8; 2032 return true; 2033 } 2034 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2035 InsertAtByte = IsLE ? 0 : 12; 2036 return true; 2037 } 2038 } 2039 2040 return false; 2041 } 2042 2043 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2044 bool &Swap, bool IsLE) { 2045 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2046 // Ensure each byte index of the word is consecutive. 2047 if (!isNByteElemShuffleMask(N, 4, 1)) 2048 return false; 2049 2050 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2051 unsigned M0 = N->getMaskElt(0) / 4; 2052 unsigned M1 = N->getMaskElt(4) / 4; 2053 unsigned M2 = N->getMaskElt(8) / 4; 2054 unsigned M3 = N->getMaskElt(12) / 4; 2055 2056 // If both vector operands for the shuffle are the same vector, the mask will 2057 // contain only elements from the first one and the second one will be undef. 2058 if (N->getOperand(1).isUndef()) { 2059 assert(M0 < 4 && "Indexing into an undef vector?"); 2060 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2061 return false; 2062 2063 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2064 Swap = false; 2065 return true; 2066 } 2067 2068 // Ensure each word index of the ShuffleVector Mask is consecutive. 2069 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2070 return false; 2071 2072 if (IsLE) { 2073 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2074 // Input vectors don't need to be swapped if the leading element 2075 // of the result is one of the 3 left elements of the second vector 2076 // (or if there is no shift to be done at all). 2077 Swap = false; 2078 ShiftElts = (8 - M0) % 8; 2079 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2080 // Input vectors need to be swapped if the leading element 2081 // of the result is one of the 3 left elements of the first vector 2082 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2083 Swap = true; 2084 ShiftElts = (4 - M0) % 4; 2085 } 2086 2087 return true; 2088 } else { // BE 2089 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2090 // Input vectors don't need to be swapped if the leading element 2091 // of the result is one of the 4 elements of the first vector. 2092 Swap = false; 2093 ShiftElts = M0; 2094 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2095 // Input vectors need to be swapped if the leading element 2096 // of the result is one of the 4 elements of the right vector. 2097 Swap = true; 2098 ShiftElts = M0 - 4; 2099 } 2100 2101 return true; 2102 } 2103 } 2104 2105 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2106 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2107 2108 if (!isNByteElemShuffleMask(N, Width, -1)) 2109 return false; 2110 2111 for (int i = 0; i < 16; i += Width) 2112 if (N->getMaskElt(i) != i + Width - 1) 2113 return false; 2114 2115 return true; 2116 } 2117 2118 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2119 return isXXBRShuffleMaskHelper(N, 2); 2120 } 2121 2122 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2123 return isXXBRShuffleMaskHelper(N, 4); 2124 } 2125 2126 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2127 return isXXBRShuffleMaskHelper(N, 8); 2128 } 2129 2130 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2131 return isXXBRShuffleMaskHelper(N, 16); 2132 } 2133 2134 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2135 /// if the inputs to the instruction should be swapped and set \p DM to the 2136 /// value for the immediate. 2137 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2138 /// AND element 0 of the result comes from the first input (LE) or second input 2139 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2140 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2141 /// mask. 2142 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2143 bool &Swap, bool IsLE) { 2144 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2145 2146 // Ensure each byte index of the double word is consecutive. 2147 if (!isNByteElemShuffleMask(N, 8, 1)) 2148 return false; 2149 2150 unsigned M0 = N->getMaskElt(0) / 8; 2151 unsigned M1 = N->getMaskElt(8) / 8; 2152 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2153 2154 // If both vector operands for the shuffle are the same vector, the mask will 2155 // contain only elements from the first one and the second one will be undef. 2156 if (N->getOperand(1).isUndef()) { 2157 if ((M0 | M1) < 2) { 2158 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2159 Swap = false; 2160 return true; 2161 } else 2162 return false; 2163 } 2164 2165 if (IsLE) { 2166 if (M0 > 1 && M1 < 2) { 2167 Swap = false; 2168 } else if (M0 < 2 && M1 > 1) { 2169 M0 = (M0 + 2) % 4; 2170 M1 = (M1 + 2) % 4; 2171 Swap = true; 2172 } else 2173 return false; 2174 2175 // Note: if control flow comes here that means Swap is already set above 2176 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2177 return true; 2178 } else { // BE 2179 if (M0 < 2 && M1 > 1) { 2180 Swap = false; 2181 } else if (M0 > 1 && M1 < 2) { 2182 M0 = (M0 + 2) % 4; 2183 M1 = (M1 + 2) % 4; 2184 Swap = true; 2185 } else 2186 return false; 2187 2188 // Note: if control flow comes here that means Swap is already set above 2189 DM = (M0 << 1) + (M1 & 1); 2190 return true; 2191 } 2192 } 2193 2194 2195 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2196 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2197 /// elements are counted from the left of the vector register). 2198 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2199 SelectionDAG &DAG) { 2200 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2201 assert(isSplatShuffleMask(SVOp, EltSize)); 2202 if (DAG.getDataLayout().isLittleEndian()) 2203 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2204 else 2205 return SVOp->getMaskElt(0) / EltSize; 2206 } 2207 2208 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2209 /// by using a vspltis[bhw] instruction of the specified element size, return 2210 /// the constant being splatted. The ByteSize field indicates the number of 2211 /// bytes of each element [124] -> [bhw]. 2212 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2213 SDValue OpVal(nullptr, 0); 2214 2215 // If ByteSize of the splat is bigger than the element size of the 2216 // build_vector, then we have a case where we are checking for a splat where 2217 // multiple elements of the buildvector are folded together into a single 2218 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2219 unsigned EltSize = 16/N->getNumOperands(); 2220 if (EltSize < ByteSize) { 2221 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2222 SDValue UniquedVals[4]; 2223 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2224 2225 // See if all of the elements in the buildvector agree across. 2226 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2227 if (N->getOperand(i).isUndef()) continue; 2228 // If the element isn't a constant, bail fully out. 2229 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2230 2231 if (!UniquedVals[i&(Multiple-1)].getNode()) 2232 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2233 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2234 return SDValue(); // no match. 2235 } 2236 2237 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2238 // either constant or undef values that are identical for each chunk. See 2239 // if these chunks can form into a larger vspltis*. 2240 2241 // Check to see if all of the leading entries are either 0 or -1. If 2242 // neither, then this won't fit into the immediate field. 2243 bool LeadingZero = true; 2244 bool LeadingOnes = true; 2245 for (unsigned i = 0; i != Multiple-1; ++i) { 2246 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2247 2248 LeadingZero &= isNullConstant(UniquedVals[i]); 2249 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2250 } 2251 // Finally, check the least significant entry. 2252 if (LeadingZero) { 2253 if (!UniquedVals[Multiple-1].getNode()) 2254 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2255 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2256 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2257 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2258 } 2259 if (LeadingOnes) { 2260 if (!UniquedVals[Multiple-1].getNode()) 2261 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2262 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2263 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2264 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2265 } 2266 2267 return SDValue(); 2268 } 2269 2270 // Check to see if this buildvec has a single non-undef value in its elements. 2271 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2272 if (N->getOperand(i).isUndef()) continue; 2273 if (!OpVal.getNode()) 2274 OpVal = N->getOperand(i); 2275 else if (OpVal != N->getOperand(i)) 2276 return SDValue(); 2277 } 2278 2279 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2280 2281 unsigned ValSizeInBytes = EltSize; 2282 uint64_t Value = 0; 2283 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2284 Value = CN->getZExtValue(); 2285 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2286 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2287 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2288 } 2289 2290 // If the splat value is larger than the element value, then we can never do 2291 // this splat. The only case that we could fit the replicated bits into our 2292 // immediate field for would be zero, and we prefer to use vxor for it. 2293 if (ValSizeInBytes < ByteSize) return SDValue(); 2294 2295 // If the element value is larger than the splat value, check if it consists 2296 // of a repeated bit pattern of size ByteSize. 2297 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2298 return SDValue(); 2299 2300 // Properly sign extend the value. 2301 int MaskVal = SignExtend32(Value, ByteSize * 8); 2302 2303 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2304 if (MaskVal == 0) return SDValue(); 2305 2306 // Finally, if this value fits in a 5 bit sext field, return it 2307 if (SignExtend32<5>(MaskVal) == MaskVal) 2308 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2309 return SDValue(); 2310 } 2311 2312 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2313 /// amount, otherwise return -1. 2314 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2315 EVT VT = N->getValueType(0); 2316 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2317 return -1; 2318 2319 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2320 2321 // Find the first non-undef value in the shuffle mask. 2322 unsigned i; 2323 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2324 /*search*/; 2325 2326 if (i == 4) return -1; // all undef. 2327 2328 // Otherwise, check to see if the rest of the elements are consecutively 2329 // numbered from this value. 2330 unsigned ShiftAmt = SVOp->getMaskElt(i); 2331 if (ShiftAmt < i) return -1; 2332 ShiftAmt -= i; 2333 2334 // Check the rest of the elements to see if they are consecutive. 2335 for (++i; i != 4; ++i) 2336 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2337 return -1; 2338 2339 return ShiftAmt; 2340 } 2341 2342 //===----------------------------------------------------------------------===// 2343 // Addressing Mode Selection 2344 //===----------------------------------------------------------------------===// 2345 2346 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2347 /// or 64-bit immediate, and if the value can be accurately represented as a 2348 /// sign extension from a 16-bit value. If so, this returns true and the 2349 /// immediate. 2350 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2351 if (!isa<ConstantSDNode>(N)) 2352 return false; 2353 2354 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2355 if (N->getValueType(0) == MVT::i32) 2356 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2357 else 2358 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2359 } 2360 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2361 return isIntS16Immediate(Op.getNode(), Imm); 2362 } 2363 2364 2365 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2366 /// be represented as an indexed [r+r] operation. 2367 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2368 SDValue &Index, 2369 SelectionDAG &DAG) const { 2370 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2371 UI != E; ++UI) { 2372 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2373 if (Memop->getMemoryVT() == MVT::f64) { 2374 Base = N.getOperand(0); 2375 Index = N.getOperand(1); 2376 return true; 2377 } 2378 } 2379 } 2380 return false; 2381 } 2382 2383 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2384 /// can be represented as an indexed [r+r] operation. Returns false if it 2385 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2386 /// non-zero and N can be represented by a base register plus a signed 16-bit 2387 /// displacement, make a more precise judgement by checking (displacement % \p 2388 /// EncodingAlignment). 2389 bool PPCTargetLowering::SelectAddressRegReg( 2390 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2391 MaybeAlign EncodingAlignment) const { 2392 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2393 // a [pc+imm]. 2394 if (SelectAddressPCRel(N, Base)) 2395 return false; 2396 2397 int16_t Imm = 0; 2398 if (N.getOpcode() == ISD::ADD) { 2399 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2400 // SPE load/store can only handle 8-bit offsets. 2401 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2402 return true; 2403 if (isIntS16Immediate(N.getOperand(1), Imm) && 2404 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2405 return false; // r+i 2406 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2407 return false; // r+i 2408 2409 Base = N.getOperand(0); 2410 Index = N.getOperand(1); 2411 return true; 2412 } else if (N.getOpcode() == ISD::OR) { 2413 if (isIntS16Immediate(N.getOperand(1), Imm) && 2414 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2415 return false; // r+i can fold it if we can. 2416 2417 // If this is an or of disjoint bitfields, we can codegen this as an add 2418 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2419 // disjoint. 2420 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2421 2422 if (LHSKnown.Zero.getBoolValue()) { 2423 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2424 // If all of the bits are known zero on the LHS or RHS, the add won't 2425 // carry. 2426 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2427 Base = N.getOperand(0); 2428 Index = N.getOperand(1); 2429 return true; 2430 } 2431 } 2432 } 2433 2434 return false; 2435 } 2436 2437 // If we happen to be doing an i64 load or store into a stack slot that has 2438 // less than a 4-byte alignment, then the frame-index elimination may need to 2439 // use an indexed load or store instruction (because the offset may not be a 2440 // multiple of 4). The extra register needed to hold the offset comes from the 2441 // register scavenger, and it is possible that the scavenger will need to use 2442 // an emergency spill slot. As a result, we need to make sure that a spill slot 2443 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2444 // stack slot. 2445 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2446 // FIXME: This does not handle the LWA case. 2447 if (VT != MVT::i64) 2448 return; 2449 2450 // NOTE: We'll exclude negative FIs here, which come from argument 2451 // lowering, because there are no known test cases triggering this problem 2452 // using packed structures (or similar). We can remove this exclusion if 2453 // we find such a test case. The reason why this is so test-case driven is 2454 // because this entire 'fixup' is only to prevent crashes (from the 2455 // register scavenger) on not-really-valid inputs. For example, if we have: 2456 // %a = alloca i1 2457 // %b = bitcast i1* %a to i64* 2458 // store i64* a, i64 b 2459 // then the store should really be marked as 'align 1', but is not. If it 2460 // were marked as 'align 1' then the indexed form would have been 2461 // instruction-selected initially, and the problem this 'fixup' is preventing 2462 // won't happen regardless. 2463 if (FrameIdx < 0) 2464 return; 2465 2466 MachineFunction &MF = DAG.getMachineFunction(); 2467 MachineFrameInfo &MFI = MF.getFrameInfo(); 2468 2469 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2470 return; 2471 2472 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2473 FuncInfo->setHasNonRISpills(); 2474 } 2475 2476 /// Returns true if the address N can be represented by a base register plus 2477 /// a signed 16-bit displacement [r+imm], and if it is not better 2478 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2479 /// displacements that are multiples of that value. 2480 bool PPCTargetLowering::SelectAddressRegImm( 2481 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2482 MaybeAlign EncodingAlignment) const { 2483 // FIXME dl should come from parent load or store, not from address 2484 SDLoc dl(N); 2485 2486 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2487 // a [pc+imm]. 2488 if (SelectAddressPCRel(N, Base)) 2489 return false; 2490 2491 // If this can be more profitably realized as r+r, fail. 2492 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2493 return false; 2494 2495 if (N.getOpcode() == ISD::ADD) { 2496 int16_t imm = 0; 2497 if (isIntS16Immediate(N.getOperand(1), imm) && 2498 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2499 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2500 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2501 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2502 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2503 } else { 2504 Base = N.getOperand(0); 2505 } 2506 return true; // [r+i] 2507 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2508 // Match LOAD (ADD (X, Lo(G))). 2509 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2510 && "Cannot handle constant offsets yet!"); 2511 Disp = N.getOperand(1).getOperand(0); // The global address. 2512 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2513 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2514 Disp.getOpcode() == ISD::TargetConstantPool || 2515 Disp.getOpcode() == ISD::TargetJumpTable); 2516 Base = N.getOperand(0); 2517 return true; // [&g+r] 2518 } 2519 } else if (N.getOpcode() == ISD::OR) { 2520 int16_t imm = 0; 2521 if (isIntS16Immediate(N.getOperand(1), imm) && 2522 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2523 // If this is an or of disjoint bitfields, we can codegen this as an add 2524 // (for better address arithmetic) if the LHS and RHS of the OR are 2525 // provably disjoint. 2526 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2527 2528 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2529 // If all of the bits are known zero on the LHS or RHS, the add won't 2530 // carry. 2531 if (FrameIndexSDNode *FI = 2532 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2533 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2534 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2535 } else { 2536 Base = N.getOperand(0); 2537 } 2538 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2539 return true; 2540 } 2541 } 2542 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2543 // Loading from a constant address. 2544 2545 // If this address fits entirely in a 16-bit sext immediate field, codegen 2546 // this as "d, 0" 2547 int16_t Imm; 2548 if (isIntS16Immediate(CN, Imm) && 2549 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2550 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2551 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2552 CN->getValueType(0)); 2553 return true; 2554 } 2555 2556 // Handle 32-bit sext immediates with LIS + addr mode. 2557 if ((CN->getValueType(0) == MVT::i32 || 2558 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2559 (!EncodingAlignment || 2560 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2561 int Addr = (int)CN->getZExtValue(); 2562 2563 // Otherwise, break this down into an LIS + disp. 2564 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2565 2566 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2567 MVT::i32); 2568 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2569 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2570 return true; 2571 } 2572 } 2573 2574 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2575 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2576 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2577 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2578 } else 2579 Base = N; 2580 return true; // [r+0] 2581 } 2582 2583 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2584 /// represented as an indexed [r+r] operation. 2585 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2586 SDValue &Index, 2587 SelectionDAG &DAG) const { 2588 // Check to see if we can easily represent this as an [r+r] address. This 2589 // will fail if it thinks that the address is more profitably represented as 2590 // reg+imm, e.g. where imm = 0. 2591 if (SelectAddressRegReg(N, Base, Index, DAG)) 2592 return true; 2593 2594 // If the address is the result of an add, we will utilize the fact that the 2595 // address calculation includes an implicit add. However, we can reduce 2596 // register pressure if we do not materialize a constant just for use as the 2597 // index register. We only get rid of the add if it is not an add of a 2598 // value and a 16-bit signed constant and both have a single use. 2599 int16_t imm = 0; 2600 if (N.getOpcode() == ISD::ADD && 2601 (!isIntS16Immediate(N.getOperand(1), imm) || 2602 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2603 Base = N.getOperand(0); 2604 Index = N.getOperand(1); 2605 return true; 2606 } 2607 2608 // Otherwise, do it the hard way, using R0 as the base register. 2609 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2610 N.getValueType()); 2611 Index = N; 2612 return true; 2613 } 2614 2615 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2616 Ty *PCRelCand = dyn_cast<Ty>(N); 2617 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2618 } 2619 2620 /// Returns true if this address is a PC Relative address. 2621 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2622 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2623 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2624 // This is a materialize PC Relative node. Always select this as PC Relative. 2625 Base = N; 2626 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2627 return true; 2628 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2629 isValidPCRelNode<GlobalAddressSDNode>(N) || 2630 isValidPCRelNode<JumpTableSDNode>(N) || 2631 isValidPCRelNode<BlockAddressSDNode>(N)) 2632 return true; 2633 return false; 2634 } 2635 2636 /// Returns true if we should use a direct load into vector instruction 2637 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2638 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2639 2640 // If there are any other uses other than scalar to vector, then we should 2641 // keep it as a scalar load -> direct move pattern to prevent multiple 2642 // loads. 2643 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2644 if (!LD) 2645 return false; 2646 2647 EVT MemVT = LD->getMemoryVT(); 2648 if (!MemVT.isSimple()) 2649 return false; 2650 switch(MemVT.getSimpleVT().SimpleTy) { 2651 case MVT::i64: 2652 break; 2653 case MVT::i32: 2654 if (!ST.hasP8Vector()) 2655 return false; 2656 break; 2657 case MVT::i16: 2658 case MVT::i8: 2659 if (!ST.hasP9Vector()) 2660 return false; 2661 break; 2662 default: 2663 return false; 2664 } 2665 2666 SDValue LoadedVal(N, 0); 2667 if (!LoadedVal.hasOneUse()) 2668 return false; 2669 2670 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2671 UI != UE; ++UI) 2672 if (UI.getUse().get().getResNo() == 0 && 2673 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2674 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2675 return false; 2676 2677 return true; 2678 } 2679 2680 /// getPreIndexedAddressParts - returns true by value, base pointer and 2681 /// offset pointer and addressing mode by reference if the node's address 2682 /// can be legally represented as pre-indexed load / store address. 2683 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2684 SDValue &Offset, 2685 ISD::MemIndexedMode &AM, 2686 SelectionDAG &DAG) const { 2687 if (DisablePPCPreinc) return false; 2688 2689 bool isLoad = true; 2690 SDValue Ptr; 2691 EVT VT; 2692 unsigned Alignment; 2693 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2694 Ptr = LD->getBasePtr(); 2695 VT = LD->getMemoryVT(); 2696 Alignment = LD->getAlignment(); 2697 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2698 Ptr = ST->getBasePtr(); 2699 VT = ST->getMemoryVT(); 2700 Alignment = ST->getAlignment(); 2701 isLoad = false; 2702 } else 2703 return false; 2704 2705 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2706 // instructions because we can fold these into a more efficient instruction 2707 // instead, (such as LXSD). 2708 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2709 return false; 2710 } 2711 2712 // PowerPC doesn't have preinc load/store instructions for vectors 2713 if (VT.isVector()) 2714 return false; 2715 2716 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2717 // Common code will reject creating a pre-inc form if the base pointer 2718 // is a frame index, or if N is a store and the base pointer is either 2719 // the same as or a predecessor of the value being stored. Check for 2720 // those situations here, and try with swapped Base/Offset instead. 2721 bool Swap = false; 2722 2723 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2724 Swap = true; 2725 else if (!isLoad) { 2726 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2727 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2728 Swap = true; 2729 } 2730 2731 if (Swap) 2732 std::swap(Base, Offset); 2733 2734 AM = ISD::PRE_INC; 2735 return true; 2736 } 2737 2738 // LDU/STU can only handle immediates that are a multiple of 4. 2739 if (VT != MVT::i64) { 2740 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2741 return false; 2742 } else { 2743 // LDU/STU need an address with at least 4-byte alignment. 2744 if (Alignment < 4) 2745 return false; 2746 2747 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2748 return false; 2749 } 2750 2751 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2752 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2753 // sext i32 to i64 when addr mode is r+i. 2754 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2755 LD->getExtensionType() == ISD::SEXTLOAD && 2756 isa<ConstantSDNode>(Offset)) 2757 return false; 2758 } 2759 2760 AM = ISD::PRE_INC; 2761 return true; 2762 } 2763 2764 //===----------------------------------------------------------------------===// 2765 // LowerOperation implementation 2766 //===----------------------------------------------------------------------===// 2767 2768 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2769 /// and LoOpFlags to the target MO flags. 2770 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2771 unsigned &HiOpFlags, unsigned &LoOpFlags, 2772 const GlobalValue *GV = nullptr) { 2773 HiOpFlags = PPCII::MO_HA; 2774 LoOpFlags = PPCII::MO_LO; 2775 2776 // Don't use the pic base if not in PIC relocation model. 2777 if (IsPIC) { 2778 HiOpFlags |= PPCII::MO_PIC_FLAG; 2779 LoOpFlags |= PPCII::MO_PIC_FLAG; 2780 } 2781 } 2782 2783 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2784 SelectionDAG &DAG) { 2785 SDLoc DL(HiPart); 2786 EVT PtrVT = HiPart.getValueType(); 2787 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2788 2789 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2790 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2791 2792 // With PIC, the first instruction is actually "GR+hi(&G)". 2793 if (isPIC) 2794 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2795 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2796 2797 // Generate non-pic code that has direct accesses to the constant pool. 2798 // The address of the global is just (hi(&g)+lo(&g)). 2799 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2800 } 2801 2802 static void setUsesTOCBasePtr(MachineFunction &MF) { 2803 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2804 FuncInfo->setUsesTOCBasePtr(); 2805 } 2806 2807 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2808 setUsesTOCBasePtr(DAG.getMachineFunction()); 2809 } 2810 2811 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2812 SDValue GA) const { 2813 const bool Is64Bit = Subtarget.isPPC64(); 2814 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2815 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2816 : Subtarget.isAIXABI() 2817 ? DAG.getRegister(PPC::R2, VT) 2818 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2819 SDValue Ops[] = { GA, Reg }; 2820 return DAG.getMemIntrinsicNode( 2821 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2822 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2823 MachineMemOperand::MOLoad); 2824 } 2825 2826 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2827 SelectionDAG &DAG) const { 2828 EVT PtrVT = Op.getValueType(); 2829 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2830 const Constant *C = CP->getConstVal(); 2831 2832 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2833 // The actual address of the GlobalValue is stored in the TOC. 2834 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2835 if (Subtarget.isUsingPCRelativeCalls()) { 2836 SDLoc DL(CP); 2837 EVT Ty = getPointerTy(DAG.getDataLayout()); 2838 SDValue ConstPool = DAG.getTargetConstantPool( 2839 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2840 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2841 } 2842 setUsesTOCBasePtr(DAG); 2843 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2844 return getTOCEntry(DAG, SDLoc(CP), GA); 2845 } 2846 2847 unsigned MOHiFlag, MOLoFlag; 2848 bool IsPIC = isPositionIndependent(); 2849 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2850 2851 if (IsPIC && Subtarget.isSVR4ABI()) { 2852 SDValue GA = 2853 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2854 return getTOCEntry(DAG, SDLoc(CP), GA); 2855 } 2856 2857 SDValue CPIHi = 2858 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2859 SDValue CPILo = 2860 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2861 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2862 } 2863 2864 // For 64-bit PowerPC, prefer the more compact relative encodings. 2865 // This trades 32 bits per jump table entry for one or two instructions 2866 // on the jump site. 2867 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2868 if (isJumpTableRelative()) 2869 return MachineJumpTableInfo::EK_LabelDifference32; 2870 2871 return TargetLowering::getJumpTableEncoding(); 2872 } 2873 2874 bool PPCTargetLowering::isJumpTableRelative() const { 2875 if (UseAbsoluteJumpTables) 2876 return false; 2877 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2878 return true; 2879 return TargetLowering::isJumpTableRelative(); 2880 } 2881 2882 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2883 SelectionDAG &DAG) const { 2884 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2885 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2886 2887 switch (getTargetMachine().getCodeModel()) { 2888 case CodeModel::Small: 2889 case CodeModel::Medium: 2890 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2891 default: 2892 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2893 getPointerTy(DAG.getDataLayout())); 2894 } 2895 } 2896 2897 const MCExpr * 2898 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2899 unsigned JTI, 2900 MCContext &Ctx) const { 2901 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2902 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2903 2904 switch (getTargetMachine().getCodeModel()) { 2905 case CodeModel::Small: 2906 case CodeModel::Medium: 2907 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2908 default: 2909 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2910 } 2911 } 2912 2913 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2914 EVT PtrVT = Op.getValueType(); 2915 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2916 2917 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2918 if (Subtarget.isUsingPCRelativeCalls()) { 2919 SDLoc DL(JT); 2920 EVT Ty = getPointerTy(DAG.getDataLayout()); 2921 SDValue GA = 2922 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2923 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2924 return MatAddr; 2925 } 2926 2927 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2928 // The actual address of the GlobalValue is stored in the TOC. 2929 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2930 setUsesTOCBasePtr(DAG); 2931 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2932 return getTOCEntry(DAG, SDLoc(JT), GA); 2933 } 2934 2935 unsigned MOHiFlag, MOLoFlag; 2936 bool IsPIC = isPositionIndependent(); 2937 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2938 2939 if (IsPIC && Subtarget.isSVR4ABI()) { 2940 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2941 PPCII::MO_PIC_FLAG); 2942 return getTOCEntry(DAG, SDLoc(GA), GA); 2943 } 2944 2945 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2946 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2947 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2948 } 2949 2950 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2951 SelectionDAG &DAG) const { 2952 EVT PtrVT = Op.getValueType(); 2953 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2954 const BlockAddress *BA = BASDN->getBlockAddress(); 2955 2956 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2957 if (Subtarget.isUsingPCRelativeCalls()) { 2958 SDLoc DL(BASDN); 2959 EVT Ty = getPointerTy(DAG.getDataLayout()); 2960 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2961 PPCII::MO_PCREL_FLAG); 2962 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2963 return MatAddr; 2964 } 2965 2966 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2967 // The actual BlockAddress is stored in the TOC. 2968 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2969 setUsesTOCBasePtr(DAG); 2970 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2971 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2972 } 2973 2974 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2975 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2976 return getTOCEntry( 2977 DAG, SDLoc(BASDN), 2978 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2979 2980 unsigned MOHiFlag, MOLoFlag; 2981 bool IsPIC = isPositionIndependent(); 2982 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2983 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2984 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2985 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2986 } 2987 2988 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2989 SelectionDAG &DAG) const { 2990 // FIXME: TLS addresses currently use medium model code sequences, 2991 // which is the most useful form. Eventually support for small and 2992 // large models could be added if users need it, at the cost of 2993 // additional complexity. 2994 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 2995 report_fatal_error("Thread local storage is not supported with pc-relative" 2996 " addressing - please compile with -mno-pcrel"); 2997 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2998 if (DAG.getTarget().useEmulatedTLS()) 2999 return LowerToTLSEmulatedModel(GA, DAG); 3000 3001 SDLoc dl(GA); 3002 const GlobalValue *GV = GA->getGlobal(); 3003 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3004 bool is64bit = Subtarget.isPPC64(); 3005 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3006 PICLevel::Level picLevel = M->getPICLevel(); 3007 3008 const TargetMachine &TM = getTargetMachine(); 3009 TLSModel::Model Model = TM.getTLSModel(GV); 3010 3011 if (Model == TLSModel::LocalExec) { 3012 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3013 PPCII::MO_TPREL_HA); 3014 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3015 PPCII::MO_TPREL_LO); 3016 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3017 : DAG.getRegister(PPC::R2, MVT::i32); 3018 3019 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3020 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3021 } 3022 3023 if (Model == TLSModel::InitialExec) { 3024 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3025 SDValue TGA = DAG.getTargetGlobalAddress( 3026 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3027 SDValue TGATLS = DAG.getTargetGlobalAddress( 3028 GV, dl, PtrVT, 0, 3029 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3030 SDValue TPOffset; 3031 if (IsPCRel) { 3032 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3033 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3034 MachinePointerInfo()); 3035 } else { 3036 SDValue GOTPtr; 3037 if (is64bit) { 3038 setUsesTOCBasePtr(DAG); 3039 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3040 GOTPtr = 3041 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3042 } else { 3043 if (!TM.isPositionIndependent()) 3044 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3045 else if (picLevel == PICLevel::SmallPIC) 3046 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3047 else 3048 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3049 } 3050 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3051 } 3052 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3053 } 3054 3055 if (Model == TLSModel::GeneralDynamic) { 3056 if (Subtarget.isUsingPCRelativeCalls()) { 3057 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3058 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3059 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3060 } 3061 3062 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3063 SDValue GOTPtr; 3064 if (is64bit) { 3065 setUsesTOCBasePtr(DAG); 3066 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3067 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3068 GOTReg, TGA); 3069 } else { 3070 if (picLevel == PICLevel::SmallPIC) 3071 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3072 else 3073 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3074 } 3075 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3076 GOTPtr, TGA, TGA); 3077 } 3078 3079 if (Model == TLSModel::LocalDynamic) { 3080 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3081 SDValue GOTPtr; 3082 if (is64bit) { 3083 setUsesTOCBasePtr(DAG); 3084 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3085 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3086 GOTReg, TGA); 3087 } else { 3088 if (picLevel == PICLevel::SmallPIC) 3089 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3090 else 3091 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3092 } 3093 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3094 PtrVT, GOTPtr, TGA, TGA); 3095 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3096 PtrVT, TLSAddr, TGA); 3097 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3098 } 3099 3100 llvm_unreachable("Unknown TLS model!"); 3101 } 3102 3103 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3104 SelectionDAG &DAG) const { 3105 EVT PtrVT = Op.getValueType(); 3106 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3107 SDLoc DL(GSDN); 3108 const GlobalValue *GV = GSDN->getGlobal(); 3109 3110 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3111 // The actual address of the GlobalValue is stored in the TOC. 3112 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3113 if (Subtarget.isUsingPCRelativeCalls()) { 3114 EVT Ty = getPointerTy(DAG.getDataLayout()); 3115 if (isAccessedAsGotIndirect(Op)) { 3116 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3117 PPCII::MO_PCREL_FLAG | 3118 PPCII::MO_GOT_FLAG); 3119 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3120 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3121 MachinePointerInfo()); 3122 return Load; 3123 } else { 3124 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3125 PPCII::MO_PCREL_FLAG); 3126 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3127 } 3128 } 3129 setUsesTOCBasePtr(DAG); 3130 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3131 return getTOCEntry(DAG, DL, GA); 3132 } 3133 3134 unsigned MOHiFlag, MOLoFlag; 3135 bool IsPIC = isPositionIndependent(); 3136 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3137 3138 if (IsPIC && Subtarget.isSVR4ABI()) { 3139 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3140 GSDN->getOffset(), 3141 PPCII::MO_PIC_FLAG); 3142 return getTOCEntry(DAG, DL, GA); 3143 } 3144 3145 SDValue GAHi = 3146 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3147 SDValue GALo = 3148 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3149 3150 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3151 } 3152 3153 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3154 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3155 SDLoc dl(Op); 3156 3157 if (Op.getValueType() == MVT::v2i64) { 3158 // When the operands themselves are v2i64 values, we need to do something 3159 // special because VSX has no underlying comparison operations for these. 3160 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3161 // Equality can be handled by casting to the legal type for Altivec 3162 // comparisons, everything else needs to be expanded. 3163 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3164 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3165 DAG.getSetCC(dl, MVT::v4i32, 3166 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3167 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3168 CC)); 3169 } 3170 3171 return SDValue(); 3172 } 3173 3174 // We handle most of these in the usual way. 3175 return Op; 3176 } 3177 3178 // If we're comparing for equality to zero, expose the fact that this is 3179 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3180 // fold the new nodes. 3181 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3182 return V; 3183 3184 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3185 // Leave comparisons against 0 and -1 alone for now, since they're usually 3186 // optimized. FIXME: revisit this when we can custom lower all setcc 3187 // optimizations. 3188 if (C->isAllOnesValue() || C->isNullValue()) 3189 return SDValue(); 3190 } 3191 3192 // If we have an integer seteq/setne, turn it into a compare against zero 3193 // by xor'ing the rhs with the lhs, which is faster than setting a 3194 // condition register, reading it back out, and masking the correct bit. The 3195 // normal approach here uses sub to do this instead of xor. Using xor exposes 3196 // the result to other bit-twiddling opportunities. 3197 EVT LHSVT = Op.getOperand(0).getValueType(); 3198 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3199 EVT VT = Op.getValueType(); 3200 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3201 Op.getOperand(1)); 3202 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3203 } 3204 return SDValue(); 3205 } 3206 3207 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3208 SDNode *Node = Op.getNode(); 3209 EVT VT = Node->getValueType(0); 3210 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3211 SDValue InChain = Node->getOperand(0); 3212 SDValue VAListPtr = Node->getOperand(1); 3213 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3214 SDLoc dl(Node); 3215 3216 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3217 3218 // gpr_index 3219 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3220 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3221 InChain = GprIndex.getValue(1); 3222 3223 if (VT == MVT::i64) { 3224 // Check if GprIndex is even 3225 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3226 DAG.getConstant(1, dl, MVT::i32)); 3227 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3228 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3229 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3230 DAG.getConstant(1, dl, MVT::i32)); 3231 // Align GprIndex to be even if it isn't 3232 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3233 GprIndex); 3234 } 3235 3236 // fpr index is 1 byte after gpr 3237 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3238 DAG.getConstant(1, dl, MVT::i32)); 3239 3240 // fpr 3241 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3242 FprPtr, MachinePointerInfo(SV), MVT::i8); 3243 InChain = FprIndex.getValue(1); 3244 3245 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3246 DAG.getConstant(8, dl, MVT::i32)); 3247 3248 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3249 DAG.getConstant(4, dl, MVT::i32)); 3250 3251 // areas 3252 SDValue OverflowArea = 3253 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3254 InChain = OverflowArea.getValue(1); 3255 3256 SDValue RegSaveArea = 3257 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3258 InChain = RegSaveArea.getValue(1); 3259 3260 // select overflow_area if index > 8 3261 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3262 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3263 3264 // adjustment constant gpr_index * 4/8 3265 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3266 VT.isInteger() ? GprIndex : FprIndex, 3267 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3268 MVT::i32)); 3269 3270 // OurReg = RegSaveArea + RegConstant 3271 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3272 RegConstant); 3273 3274 // Floating types are 32 bytes into RegSaveArea 3275 if (VT.isFloatingPoint()) 3276 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3277 DAG.getConstant(32, dl, MVT::i32)); 3278 3279 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3280 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3281 VT.isInteger() ? GprIndex : FprIndex, 3282 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3283 MVT::i32)); 3284 3285 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3286 VT.isInteger() ? VAListPtr : FprPtr, 3287 MachinePointerInfo(SV), MVT::i8); 3288 3289 // determine if we should load from reg_save_area or overflow_area 3290 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3291 3292 // increase overflow_area by 4/8 if gpr/fpr > 8 3293 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3294 DAG.getConstant(VT.isInteger() ? 4 : 8, 3295 dl, MVT::i32)); 3296 3297 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3298 OverflowAreaPlusN); 3299 3300 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3301 MachinePointerInfo(), MVT::i32); 3302 3303 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3304 } 3305 3306 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3307 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3308 3309 // We have to copy the entire va_list struct: 3310 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3311 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3312 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3313 false, true, false, MachinePointerInfo(), 3314 MachinePointerInfo()); 3315 } 3316 3317 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3318 SelectionDAG &DAG) const { 3319 if (Subtarget.isAIXABI()) 3320 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3321 3322 return Op.getOperand(0); 3323 } 3324 3325 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3326 SelectionDAG &DAG) const { 3327 if (Subtarget.isAIXABI()) 3328 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3329 3330 SDValue Chain = Op.getOperand(0); 3331 SDValue Trmp = Op.getOperand(1); // trampoline 3332 SDValue FPtr = Op.getOperand(2); // nested function 3333 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3334 SDLoc dl(Op); 3335 3336 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3337 bool isPPC64 = (PtrVT == MVT::i64); 3338 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3339 3340 TargetLowering::ArgListTy Args; 3341 TargetLowering::ArgListEntry Entry; 3342 3343 Entry.Ty = IntPtrTy; 3344 Entry.Node = Trmp; Args.push_back(Entry); 3345 3346 // TrampSize == (isPPC64 ? 48 : 40); 3347 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3348 isPPC64 ? MVT::i64 : MVT::i32); 3349 Args.push_back(Entry); 3350 3351 Entry.Node = FPtr; Args.push_back(Entry); 3352 Entry.Node = Nest; Args.push_back(Entry); 3353 3354 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3355 TargetLowering::CallLoweringInfo CLI(DAG); 3356 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3357 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3358 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3359 3360 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3361 return CallResult.second; 3362 } 3363 3364 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3365 MachineFunction &MF = DAG.getMachineFunction(); 3366 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3367 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3368 3369 SDLoc dl(Op); 3370 3371 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3372 // vastart just stores the address of the VarArgsFrameIndex slot into the 3373 // memory location argument. 3374 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3375 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3376 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3377 MachinePointerInfo(SV)); 3378 } 3379 3380 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3381 // We suppose the given va_list is already allocated. 3382 // 3383 // typedef struct { 3384 // char gpr; /* index into the array of 8 GPRs 3385 // * stored in the register save area 3386 // * gpr=0 corresponds to r3, 3387 // * gpr=1 to r4, etc. 3388 // */ 3389 // char fpr; /* index into the array of 8 FPRs 3390 // * stored in the register save area 3391 // * fpr=0 corresponds to f1, 3392 // * fpr=1 to f2, etc. 3393 // */ 3394 // char *overflow_arg_area; 3395 // /* location on stack that holds 3396 // * the next overflow argument 3397 // */ 3398 // char *reg_save_area; 3399 // /* where r3:r10 and f1:f8 (if saved) 3400 // * are stored 3401 // */ 3402 // } va_list[1]; 3403 3404 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3405 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3406 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3407 PtrVT); 3408 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3409 PtrVT); 3410 3411 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3412 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3413 3414 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3415 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3416 3417 uint64_t FPROffset = 1; 3418 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3419 3420 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3421 3422 // Store first byte : number of int regs 3423 SDValue firstStore = 3424 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3425 MachinePointerInfo(SV), MVT::i8); 3426 uint64_t nextOffset = FPROffset; 3427 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3428 ConstFPROffset); 3429 3430 // Store second byte : number of float regs 3431 SDValue secondStore = 3432 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3433 MachinePointerInfo(SV, nextOffset), MVT::i8); 3434 nextOffset += StackOffset; 3435 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3436 3437 // Store second word : arguments given on stack 3438 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3439 MachinePointerInfo(SV, nextOffset)); 3440 nextOffset += FrameOffset; 3441 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3442 3443 // Store third word : arguments given in registers 3444 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3445 MachinePointerInfo(SV, nextOffset)); 3446 } 3447 3448 /// FPR - The set of FP registers that should be allocated for arguments 3449 /// on Darwin and AIX. 3450 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3451 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3452 PPC::F11, PPC::F12, PPC::F13}; 3453 3454 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3455 /// the stack. 3456 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3457 unsigned PtrByteSize) { 3458 unsigned ArgSize = ArgVT.getStoreSize(); 3459 if (Flags.isByVal()) 3460 ArgSize = Flags.getByValSize(); 3461 3462 // Round up to multiples of the pointer size, except for array members, 3463 // which are always packed. 3464 if (!Flags.isInConsecutiveRegs()) 3465 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3466 3467 return ArgSize; 3468 } 3469 3470 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3471 /// on the stack. 3472 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3473 ISD::ArgFlagsTy Flags, 3474 unsigned PtrByteSize) { 3475 Align Alignment(PtrByteSize); 3476 3477 // Altivec parameters are padded to a 16 byte boundary. 3478 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3479 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3480 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3481 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3482 Alignment = Align(16); 3483 3484 // ByVal parameters are aligned as requested. 3485 if (Flags.isByVal()) { 3486 auto BVAlign = Flags.getNonZeroByValAlign(); 3487 if (BVAlign > PtrByteSize) { 3488 if (BVAlign.value() % PtrByteSize != 0) 3489 llvm_unreachable( 3490 "ByVal alignment is not a multiple of the pointer size"); 3491 3492 Alignment = BVAlign; 3493 } 3494 } 3495 3496 // Array members are always packed to their original alignment. 3497 if (Flags.isInConsecutiveRegs()) { 3498 // If the array member was split into multiple registers, the first 3499 // needs to be aligned to the size of the full type. (Except for 3500 // ppcf128, which is only aligned as its f64 components.) 3501 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3502 Alignment = Align(OrigVT.getStoreSize()); 3503 else 3504 Alignment = Align(ArgVT.getStoreSize()); 3505 } 3506 3507 return Alignment; 3508 } 3509 3510 /// CalculateStackSlotUsed - Return whether this argument will use its 3511 /// stack slot (instead of being passed in registers). ArgOffset, 3512 /// AvailableFPRs, and AvailableVRs must hold the current argument 3513 /// position, and will be updated to account for this argument. 3514 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3515 unsigned PtrByteSize, unsigned LinkageSize, 3516 unsigned ParamAreaSize, unsigned &ArgOffset, 3517 unsigned &AvailableFPRs, 3518 unsigned &AvailableVRs) { 3519 bool UseMemory = false; 3520 3521 // Respect alignment of argument on the stack. 3522 Align Alignment = 3523 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3524 ArgOffset = alignTo(ArgOffset, Alignment); 3525 // If there's no space left in the argument save area, we must 3526 // use memory (this check also catches zero-sized arguments). 3527 if (ArgOffset >= LinkageSize + ParamAreaSize) 3528 UseMemory = true; 3529 3530 // Allocate argument on the stack. 3531 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3532 if (Flags.isInConsecutiveRegsLast()) 3533 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3534 // If we overran the argument save area, we must use memory 3535 // (this check catches arguments passed partially in memory) 3536 if (ArgOffset > LinkageSize + ParamAreaSize) 3537 UseMemory = true; 3538 3539 // However, if the argument is actually passed in an FPR or a VR, 3540 // we don't use memory after all. 3541 if (!Flags.isByVal()) { 3542 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3543 if (AvailableFPRs > 0) { 3544 --AvailableFPRs; 3545 return false; 3546 } 3547 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3548 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3549 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3550 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3551 if (AvailableVRs > 0) { 3552 --AvailableVRs; 3553 return false; 3554 } 3555 } 3556 3557 return UseMemory; 3558 } 3559 3560 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3561 /// ensure minimum alignment required for target. 3562 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3563 unsigned NumBytes) { 3564 return alignTo(NumBytes, Lowering->getStackAlign()); 3565 } 3566 3567 SDValue PPCTargetLowering::LowerFormalArguments( 3568 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3569 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3570 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3571 if (Subtarget.isAIXABI()) 3572 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3573 InVals); 3574 if (Subtarget.is64BitELFABI()) 3575 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3576 InVals); 3577 if (Subtarget.is32BitELFABI()) 3578 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3579 InVals); 3580 3581 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3582 InVals); 3583 } 3584 3585 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3586 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3587 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3588 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3589 3590 // 32-bit SVR4 ABI Stack Frame Layout: 3591 // +-----------------------------------+ 3592 // +--> | Back chain | 3593 // | +-----------------------------------+ 3594 // | | Floating-point register save area | 3595 // | +-----------------------------------+ 3596 // | | General register save area | 3597 // | +-----------------------------------+ 3598 // | | CR save word | 3599 // | +-----------------------------------+ 3600 // | | VRSAVE save word | 3601 // | +-----------------------------------+ 3602 // | | Alignment padding | 3603 // | +-----------------------------------+ 3604 // | | Vector register save area | 3605 // | +-----------------------------------+ 3606 // | | Local variable space | 3607 // | +-----------------------------------+ 3608 // | | Parameter list area | 3609 // | +-----------------------------------+ 3610 // | | LR save word | 3611 // | +-----------------------------------+ 3612 // SP--> +--- | Back chain | 3613 // +-----------------------------------+ 3614 // 3615 // Specifications: 3616 // System V Application Binary Interface PowerPC Processor Supplement 3617 // AltiVec Technology Programming Interface Manual 3618 3619 MachineFunction &MF = DAG.getMachineFunction(); 3620 MachineFrameInfo &MFI = MF.getFrameInfo(); 3621 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3622 3623 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3624 // Potential tail calls could cause overwriting of argument stack slots. 3625 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3626 (CallConv == CallingConv::Fast)); 3627 const Align PtrAlign(4); 3628 3629 // Assign locations to all of the incoming arguments. 3630 SmallVector<CCValAssign, 16> ArgLocs; 3631 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3632 *DAG.getContext()); 3633 3634 // Reserve space for the linkage area on the stack. 3635 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3636 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3637 if (useSoftFloat()) 3638 CCInfo.PreAnalyzeFormalArguments(Ins); 3639 3640 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3641 CCInfo.clearWasPPCF128(); 3642 3643 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3644 CCValAssign &VA = ArgLocs[i]; 3645 3646 // Arguments stored in registers. 3647 if (VA.isRegLoc()) { 3648 const TargetRegisterClass *RC; 3649 EVT ValVT = VA.getValVT(); 3650 3651 switch (ValVT.getSimpleVT().SimpleTy) { 3652 default: 3653 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3654 case MVT::i1: 3655 case MVT::i32: 3656 RC = &PPC::GPRCRegClass; 3657 break; 3658 case MVT::f32: 3659 if (Subtarget.hasP8Vector()) 3660 RC = &PPC::VSSRCRegClass; 3661 else if (Subtarget.hasSPE()) 3662 RC = &PPC::GPRCRegClass; 3663 else 3664 RC = &PPC::F4RCRegClass; 3665 break; 3666 case MVT::f64: 3667 if (Subtarget.hasVSX()) 3668 RC = &PPC::VSFRCRegClass; 3669 else if (Subtarget.hasSPE()) 3670 // SPE passes doubles in GPR pairs. 3671 RC = &PPC::GPRCRegClass; 3672 else 3673 RC = &PPC::F8RCRegClass; 3674 break; 3675 case MVT::v16i8: 3676 case MVT::v8i16: 3677 case MVT::v4i32: 3678 RC = &PPC::VRRCRegClass; 3679 break; 3680 case MVT::v4f32: 3681 RC = &PPC::VRRCRegClass; 3682 break; 3683 case MVT::v2f64: 3684 case MVT::v2i64: 3685 RC = &PPC::VRRCRegClass; 3686 break; 3687 } 3688 3689 SDValue ArgValue; 3690 // Transform the arguments stored in physical registers into 3691 // virtual ones. 3692 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3693 assert(i + 1 < e && "No second half of double precision argument"); 3694 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3695 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3696 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3697 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3698 if (!Subtarget.isLittleEndian()) 3699 std::swap (ArgValueLo, ArgValueHi); 3700 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3701 ArgValueHi); 3702 } else { 3703 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3704 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3705 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3706 if (ValVT == MVT::i1) 3707 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3708 } 3709 3710 InVals.push_back(ArgValue); 3711 } else { 3712 // Argument stored in memory. 3713 assert(VA.isMemLoc()); 3714 3715 // Get the extended size of the argument type in stack 3716 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3717 // Get the actual size of the argument type 3718 unsigned ObjSize = VA.getValVT().getStoreSize(); 3719 unsigned ArgOffset = VA.getLocMemOffset(); 3720 // Stack objects in PPC32 are right justified. 3721 ArgOffset += ArgSize - ObjSize; 3722 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3723 3724 // Create load nodes to retrieve arguments from the stack. 3725 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3726 InVals.push_back( 3727 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3728 } 3729 } 3730 3731 // Assign locations to all of the incoming aggregate by value arguments. 3732 // Aggregates passed by value are stored in the local variable space of the 3733 // caller's stack frame, right above the parameter list area. 3734 SmallVector<CCValAssign, 16> ByValArgLocs; 3735 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3736 ByValArgLocs, *DAG.getContext()); 3737 3738 // Reserve stack space for the allocations in CCInfo. 3739 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3740 3741 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3742 3743 // Area that is at least reserved in the caller of this function. 3744 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3745 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3746 3747 // Set the size that is at least reserved in caller of this function. Tail 3748 // call optimized function's reserved stack space needs to be aligned so that 3749 // taking the difference between two stack areas will result in an aligned 3750 // stack. 3751 MinReservedArea = 3752 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3753 FuncInfo->setMinReservedArea(MinReservedArea); 3754 3755 SmallVector<SDValue, 8> MemOps; 3756 3757 // If the function takes variable number of arguments, make a frame index for 3758 // the start of the first vararg value... for expansion of llvm.va_start. 3759 if (isVarArg) { 3760 static const MCPhysReg GPArgRegs[] = { 3761 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3762 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3763 }; 3764 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3765 3766 static const MCPhysReg FPArgRegs[] = { 3767 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3768 PPC::F8 3769 }; 3770 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3771 3772 if (useSoftFloat() || hasSPE()) 3773 NumFPArgRegs = 0; 3774 3775 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3776 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3777 3778 // Make room for NumGPArgRegs and NumFPArgRegs. 3779 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3780 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3781 3782 FuncInfo->setVarArgsStackOffset( 3783 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3784 CCInfo.getNextStackOffset(), true)); 3785 3786 FuncInfo->setVarArgsFrameIndex( 3787 MFI.CreateStackObject(Depth, Align(8), false)); 3788 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3789 3790 // The fixed integer arguments of a variadic function are stored to the 3791 // VarArgsFrameIndex on the stack so that they may be loaded by 3792 // dereferencing the result of va_next. 3793 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3794 // Get an existing live-in vreg, or add a new one. 3795 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3796 if (!VReg) 3797 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3798 3799 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3800 SDValue Store = 3801 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3802 MemOps.push_back(Store); 3803 // Increment the address by four for the next argument to store 3804 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3805 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3806 } 3807 3808 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3809 // is set. 3810 // The double arguments are stored to the VarArgsFrameIndex 3811 // on the stack. 3812 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3813 // Get an existing live-in vreg, or add a new one. 3814 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3815 if (!VReg) 3816 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3817 3818 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3819 SDValue Store = 3820 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3821 MemOps.push_back(Store); 3822 // Increment the address by eight for the next argument to store 3823 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3824 PtrVT); 3825 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3826 } 3827 } 3828 3829 if (!MemOps.empty()) 3830 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3831 3832 return Chain; 3833 } 3834 3835 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3836 // value to MVT::i64 and then truncate to the correct register size. 3837 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3838 EVT ObjectVT, SelectionDAG &DAG, 3839 SDValue ArgVal, 3840 const SDLoc &dl) const { 3841 if (Flags.isSExt()) 3842 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3843 DAG.getValueType(ObjectVT)); 3844 else if (Flags.isZExt()) 3845 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3846 DAG.getValueType(ObjectVT)); 3847 3848 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3849 } 3850 3851 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3852 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3853 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3854 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3855 // TODO: add description of PPC stack frame format, or at least some docs. 3856 // 3857 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3858 bool isLittleEndian = Subtarget.isLittleEndian(); 3859 MachineFunction &MF = DAG.getMachineFunction(); 3860 MachineFrameInfo &MFI = MF.getFrameInfo(); 3861 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3862 3863 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3864 "fastcc not supported on varargs functions"); 3865 3866 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3867 // Potential tail calls could cause overwriting of argument stack slots. 3868 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3869 (CallConv == CallingConv::Fast)); 3870 unsigned PtrByteSize = 8; 3871 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3872 3873 static const MCPhysReg GPR[] = { 3874 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3875 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3876 }; 3877 static const MCPhysReg VR[] = { 3878 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3879 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3880 }; 3881 3882 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3883 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3884 const unsigned Num_VR_Regs = array_lengthof(VR); 3885 3886 // Do a first pass over the arguments to determine whether the ABI 3887 // guarantees that our caller has allocated the parameter save area 3888 // on its stack frame. In the ELFv1 ABI, this is always the case; 3889 // in the ELFv2 ABI, it is true if this is a vararg function or if 3890 // any parameter is located in a stack slot. 3891 3892 bool HasParameterArea = !isELFv2ABI || isVarArg; 3893 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3894 unsigned NumBytes = LinkageSize; 3895 unsigned AvailableFPRs = Num_FPR_Regs; 3896 unsigned AvailableVRs = Num_VR_Regs; 3897 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3898 if (Ins[i].Flags.isNest()) 3899 continue; 3900 3901 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3902 PtrByteSize, LinkageSize, ParamAreaSize, 3903 NumBytes, AvailableFPRs, AvailableVRs)) 3904 HasParameterArea = true; 3905 } 3906 3907 // Add DAG nodes to load the arguments or copy them out of registers. On 3908 // entry to a function on PPC, the arguments start after the linkage area, 3909 // although the first ones are often in registers. 3910 3911 unsigned ArgOffset = LinkageSize; 3912 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3913 SmallVector<SDValue, 8> MemOps; 3914 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3915 unsigned CurArgIdx = 0; 3916 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3917 SDValue ArgVal; 3918 bool needsLoad = false; 3919 EVT ObjectVT = Ins[ArgNo].VT; 3920 EVT OrigVT = Ins[ArgNo].ArgVT; 3921 unsigned ObjSize = ObjectVT.getStoreSize(); 3922 unsigned ArgSize = ObjSize; 3923 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3924 if (Ins[ArgNo].isOrigArg()) { 3925 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3926 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3927 } 3928 // We re-align the argument offset for each argument, except when using the 3929 // fast calling convention, when we need to make sure we do that only when 3930 // we'll actually use a stack slot. 3931 unsigned CurArgOffset; 3932 Align Alignment; 3933 auto ComputeArgOffset = [&]() { 3934 /* Respect alignment of argument on the stack. */ 3935 Alignment = 3936 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3937 ArgOffset = alignTo(ArgOffset, Alignment); 3938 CurArgOffset = ArgOffset; 3939 }; 3940 3941 if (CallConv != CallingConv::Fast) { 3942 ComputeArgOffset(); 3943 3944 /* Compute GPR index associated with argument offset. */ 3945 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3946 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3947 } 3948 3949 // FIXME the codegen can be much improved in some cases. 3950 // We do not have to keep everything in memory. 3951 if (Flags.isByVal()) { 3952 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3953 3954 if (CallConv == CallingConv::Fast) 3955 ComputeArgOffset(); 3956 3957 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3958 ObjSize = Flags.getByValSize(); 3959 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3960 // Empty aggregate parameters do not take up registers. Examples: 3961 // struct { } a; 3962 // union { } b; 3963 // int c[0]; 3964 // etc. However, we have to provide a place-holder in InVals, so 3965 // pretend we have an 8-byte item at the current address for that 3966 // purpose. 3967 if (!ObjSize) { 3968 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3969 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3970 InVals.push_back(FIN); 3971 continue; 3972 } 3973 3974 // Create a stack object covering all stack doublewords occupied 3975 // by the argument. If the argument is (fully or partially) on 3976 // the stack, or if the argument is fully in registers but the 3977 // caller has allocated the parameter save anyway, we can refer 3978 // directly to the caller's stack frame. Otherwise, create a 3979 // local copy in our own frame. 3980 int FI; 3981 if (HasParameterArea || 3982 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3983 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3984 else 3985 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3986 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3987 3988 // Handle aggregates smaller than 8 bytes. 3989 if (ObjSize < PtrByteSize) { 3990 // The value of the object is its address, which differs from the 3991 // address of the enclosing doubleword on big-endian systems. 3992 SDValue Arg = FIN; 3993 if (!isLittleEndian) { 3994 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3995 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3996 } 3997 InVals.push_back(Arg); 3998 3999 if (GPR_idx != Num_GPR_Regs) { 4000 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4001 FuncInfo->addLiveInAttr(VReg, Flags); 4002 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4003 SDValue Store; 4004 4005 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 4006 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 4007 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 4008 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4009 MachinePointerInfo(&*FuncArg), ObjType); 4010 } else { 4011 // For sizes that don't fit a truncating store (3, 5, 6, 7), 4012 // store the whole register as-is to the parameter save area 4013 // slot. 4014 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4015 MachinePointerInfo(&*FuncArg)); 4016 } 4017 4018 MemOps.push_back(Store); 4019 } 4020 // Whether we copied from a register or not, advance the offset 4021 // into the parameter save area by a full doubleword. 4022 ArgOffset += PtrByteSize; 4023 continue; 4024 } 4025 4026 // The value of the object is its address, which is the address of 4027 // its first stack doubleword. 4028 InVals.push_back(FIN); 4029 4030 // Store whatever pieces of the object are in registers to memory. 4031 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4032 if (GPR_idx == Num_GPR_Regs) 4033 break; 4034 4035 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4036 FuncInfo->addLiveInAttr(VReg, Flags); 4037 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4038 SDValue Addr = FIN; 4039 if (j) { 4040 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4041 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4042 } 4043 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 4044 MachinePointerInfo(&*FuncArg, j)); 4045 MemOps.push_back(Store); 4046 ++GPR_idx; 4047 } 4048 ArgOffset += ArgSize; 4049 continue; 4050 } 4051 4052 switch (ObjectVT.getSimpleVT().SimpleTy) { 4053 default: llvm_unreachable("Unhandled argument type!"); 4054 case MVT::i1: 4055 case MVT::i32: 4056 case MVT::i64: 4057 if (Flags.isNest()) { 4058 // The 'nest' parameter, if any, is passed in R11. 4059 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4060 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4061 4062 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4063 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4064 4065 break; 4066 } 4067 4068 // These can be scalar arguments or elements of an integer array type 4069 // passed directly. Clang may use those instead of "byval" aggregate 4070 // types to avoid forcing arguments to memory unnecessarily. 4071 if (GPR_idx != Num_GPR_Regs) { 4072 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4073 FuncInfo->addLiveInAttr(VReg, Flags); 4074 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4075 4076 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4077 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4078 // value to MVT::i64 and then truncate to the correct register size. 4079 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4080 } else { 4081 if (CallConv == CallingConv::Fast) 4082 ComputeArgOffset(); 4083 4084 needsLoad = true; 4085 ArgSize = PtrByteSize; 4086 } 4087 if (CallConv != CallingConv::Fast || needsLoad) 4088 ArgOffset += 8; 4089 break; 4090 4091 case MVT::f32: 4092 case MVT::f64: 4093 // These can be scalar arguments or elements of a float array type 4094 // passed directly. The latter are used to implement ELFv2 homogenous 4095 // float aggregates. 4096 if (FPR_idx != Num_FPR_Regs) { 4097 unsigned VReg; 4098 4099 if (ObjectVT == MVT::f32) 4100 VReg = MF.addLiveIn(FPR[FPR_idx], 4101 Subtarget.hasP8Vector() 4102 ? &PPC::VSSRCRegClass 4103 : &PPC::F4RCRegClass); 4104 else 4105 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4106 ? &PPC::VSFRCRegClass 4107 : &PPC::F8RCRegClass); 4108 4109 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4110 ++FPR_idx; 4111 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4112 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4113 // once we support fp <-> gpr moves. 4114 4115 // This can only ever happen in the presence of f32 array types, 4116 // since otherwise we never run out of FPRs before running out 4117 // of GPRs. 4118 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4119 FuncInfo->addLiveInAttr(VReg, Flags); 4120 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4121 4122 if (ObjectVT == MVT::f32) { 4123 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4124 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4125 DAG.getConstant(32, dl, MVT::i32)); 4126 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4127 } 4128 4129 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4130 } else { 4131 if (CallConv == CallingConv::Fast) 4132 ComputeArgOffset(); 4133 4134 needsLoad = true; 4135 } 4136 4137 // When passing an array of floats, the array occupies consecutive 4138 // space in the argument area; only round up to the next doubleword 4139 // at the end of the array. Otherwise, each float takes 8 bytes. 4140 if (CallConv != CallingConv::Fast || needsLoad) { 4141 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4142 ArgOffset += ArgSize; 4143 if (Flags.isInConsecutiveRegsLast()) 4144 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4145 } 4146 break; 4147 case MVT::v4f32: 4148 case MVT::v4i32: 4149 case MVT::v8i16: 4150 case MVT::v16i8: 4151 case MVT::v2f64: 4152 case MVT::v2i64: 4153 case MVT::v1i128: 4154 case MVT::f128: 4155 // These can be scalar arguments or elements of a vector array type 4156 // passed directly. The latter are used to implement ELFv2 homogenous 4157 // vector aggregates. 4158 if (VR_idx != Num_VR_Regs) { 4159 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4160 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4161 ++VR_idx; 4162 } else { 4163 if (CallConv == CallingConv::Fast) 4164 ComputeArgOffset(); 4165 needsLoad = true; 4166 } 4167 if (CallConv != CallingConv::Fast || needsLoad) 4168 ArgOffset += 16; 4169 break; 4170 } 4171 4172 // We need to load the argument to a virtual register if we determined 4173 // above that we ran out of physical registers of the appropriate type. 4174 if (needsLoad) { 4175 if (ObjSize < ArgSize && !isLittleEndian) 4176 CurArgOffset += ArgSize - ObjSize; 4177 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4178 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4179 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4180 } 4181 4182 InVals.push_back(ArgVal); 4183 } 4184 4185 // Area that is at least reserved in the caller of this function. 4186 unsigned MinReservedArea; 4187 if (HasParameterArea) 4188 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4189 else 4190 MinReservedArea = LinkageSize; 4191 4192 // Set the size that is at least reserved in caller of this function. Tail 4193 // call optimized functions' reserved stack space needs to be aligned so that 4194 // taking the difference between two stack areas will result in an aligned 4195 // stack. 4196 MinReservedArea = 4197 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4198 FuncInfo->setMinReservedArea(MinReservedArea); 4199 4200 // If the function takes variable number of arguments, make a frame index for 4201 // the start of the first vararg value... for expansion of llvm.va_start. 4202 // On ELFv2ABI spec, it writes: 4203 // C programs that are intended to be *portable* across different compilers 4204 // and architectures must use the header file <stdarg.h> to deal with variable 4205 // argument lists. 4206 if (isVarArg && MFI.hasVAStart()) { 4207 int Depth = ArgOffset; 4208 4209 FuncInfo->setVarArgsFrameIndex( 4210 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4211 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4212 4213 // If this function is vararg, store any remaining integer argument regs 4214 // to their spots on the stack so that they may be loaded by dereferencing 4215 // the result of va_next. 4216 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4217 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4218 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4219 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4220 SDValue Store = 4221 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4222 MemOps.push_back(Store); 4223 // Increment the address by four for the next argument to store 4224 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4225 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4226 } 4227 } 4228 4229 if (!MemOps.empty()) 4230 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4231 4232 return Chain; 4233 } 4234 4235 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4236 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4237 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4238 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4239 // TODO: add description of PPC stack frame format, or at least some docs. 4240 // 4241 MachineFunction &MF = DAG.getMachineFunction(); 4242 MachineFrameInfo &MFI = MF.getFrameInfo(); 4243 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4244 4245 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4246 bool isPPC64 = PtrVT == MVT::i64; 4247 // Potential tail calls could cause overwriting of argument stack slots. 4248 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4249 (CallConv == CallingConv::Fast)); 4250 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4251 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4252 unsigned ArgOffset = LinkageSize; 4253 // Area that is at least reserved in caller of this function. 4254 unsigned MinReservedArea = ArgOffset; 4255 4256 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4257 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4258 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4259 }; 4260 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4261 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4262 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4263 }; 4264 static const MCPhysReg VR[] = { 4265 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4266 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4267 }; 4268 4269 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4270 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4271 const unsigned Num_VR_Regs = array_lengthof( VR); 4272 4273 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4274 4275 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4276 4277 // In 32-bit non-varargs functions, the stack space for vectors is after the 4278 // stack space for non-vectors. We do not use this space unless we have 4279 // too many vectors to fit in registers, something that only occurs in 4280 // constructed examples:), but we have to walk the arglist to figure 4281 // that out...for the pathological case, compute VecArgOffset as the 4282 // start of the vector parameter area. Computing VecArgOffset is the 4283 // entire point of the following loop. 4284 unsigned VecArgOffset = ArgOffset; 4285 if (!isVarArg && !isPPC64) { 4286 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4287 ++ArgNo) { 4288 EVT ObjectVT = Ins[ArgNo].VT; 4289 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4290 4291 if (Flags.isByVal()) { 4292 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4293 unsigned ObjSize = Flags.getByValSize(); 4294 unsigned ArgSize = 4295 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4296 VecArgOffset += ArgSize; 4297 continue; 4298 } 4299 4300 switch(ObjectVT.getSimpleVT().SimpleTy) { 4301 default: llvm_unreachable("Unhandled argument type!"); 4302 case MVT::i1: 4303 case MVT::i32: 4304 case MVT::f32: 4305 VecArgOffset += 4; 4306 break; 4307 case MVT::i64: // PPC64 4308 case MVT::f64: 4309 // FIXME: We are guaranteed to be !isPPC64 at this point. 4310 // Does MVT::i64 apply? 4311 VecArgOffset += 8; 4312 break; 4313 case MVT::v4f32: 4314 case MVT::v4i32: 4315 case MVT::v8i16: 4316 case MVT::v16i8: 4317 // Nothing to do, we're only looking at Nonvector args here. 4318 break; 4319 } 4320 } 4321 } 4322 // We've found where the vector parameter area in memory is. Skip the 4323 // first 12 parameters; these don't use that memory. 4324 VecArgOffset = ((VecArgOffset+15)/16)*16; 4325 VecArgOffset += 12*16; 4326 4327 // Add DAG nodes to load the arguments or copy them out of registers. On 4328 // entry to a function on PPC, the arguments start after the linkage area, 4329 // although the first ones are often in registers. 4330 4331 SmallVector<SDValue, 8> MemOps; 4332 unsigned nAltivecParamsAtEnd = 0; 4333 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4334 unsigned CurArgIdx = 0; 4335 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4336 SDValue ArgVal; 4337 bool needsLoad = false; 4338 EVT ObjectVT = Ins[ArgNo].VT; 4339 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4340 unsigned ArgSize = ObjSize; 4341 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4342 if (Ins[ArgNo].isOrigArg()) { 4343 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4344 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4345 } 4346 unsigned CurArgOffset = ArgOffset; 4347 4348 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4349 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4350 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4351 if (isVarArg || isPPC64) { 4352 MinReservedArea = ((MinReservedArea+15)/16)*16; 4353 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4354 Flags, 4355 PtrByteSize); 4356 } else nAltivecParamsAtEnd++; 4357 } else 4358 // Calculate min reserved area. 4359 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4360 Flags, 4361 PtrByteSize); 4362 4363 // FIXME the codegen can be much improved in some cases. 4364 // We do not have to keep everything in memory. 4365 if (Flags.isByVal()) { 4366 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4367 4368 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4369 ObjSize = Flags.getByValSize(); 4370 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4371 // Objects of size 1 and 2 are right justified, everything else is 4372 // left justified. This means the memory address is adjusted forwards. 4373 if (ObjSize==1 || ObjSize==2) { 4374 CurArgOffset = CurArgOffset + (4 - ObjSize); 4375 } 4376 // The value of the object is its address. 4377 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4378 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4379 InVals.push_back(FIN); 4380 if (ObjSize==1 || ObjSize==2) { 4381 if (GPR_idx != Num_GPR_Regs) { 4382 unsigned VReg; 4383 if (isPPC64) 4384 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4385 else 4386 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4387 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4388 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4389 SDValue Store = 4390 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4391 MachinePointerInfo(&*FuncArg), ObjType); 4392 MemOps.push_back(Store); 4393 ++GPR_idx; 4394 } 4395 4396 ArgOffset += PtrByteSize; 4397 4398 continue; 4399 } 4400 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4401 // Store whatever pieces of the object are in registers 4402 // to memory. ArgOffset will be the address of the beginning 4403 // of the object. 4404 if (GPR_idx != Num_GPR_Regs) { 4405 unsigned VReg; 4406 if (isPPC64) 4407 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4408 else 4409 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4410 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4411 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4412 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4413 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4414 MachinePointerInfo(&*FuncArg, j)); 4415 MemOps.push_back(Store); 4416 ++GPR_idx; 4417 ArgOffset += PtrByteSize; 4418 } else { 4419 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4420 break; 4421 } 4422 } 4423 continue; 4424 } 4425 4426 switch (ObjectVT.getSimpleVT().SimpleTy) { 4427 default: llvm_unreachable("Unhandled argument type!"); 4428 case MVT::i1: 4429 case MVT::i32: 4430 if (!isPPC64) { 4431 if (GPR_idx != Num_GPR_Regs) { 4432 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4433 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4434 4435 if (ObjectVT == MVT::i1) 4436 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4437 4438 ++GPR_idx; 4439 } else { 4440 needsLoad = true; 4441 ArgSize = PtrByteSize; 4442 } 4443 // All int arguments reserve stack space in the Darwin ABI. 4444 ArgOffset += PtrByteSize; 4445 break; 4446 } 4447 LLVM_FALLTHROUGH; 4448 case MVT::i64: // PPC64 4449 if (GPR_idx != Num_GPR_Regs) { 4450 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4451 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4452 4453 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4454 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4455 // value to MVT::i64 and then truncate to the correct register size. 4456 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4457 4458 ++GPR_idx; 4459 } else { 4460 needsLoad = true; 4461 ArgSize = PtrByteSize; 4462 } 4463 // All int arguments reserve stack space in the Darwin ABI. 4464 ArgOffset += 8; 4465 break; 4466 4467 case MVT::f32: 4468 case MVT::f64: 4469 // Every 4 bytes of argument space consumes one of the GPRs available for 4470 // argument passing. 4471 if (GPR_idx != Num_GPR_Regs) { 4472 ++GPR_idx; 4473 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4474 ++GPR_idx; 4475 } 4476 if (FPR_idx != Num_FPR_Regs) { 4477 unsigned VReg; 4478 4479 if (ObjectVT == MVT::f32) 4480 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4481 else 4482 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4483 4484 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4485 ++FPR_idx; 4486 } else { 4487 needsLoad = true; 4488 } 4489 4490 // All FP arguments reserve stack space in the Darwin ABI. 4491 ArgOffset += isPPC64 ? 8 : ObjSize; 4492 break; 4493 case MVT::v4f32: 4494 case MVT::v4i32: 4495 case MVT::v8i16: 4496 case MVT::v16i8: 4497 // Note that vector arguments in registers don't reserve stack space, 4498 // except in varargs functions. 4499 if (VR_idx != Num_VR_Regs) { 4500 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4501 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4502 if (isVarArg) { 4503 while ((ArgOffset % 16) != 0) { 4504 ArgOffset += PtrByteSize; 4505 if (GPR_idx != Num_GPR_Regs) 4506 GPR_idx++; 4507 } 4508 ArgOffset += 16; 4509 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4510 } 4511 ++VR_idx; 4512 } else { 4513 if (!isVarArg && !isPPC64) { 4514 // Vectors go after all the nonvectors. 4515 CurArgOffset = VecArgOffset; 4516 VecArgOffset += 16; 4517 } else { 4518 // Vectors are aligned. 4519 ArgOffset = ((ArgOffset+15)/16)*16; 4520 CurArgOffset = ArgOffset; 4521 ArgOffset += 16; 4522 } 4523 needsLoad = true; 4524 } 4525 break; 4526 } 4527 4528 // We need to load the argument to a virtual register if we determined above 4529 // that we ran out of physical registers of the appropriate type. 4530 if (needsLoad) { 4531 int FI = MFI.CreateFixedObject(ObjSize, 4532 CurArgOffset + (ArgSize - ObjSize), 4533 isImmutable); 4534 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4535 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4536 } 4537 4538 InVals.push_back(ArgVal); 4539 } 4540 4541 // Allow for Altivec parameters at the end, if needed. 4542 if (nAltivecParamsAtEnd) { 4543 MinReservedArea = ((MinReservedArea+15)/16)*16; 4544 MinReservedArea += 16*nAltivecParamsAtEnd; 4545 } 4546 4547 // Area that is at least reserved in the caller of this function. 4548 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4549 4550 // Set the size that is at least reserved in caller of this function. Tail 4551 // call optimized functions' reserved stack space needs to be aligned so that 4552 // taking the difference between two stack areas will result in an aligned 4553 // stack. 4554 MinReservedArea = 4555 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4556 FuncInfo->setMinReservedArea(MinReservedArea); 4557 4558 // If the function takes variable number of arguments, make a frame index for 4559 // the start of the first vararg value... for expansion of llvm.va_start. 4560 if (isVarArg) { 4561 int Depth = ArgOffset; 4562 4563 FuncInfo->setVarArgsFrameIndex( 4564 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4565 Depth, true)); 4566 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4567 4568 // If this function is vararg, store any remaining integer argument regs 4569 // to their spots on the stack so that they may be loaded by dereferencing 4570 // the result of va_next. 4571 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4572 unsigned VReg; 4573 4574 if (isPPC64) 4575 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4576 else 4577 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4578 4579 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4580 SDValue Store = 4581 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4582 MemOps.push_back(Store); 4583 // Increment the address by four for the next argument to store 4584 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4585 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4586 } 4587 } 4588 4589 if (!MemOps.empty()) 4590 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4591 4592 return Chain; 4593 } 4594 4595 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4596 /// adjusted to accommodate the arguments for the tailcall. 4597 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4598 unsigned ParamSize) { 4599 4600 if (!isTailCall) return 0; 4601 4602 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4603 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4604 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4605 // Remember only if the new adjustment is bigger. 4606 if (SPDiff < FI->getTailCallSPDelta()) 4607 FI->setTailCallSPDelta(SPDiff); 4608 4609 return SPDiff; 4610 } 4611 4612 static bool isFunctionGlobalAddress(SDValue Callee); 4613 4614 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4615 const TargetMachine &TM) { 4616 // It does not make sense to call callsShareTOCBase() with a caller that 4617 // is PC Relative since PC Relative callers do not have a TOC. 4618 #ifndef NDEBUG 4619 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4620 assert(!STICaller->isUsingPCRelativeCalls() && 4621 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4622 #endif 4623 4624 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4625 // don't have enough information to determine if the caller and callee share 4626 // the same TOC base, so we have to pessimistically assume they don't for 4627 // correctness. 4628 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4629 if (!G) 4630 return false; 4631 4632 const GlobalValue *GV = G->getGlobal(); 4633 4634 // If the callee is preemptable, then the static linker will use a plt-stub 4635 // which saves the toc to the stack, and needs a nop after the call 4636 // instruction to convert to a toc-restore. 4637 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4638 return false; 4639 4640 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4641 // We may need a TOC restore in the situation where the caller requires a 4642 // valid TOC but the callee is PC Relative and does not. 4643 const Function *F = dyn_cast<Function>(GV); 4644 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4645 4646 // If we have an Alias we can try to get the function from there. 4647 if (Alias) { 4648 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4649 F = dyn_cast<Function>(GlobalObj); 4650 } 4651 4652 // If we still have no valid function pointer we do not have enough 4653 // information to determine if the callee uses PC Relative calls so we must 4654 // assume that it does. 4655 if (!F) 4656 return false; 4657 4658 // If the callee uses PC Relative we cannot guarantee that the callee won't 4659 // clobber the TOC of the caller and so we must assume that the two 4660 // functions do not share a TOC base. 4661 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4662 if (STICallee->isUsingPCRelativeCalls()) 4663 return false; 4664 4665 // The medium and large code models are expected to provide a sufficiently 4666 // large TOC to provide all data addressing needs of a module with a 4667 // single TOC. 4668 if (CodeModel::Medium == TM.getCodeModel() || 4669 CodeModel::Large == TM.getCodeModel()) 4670 return true; 4671 4672 // Otherwise we need to ensure callee and caller are in the same section, 4673 // since the linker may allocate multiple TOCs, and we don't know which 4674 // sections will belong to the same TOC base. 4675 if (!GV->isStrongDefinitionForLinker()) 4676 return false; 4677 4678 // Any explicitly-specified sections and section prefixes must also match. 4679 // Also, if we're using -ffunction-sections, then each function is always in 4680 // a different section (the same is true for COMDAT functions). 4681 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4682 GV->getSection() != Caller->getSection()) 4683 return false; 4684 if (const auto *F = dyn_cast<Function>(GV)) { 4685 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4686 return false; 4687 } 4688 4689 return true; 4690 } 4691 4692 static bool 4693 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4694 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4695 assert(Subtarget.is64BitELFABI()); 4696 4697 const unsigned PtrByteSize = 8; 4698 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4699 4700 static const MCPhysReg GPR[] = { 4701 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4702 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4703 }; 4704 static const MCPhysReg VR[] = { 4705 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4706 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4707 }; 4708 4709 const unsigned NumGPRs = array_lengthof(GPR); 4710 const unsigned NumFPRs = 13; 4711 const unsigned NumVRs = array_lengthof(VR); 4712 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4713 4714 unsigned NumBytes = LinkageSize; 4715 unsigned AvailableFPRs = NumFPRs; 4716 unsigned AvailableVRs = NumVRs; 4717 4718 for (const ISD::OutputArg& Param : Outs) { 4719 if (Param.Flags.isNest()) continue; 4720 4721 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4722 LinkageSize, ParamAreaSize, NumBytes, 4723 AvailableFPRs, AvailableVRs)) 4724 return true; 4725 } 4726 return false; 4727 } 4728 4729 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4730 if (CB.arg_size() != CallerFn->arg_size()) 4731 return false; 4732 4733 auto CalleeArgIter = CB.arg_begin(); 4734 auto CalleeArgEnd = CB.arg_end(); 4735 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4736 4737 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4738 const Value* CalleeArg = *CalleeArgIter; 4739 const Value* CallerArg = &(*CallerArgIter); 4740 if (CalleeArg == CallerArg) 4741 continue; 4742 4743 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4744 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4745 // } 4746 // 1st argument of callee is undef and has the same type as caller. 4747 if (CalleeArg->getType() == CallerArg->getType() && 4748 isa<UndefValue>(CalleeArg)) 4749 continue; 4750 4751 return false; 4752 } 4753 4754 return true; 4755 } 4756 4757 // Returns true if TCO is possible between the callers and callees 4758 // calling conventions. 4759 static bool 4760 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4761 CallingConv::ID CalleeCC) { 4762 // Tail calls are possible with fastcc and ccc. 4763 auto isTailCallableCC = [] (CallingConv::ID CC){ 4764 return CC == CallingConv::C || CC == CallingConv::Fast; 4765 }; 4766 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4767 return false; 4768 4769 // We can safely tail call both fastcc and ccc callees from a c calling 4770 // convention caller. If the caller is fastcc, we may have less stack space 4771 // than a non-fastcc caller with the same signature so disable tail-calls in 4772 // that case. 4773 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4774 } 4775 4776 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4777 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4778 const SmallVectorImpl<ISD::OutputArg> &Outs, 4779 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4780 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4781 4782 if (DisableSCO && !TailCallOpt) return false; 4783 4784 // Variadic argument functions are not supported. 4785 if (isVarArg) return false; 4786 4787 auto &Caller = DAG.getMachineFunction().getFunction(); 4788 // Check that the calling conventions are compatible for tco. 4789 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4790 return false; 4791 4792 // Caller contains any byval parameter is not supported. 4793 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4794 return false; 4795 4796 // Callee contains any byval parameter is not supported, too. 4797 // Note: This is a quick work around, because in some cases, e.g. 4798 // caller's stack size > callee's stack size, we are still able to apply 4799 // sibling call optimization. For example, gcc is able to do SCO for caller1 4800 // in the following example, but not for caller2. 4801 // struct test { 4802 // long int a; 4803 // char ary[56]; 4804 // } gTest; 4805 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4806 // b->a = v.a; 4807 // return 0; 4808 // } 4809 // void caller1(struct test a, struct test c, struct test *b) { 4810 // callee(gTest, b); } 4811 // void caller2(struct test *b) { callee(gTest, b); } 4812 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4813 return false; 4814 4815 // If callee and caller use different calling conventions, we cannot pass 4816 // parameters on stack since offsets for the parameter area may be different. 4817 if (Caller.getCallingConv() != CalleeCC && 4818 needStackSlotPassParameters(Subtarget, Outs)) 4819 return false; 4820 4821 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4822 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4823 // callee potentially have different TOC bases then we cannot tail call since 4824 // we need to restore the TOC pointer after the call. 4825 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4826 // We cannot guarantee this for indirect calls or calls to external functions. 4827 // When PC-Relative addressing is used, the concept of the TOC is no longer 4828 // applicable so this check is not required. 4829 // Check first for indirect calls. 4830 if (!Subtarget.isUsingPCRelativeCalls() && 4831 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4832 return false; 4833 4834 // Check if we share the TOC base. 4835 if (!Subtarget.isUsingPCRelativeCalls() && 4836 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4837 return false; 4838 4839 // TCO allows altering callee ABI, so we don't have to check further. 4840 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4841 return true; 4842 4843 if (DisableSCO) return false; 4844 4845 // If callee use the same argument list that caller is using, then we can 4846 // apply SCO on this case. If it is not, then we need to check if callee needs 4847 // stack for passing arguments. 4848 // PC Relative tail calls may not have a CallBase. 4849 // If there is no CallBase we cannot verify if we have the same argument 4850 // list so assume that we don't have the same argument list. 4851 if (CB && !hasSameArgumentList(&Caller, *CB) && 4852 needStackSlotPassParameters(Subtarget, Outs)) 4853 return false; 4854 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4855 return false; 4856 4857 return true; 4858 } 4859 4860 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4861 /// for tail call optimization. Targets which want to do tail call 4862 /// optimization should implement this function. 4863 bool 4864 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4865 CallingConv::ID CalleeCC, 4866 bool isVarArg, 4867 const SmallVectorImpl<ISD::InputArg> &Ins, 4868 SelectionDAG& DAG) const { 4869 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4870 return false; 4871 4872 // Variable argument functions are not supported. 4873 if (isVarArg) 4874 return false; 4875 4876 MachineFunction &MF = DAG.getMachineFunction(); 4877 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4878 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4879 // Functions containing by val parameters are not supported. 4880 for (unsigned i = 0; i != Ins.size(); i++) { 4881 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4882 if (Flags.isByVal()) return false; 4883 } 4884 4885 // Non-PIC/GOT tail calls are supported. 4886 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4887 return true; 4888 4889 // At the moment we can only do local tail calls (in same module, hidden 4890 // or protected) if we are generating PIC. 4891 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4892 return G->getGlobal()->hasHiddenVisibility() 4893 || G->getGlobal()->hasProtectedVisibility(); 4894 } 4895 4896 return false; 4897 } 4898 4899 /// isCallCompatibleAddress - Return the immediate to use if the specified 4900 /// 32-bit value is representable in the immediate field of a BxA instruction. 4901 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4902 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4903 if (!C) return nullptr; 4904 4905 int Addr = C->getZExtValue(); 4906 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4907 SignExtend32<26>(Addr) != Addr) 4908 return nullptr; // Top 6 bits have to be sext of immediate. 4909 4910 return DAG 4911 .getConstant( 4912 (int)C->getZExtValue() >> 2, SDLoc(Op), 4913 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4914 .getNode(); 4915 } 4916 4917 namespace { 4918 4919 struct TailCallArgumentInfo { 4920 SDValue Arg; 4921 SDValue FrameIdxOp; 4922 int FrameIdx = 0; 4923 4924 TailCallArgumentInfo() = default; 4925 }; 4926 4927 } // end anonymous namespace 4928 4929 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4930 static void StoreTailCallArgumentsToStackSlot( 4931 SelectionDAG &DAG, SDValue Chain, 4932 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4933 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4934 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4935 SDValue Arg = TailCallArgs[i].Arg; 4936 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4937 int FI = TailCallArgs[i].FrameIdx; 4938 // Store relative to framepointer. 4939 MemOpChains.push_back(DAG.getStore( 4940 Chain, dl, Arg, FIN, 4941 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4942 } 4943 } 4944 4945 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4946 /// the appropriate stack slot for the tail call optimized function call. 4947 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4948 SDValue OldRetAddr, SDValue OldFP, 4949 int SPDiff, const SDLoc &dl) { 4950 if (SPDiff) { 4951 // Calculate the new stack slot for the return address. 4952 MachineFunction &MF = DAG.getMachineFunction(); 4953 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4954 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4955 bool isPPC64 = Subtarget.isPPC64(); 4956 int SlotSize = isPPC64 ? 8 : 4; 4957 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4958 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4959 NewRetAddrLoc, true); 4960 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4961 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4962 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4963 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4964 } 4965 return Chain; 4966 } 4967 4968 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4969 /// the position of the argument. 4970 static void 4971 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4972 SDValue Arg, int SPDiff, unsigned ArgOffset, 4973 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4974 int Offset = ArgOffset + SPDiff; 4975 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4976 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4977 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4978 SDValue FIN = DAG.getFrameIndex(FI, VT); 4979 TailCallArgumentInfo Info; 4980 Info.Arg = Arg; 4981 Info.FrameIdxOp = FIN; 4982 Info.FrameIdx = FI; 4983 TailCallArguments.push_back(Info); 4984 } 4985 4986 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4987 /// stack slot. Returns the chain as result and the loaded frame pointers in 4988 /// LROpOut/FPOpout. Used when tail calling. 4989 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4990 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4991 SDValue &FPOpOut, const SDLoc &dl) const { 4992 if (SPDiff) { 4993 // Load the LR and FP stack slot for later adjusting. 4994 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4995 LROpOut = getReturnAddrFrameIndex(DAG); 4996 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4997 Chain = SDValue(LROpOut.getNode(), 1); 4998 } 4999 return Chain; 5000 } 5001 5002 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5003 /// by "Src" to address "Dst" of size "Size". Alignment information is 5004 /// specified by the specific parameter attribute. The copy will be passed as 5005 /// a byval function parameter. 5006 /// Sometimes what we are copying is the end of a larger object, the part that 5007 /// does not fit in registers. 5008 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5009 SDValue Chain, ISD::ArgFlagsTy Flags, 5010 SelectionDAG &DAG, const SDLoc &dl) { 5011 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5012 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5013 Flags.getNonZeroByValAlign(), false, false, false, 5014 MachinePointerInfo(), MachinePointerInfo()); 5015 } 5016 5017 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5018 /// tail calls. 5019 static void LowerMemOpCallTo( 5020 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5021 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5022 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5023 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5024 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5025 if (!isTailCall) { 5026 if (isVector) { 5027 SDValue StackPtr; 5028 if (isPPC64) 5029 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5030 else 5031 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5032 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5033 DAG.getConstant(ArgOffset, dl, PtrVT)); 5034 } 5035 MemOpChains.push_back( 5036 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5037 // Calculate and remember argument location. 5038 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5039 TailCallArguments); 5040 } 5041 5042 static void 5043 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5044 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5045 SDValue FPOp, 5046 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5047 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5048 // might overwrite each other in case of tail call optimization. 5049 SmallVector<SDValue, 8> MemOpChains2; 5050 // Do not flag preceding copytoreg stuff together with the following stuff. 5051 InFlag = SDValue(); 5052 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5053 MemOpChains2, dl); 5054 if (!MemOpChains2.empty()) 5055 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5056 5057 // Store the return address to the appropriate stack slot. 5058 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5059 5060 // Emit callseq_end just before tailcall node. 5061 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5062 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5063 InFlag = Chain.getValue(1); 5064 } 5065 5066 // Is this global address that of a function that can be called by name? (as 5067 // opposed to something that must hold a descriptor for an indirect call). 5068 static bool isFunctionGlobalAddress(SDValue Callee) { 5069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5070 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5071 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5072 return false; 5073 5074 return G->getGlobal()->getValueType()->isFunctionTy(); 5075 } 5076 5077 return false; 5078 } 5079 5080 SDValue PPCTargetLowering::LowerCallResult( 5081 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5082 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5083 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5084 SmallVector<CCValAssign, 16> RVLocs; 5085 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5086 *DAG.getContext()); 5087 5088 CCRetInfo.AnalyzeCallResult( 5089 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5090 ? RetCC_PPC_Cold 5091 : RetCC_PPC); 5092 5093 // Copy all of the result registers out of their specified physreg. 5094 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5095 CCValAssign &VA = RVLocs[i]; 5096 assert(VA.isRegLoc() && "Can only return in registers!"); 5097 5098 SDValue Val; 5099 5100 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5101 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5102 InFlag); 5103 Chain = Lo.getValue(1); 5104 InFlag = Lo.getValue(2); 5105 VA = RVLocs[++i]; // skip ahead to next loc 5106 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5107 InFlag); 5108 Chain = Hi.getValue(1); 5109 InFlag = Hi.getValue(2); 5110 if (!Subtarget.isLittleEndian()) 5111 std::swap (Lo, Hi); 5112 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5113 } else { 5114 Val = DAG.getCopyFromReg(Chain, dl, 5115 VA.getLocReg(), VA.getLocVT(), InFlag); 5116 Chain = Val.getValue(1); 5117 InFlag = Val.getValue(2); 5118 } 5119 5120 switch (VA.getLocInfo()) { 5121 default: llvm_unreachable("Unknown loc info!"); 5122 case CCValAssign::Full: break; 5123 case CCValAssign::AExt: 5124 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5125 break; 5126 case CCValAssign::ZExt: 5127 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5128 DAG.getValueType(VA.getValVT())); 5129 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5130 break; 5131 case CCValAssign::SExt: 5132 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5133 DAG.getValueType(VA.getValVT())); 5134 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5135 break; 5136 } 5137 5138 InVals.push_back(Val); 5139 } 5140 5141 return Chain; 5142 } 5143 5144 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5145 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5146 // PatchPoint calls are not indirect. 5147 if (isPatchPoint) 5148 return false; 5149 5150 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5151 return false; 5152 5153 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5154 // becuase the immediate function pointer points to a descriptor instead of 5155 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5156 // pointer immediate points to the global entry point, while the BLA would 5157 // need to jump to the local entry point (see rL211174). 5158 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5159 isBLACompatibleAddress(Callee, DAG)) 5160 return false; 5161 5162 return true; 5163 } 5164 5165 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5166 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5167 return Subtarget.isAIXABI() || 5168 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5169 } 5170 5171 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5172 const Function &Caller, 5173 const SDValue &Callee, 5174 const PPCSubtarget &Subtarget, 5175 const TargetMachine &TM) { 5176 if (CFlags.IsTailCall) 5177 return PPCISD::TC_RETURN; 5178 5179 // This is a call through a function pointer. 5180 if (CFlags.IsIndirect) { 5181 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5182 // indirect calls. The save of the caller's TOC pointer to the stack will be 5183 // inserted into the DAG as part of call lowering. The restore of the TOC 5184 // pointer is modeled by using a pseudo instruction for the call opcode that 5185 // represents the 2 instruction sequence of an indirect branch and link, 5186 // immediately followed by a load of the TOC pointer from the the stack save 5187 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5188 // as it is not saved or used. 5189 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5190 : PPCISD::BCTRL; 5191 } 5192 5193 if (Subtarget.isUsingPCRelativeCalls()) { 5194 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5195 return PPCISD::CALL_NOTOC; 5196 } 5197 5198 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5199 // immediately following the call instruction if the caller and callee may 5200 // have different TOC bases. At link time if the linker determines the calls 5201 // may not share a TOC base, the call is redirected to a trampoline inserted 5202 // by the linker. The trampoline will (among other things) save the callers 5203 // TOC pointer at an ABI designated offset in the linkage area and the linker 5204 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5205 // into gpr2. 5206 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5207 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5208 : PPCISD::CALL_NOP; 5209 5210 return PPCISD::CALL; 5211 } 5212 5213 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5214 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5215 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5216 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5217 return SDValue(Dest, 0); 5218 5219 // Returns true if the callee is local, and false otherwise. 5220 auto isLocalCallee = [&]() { 5221 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5222 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5223 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5224 5225 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5226 !dyn_cast_or_null<GlobalIFunc>(GV); 5227 }; 5228 5229 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5230 // a static relocation model causes some versions of GNU LD (2.17.50, at 5231 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5232 // built with secure-PLT. 5233 bool UsePlt = 5234 Subtarget.is32BitELFABI() && !isLocalCallee() && 5235 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5236 5237 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5238 const TargetMachine &TM = Subtarget.getTargetMachine(); 5239 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5240 MCSymbolXCOFF *S = 5241 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5242 5243 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5244 return DAG.getMCSymbol(S, PtrVT); 5245 }; 5246 5247 if (isFunctionGlobalAddress(Callee)) { 5248 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5249 5250 if (Subtarget.isAIXABI()) { 5251 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5252 return getAIXFuncEntryPointSymbolSDNode(GV); 5253 } 5254 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5255 UsePlt ? PPCII::MO_PLT : 0); 5256 } 5257 5258 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5259 const char *SymName = S->getSymbol(); 5260 if (Subtarget.isAIXABI()) { 5261 // If there exists a user-declared function whose name is the same as the 5262 // ExternalSymbol's, then we pick up the user-declared version. 5263 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5264 if (const Function *F = 5265 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5266 return getAIXFuncEntryPointSymbolSDNode(F); 5267 5268 // On AIX, direct function calls reference the symbol for the function's 5269 // entry point, which is named by prepending a "." before the function's 5270 // C-linkage name. A Qualname is returned here because an external 5271 // function entry point is a csect with XTY_ER property. 5272 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5273 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5274 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5275 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5276 SectionKind::getMetadata()); 5277 return Sec->getQualNameSymbol(); 5278 }; 5279 5280 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5281 } 5282 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5283 UsePlt ? PPCII::MO_PLT : 0); 5284 } 5285 5286 // No transformation needed. 5287 assert(Callee.getNode() && "What no callee?"); 5288 return Callee; 5289 } 5290 5291 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5292 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5293 "Expected a CALLSEQ_STARTSDNode."); 5294 5295 // The last operand is the chain, except when the node has glue. If the node 5296 // has glue, then the last operand is the glue, and the chain is the second 5297 // last operand. 5298 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5299 if (LastValue.getValueType() != MVT::Glue) 5300 return LastValue; 5301 5302 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5303 } 5304 5305 // Creates the node that moves a functions address into the count register 5306 // to prepare for an indirect call instruction. 5307 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5308 SDValue &Glue, SDValue &Chain, 5309 const SDLoc &dl) { 5310 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5311 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5312 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5313 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5314 // The glue is the second value produced. 5315 Glue = Chain.getValue(1); 5316 } 5317 5318 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5319 SDValue &Glue, SDValue &Chain, 5320 SDValue CallSeqStart, 5321 const CallBase *CB, const SDLoc &dl, 5322 bool hasNest, 5323 const PPCSubtarget &Subtarget) { 5324 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5325 // entry point, but to the function descriptor (the function entry point 5326 // address is part of the function descriptor though). 5327 // The function descriptor is a three doubleword structure with the 5328 // following fields: function entry point, TOC base address and 5329 // environment pointer. 5330 // Thus for a call through a function pointer, the following actions need 5331 // to be performed: 5332 // 1. Save the TOC of the caller in the TOC save area of its stack 5333 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5334 // 2. Load the address of the function entry point from the function 5335 // descriptor. 5336 // 3. Load the TOC of the callee from the function descriptor into r2. 5337 // 4. Load the environment pointer from the function descriptor into 5338 // r11. 5339 // 5. Branch to the function entry point address. 5340 // 6. On return of the callee, the TOC of the caller needs to be 5341 // restored (this is done in FinishCall()). 5342 // 5343 // The loads are scheduled at the beginning of the call sequence, and the 5344 // register copies are flagged together to ensure that no other 5345 // operations can be scheduled in between. E.g. without flagging the 5346 // copies together, a TOC access in the caller could be scheduled between 5347 // the assignment of the callee TOC and the branch to the callee, which leads 5348 // to incorrect code. 5349 5350 // Start by loading the function address from the descriptor. 5351 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5352 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5353 ? (MachineMemOperand::MODereferenceable | 5354 MachineMemOperand::MOInvariant) 5355 : MachineMemOperand::MONone; 5356 5357 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5358 5359 // Registers used in building the DAG. 5360 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5361 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5362 5363 // Offsets of descriptor members. 5364 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5365 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5366 5367 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5368 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5369 5370 // One load for the functions entry point address. 5371 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5372 Alignment, MMOFlags); 5373 5374 // One for loading the TOC anchor for the module that contains the called 5375 // function. 5376 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5377 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5378 SDValue TOCPtr = 5379 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5380 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5381 5382 // One for loading the environment pointer. 5383 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5384 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5385 SDValue LoadEnvPtr = 5386 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5387 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5388 5389 5390 // Then copy the newly loaded TOC anchor to the TOC pointer. 5391 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5392 Chain = TOCVal.getValue(0); 5393 Glue = TOCVal.getValue(1); 5394 5395 // If the function call has an explicit 'nest' parameter, it takes the 5396 // place of the environment pointer. 5397 assert((!hasNest || !Subtarget.isAIXABI()) && 5398 "Nest parameter is not supported on AIX."); 5399 if (!hasNest) { 5400 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5401 Chain = EnvVal.getValue(0); 5402 Glue = EnvVal.getValue(1); 5403 } 5404 5405 // The rest of the indirect call sequence is the same as the non-descriptor 5406 // DAG. 5407 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5408 } 5409 5410 static void 5411 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5412 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5413 SelectionDAG &DAG, 5414 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5415 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5416 const PPCSubtarget &Subtarget) { 5417 const bool IsPPC64 = Subtarget.isPPC64(); 5418 // MVT for a general purpose register. 5419 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5420 5421 // First operand is always the chain. 5422 Ops.push_back(Chain); 5423 5424 // If it's a direct call pass the callee as the second operand. 5425 if (!CFlags.IsIndirect) 5426 Ops.push_back(Callee); 5427 else { 5428 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5429 5430 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5431 // on the stack (this would have been done in `LowerCall_64SVR4` or 5432 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5433 // represents both the indirect branch and a load that restores the TOC 5434 // pointer from the linkage area. The operand for the TOC restore is an add 5435 // of the TOC save offset to the stack pointer. This must be the second 5436 // operand: after the chain input but before any other variadic arguments. 5437 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5438 // saved or used. 5439 if (isTOCSaveRestoreRequired(Subtarget)) { 5440 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5441 5442 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5443 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5444 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5445 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5446 Ops.push_back(AddTOC); 5447 } 5448 5449 // Add the register used for the environment pointer. 5450 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5451 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5452 RegVT)); 5453 5454 5455 // Add CTR register as callee so a bctr can be emitted later. 5456 if (CFlags.IsTailCall) 5457 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5458 } 5459 5460 // If this is a tail call add stack pointer delta. 5461 if (CFlags.IsTailCall) 5462 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5463 5464 // Add argument registers to the end of the list so that they are known live 5465 // into the call. 5466 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5467 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5468 RegsToPass[i].second.getValueType())); 5469 5470 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5471 // no way to mark dependencies as implicit here. 5472 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5473 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5474 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5475 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5476 5477 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5478 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5479 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5480 5481 // Add a register mask operand representing the call-preserved registers. 5482 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5483 const uint32_t *Mask = 5484 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5485 assert(Mask && "Missing call preserved mask for calling convention"); 5486 Ops.push_back(DAG.getRegisterMask(Mask)); 5487 5488 // If the glue is valid, it is the last operand. 5489 if (Glue.getNode()) 5490 Ops.push_back(Glue); 5491 } 5492 5493 SDValue PPCTargetLowering::FinishCall( 5494 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5495 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5496 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5497 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5498 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5499 5500 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5501 Subtarget.isAIXABI()) 5502 setUsesTOCBasePtr(DAG); 5503 5504 unsigned CallOpc = 5505 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5506 Subtarget, DAG.getTarget()); 5507 5508 if (!CFlags.IsIndirect) 5509 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5510 else if (Subtarget.usesFunctionDescriptors()) 5511 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5512 dl, CFlags.HasNest, Subtarget); 5513 else 5514 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5515 5516 // Build the operand list for the call instruction. 5517 SmallVector<SDValue, 8> Ops; 5518 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5519 SPDiff, Subtarget); 5520 5521 // Emit tail call. 5522 if (CFlags.IsTailCall) { 5523 // Indirect tail call when using PC Relative calls do not have the same 5524 // constraints. 5525 assert(((Callee.getOpcode() == ISD::Register && 5526 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5527 Callee.getOpcode() == ISD::TargetExternalSymbol || 5528 Callee.getOpcode() == ISD::TargetGlobalAddress || 5529 isa<ConstantSDNode>(Callee) || 5530 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5531 "Expecting a global address, external symbol, absolute value, " 5532 "register or an indirect tail call when PC Relative calls are " 5533 "used."); 5534 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5535 assert(CallOpc == PPCISD::TC_RETURN && 5536 "Unexpected call opcode for a tail call."); 5537 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5538 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5539 } 5540 5541 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5542 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5543 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5544 Glue = Chain.getValue(1); 5545 5546 // When performing tail call optimization the callee pops its arguments off 5547 // the stack. Account for this here so these bytes can be pushed back on in 5548 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5549 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5550 getTargetMachine().Options.GuaranteedTailCallOpt) 5551 ? NumBytes 5552 : 0; 5553 5554 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5555 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5556 Glue, dl); 5557 Glue = Chain.getValue(1); 5558 5559 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5560 DAG, InVals); 5561 } 5562 5563 SDValue 5564 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5565 SmallVectorImpl<SDValue> &InVals) const { 5566 SelectionDAG &DAG = CLI.DAG; 5567 SDLoc &dl = CLI.DL; 5568 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5569 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5570 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5571 SDValue Chain = CLI.Chain; 5572 SDValue Callee = CLI.Callee; 5573 bool &isTailCall = CLI.IsTailCall; 5574 CallingConv::ID CallConv = CLI.CallConv; 5575 bool isVarArg = CLI.IsVarArg; 5576 bool isPatchPoint = CLI.IsPatchPoint; 5577 const CallBase *CB = CLI.CB; 5578 5579 if (isTailCall) { 5580 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5581 isTailCall = false; 5582 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5583 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5584 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5585 else 5586 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5587 Ins, DAG); 5588 if (isTailCall) { 5589 ++NumTailCalls; 5590 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5591 ++NumSiblingCalls; 5592 5593 // PC Relative calls no longer guarantee that the callee is a Global 5594 // Address Node. The callee could be an indirect tail call in which 5595 // case the SDValue for the callee could be a load (to load the address 5596 // of a function pointer) or it may be a register copy (to move the 5597 // address of the callee from a function parameter into a virtual 5598 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5599 assert((Subtarget.isUsingPCRelativeCalls() || 5600 isa<GlobalAddressSDNode>(Callee)) && 5601 "Callee should be an llvm::Function object."); 5602 5603 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5604 << "\nTCO callee: "); 5605 LLVM_DEBUG(Callee.dump()); 5606 } 5607 } 5608 5609 if (!isTailCall && CB && CB->isMustTailCall()) 5610 report_fatal_error("failed to perform tail call elimination on a call " 5611 "site marked musttail"); 5612 5613 // When long calls (i.e. indirect calls) are always used, calls are always 5614 // made via function pointer. If we have a function name, first translate it 5615 // into a pointer. 5616 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5617 !isTailCall) 5618 Callee = LowerGlobalAddress(Callee, DAG); 5619 5620 CallFlags CFlags( 5621 CallConv, isTailCall, isVarArg, isPatchPoint, 5622 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5623 // hasNest 5624 Subtarget.is64BitELFABI() && 5625 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5626 CLI.NoMerge); 5627 5628 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5629 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5630 InVals, CB); 5631 5632 if (Subtarget.isSVR4ABI()) 5633 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5634 InVals, CB); 5635 5636 if (Subtarget.isAIXABI()) 5637 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5638 InVals, CB); 5639 5640 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5641 InVals, CB); 5642 } 5643 5644 SDValue PPCTargetLowering::LowerCall_32SVR4( 5645 SDValue Chain, SDValue Callee, CallFlags CFlags, 5646 const SmallVectorImpl<ISD::OutputArg> &Outs, 5647 const SmallVectorImpl<SDValue> &OutVals, 5648 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5649 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5650 const CallBase *CB) const { 5651 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5652 // of the 32-bit SVR4 ABI stack frame layout. 5653 5654 const CallingConv::ID CallConv = CFlags.CallConv; 5655 const bool IsVarArg = CFlags.IsVarArg; 5656 const bool IsTailCall = CFlags.IsTailCall; 5657 5658 assert((CallConv == CallingConv::C || 5659 CallConv == CallingConv::Cold || 5660 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5661 5662 const Align PtrAlign(4); 5663 5664 MachineFunction &MF = DAG.getMachineFunction(); 5665 5666 // Mark this function as potentially containing a function that contains a 5667 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5668 // and restoring the callers stack pointer in this functions epilog. This is 5669 // done because by tail calling the called function might overwrite the value 5670 // in this function's (MF) stack pointer stack slot 0(SP). 5671 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5672 CallConv == CallingConv::Fast) 5673 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5674 5675 // Count how many bytes are to be pushed on the stack, including the linkage 5676 // area, parameter list area and the part of the local variable space which 5677 // contains copies of aggregates which are passed by value. 5678 5679 // Assign locations to all of the outgoing arguments. 5680 SmallVector<CCValAssign, 16> ArgLocs; 5681 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5682 5683 // Reserve space for the linkage area on the stack. 5684 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5685 PtrAlign); 5686 if (useSoftFloat()) 5687 CCInfo.PreAnalyzeCallOperands(Outs); 5688 5689 if (IsVarArg) { 5690 // Handle fixed and variable vector arguments differently. 5691 // Fixed vector arguments go into registers as long as registers are 5692 // available. Variable vector arguments always go into memory. 5693 unsigned NumArgs = Outs.size(); 5694 5695 for (unsigned i = 0; i != NumArgs; ++i) { 5696 MVT ArgVT = Outs[i].VT; 5697 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5698 bool Result; 5699 5700 if (Outs[i].IsFixed) { 5701 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5702 CCInfo); 5703 } else { 5704 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5705 ArgFlags, CCInfo); 5706 } 5707 5708 if (Result) { 5709 #ifndef NDEBUG 5710 errs() << "Call operand #" << i << " has unhandled type " 5711 << EVT(ArgVT).getEVTString() << "\n"; 5712 #endif 5713 llvm_unreachable(nullptr); 5714 } 5715 } 5716 } else { 5717 // All arguments are treated the same. 5718 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5719 } 5720 CCInfo.clearWasPPCF128(); 5721 5722 // Assign locations to all of the outgoing aggregate by value arguments. 5723 SmallVector<CCValAssign, 16> ByValArgLocs; 5724 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5725 5726 // Reserve stack space for the allocations in CCInfo. 5727 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5728 5729 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5730 5731 // Size of the linkage area, parameter list area and the part of the local 5732 // space variable where copies of aggregates which are passed by value are 5733 // stored. 5734 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5735 5736 // Calculate by how many bytes the stack has to be adjusted in case of tail 5737 // call optimization. 5738 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5739 5740 // Adjust the stack pointer for the new arguments... 5741 // These operations are automatically eliminated by the prolog/epilog pass 5742 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5743 SDValue CallSeqStart = Chain; 5744 5745 // Load the return address and frame pointer so it can be moved somewhere else 5746 // later. 5747 SDValue LROp, FPOp; 5748 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5749 5750 // Set up a copy of the stack pointer for use loading and storing any 5751 // arguments that may not fit in the registers available for argument 5752 // passing. 5753 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5754 5755 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5756 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5757 SmallVector<SDValue, 8> MemOpChains; 5758 5759 bool seenFloatArg = false; 5760 // Walk the register/memloc assignments, inserting copies/loads. 5761 // i - Tracks the index into the list of registers allocated for the call 5762 // RealArgIdx - Tracks the index into the list of actual function arguments 5763 // j - Tracks the index into the list of byval arguments 5764 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5765 i != e; 5766 ++i, ++RealArgIdx) { 5767 CCValAssign &VA = ArgLocs[i]; 5768 SDValue Arg = OutVals[RealArgIdx]; 5769 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5770 5771 if (Flags.isByVal()) { 5772 // Argument is an aggregate which is passed by value, thus we need to 5773 // create a copy of it in the local variable space of the current stack 5774 // frame (which is the stack frame of the caller) and pass the address of 5775 // this copy to the callee. 5776 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5777 CCValAssign &ByValVA = ByValArgLocs[j++]; 5778 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5779 5780 // Memory reserved in the local variable space of the callers stack frame. 5781 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5782 5783 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5784 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5785 StackPtr, PtrOff); 5786 5787 // Create a copy of the argument in the local area of the current 5788 // stack frame. 5789 SDValue MemcpyCall = 5790 CreateCopyOfByValArgument(Arg, PtrOff, 5791 CallSeqStart.getNode()->getOperand(0), 5792 Flags, DAG, dl); 5793 5794 // This must go outside the CALLSEQ_START..END. 5795 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5796 SDLoc(MemcpyCall)); 5797 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5798 NewCallSeqStart.getNode()); 5799 Chain = CallSeqStart = NewCallSeqStart; 5800 5801 // Pass the address of the aggregate copy on the stack either in a 5802 // physical register or in the parameter list area of the current stack 5803 // frame to the callee. 5804 Arg = PtrOff; 5805 } 5806 5807 // When useCRBits() is true, there can be i1 arguments. 5808 // It is because getRegisterType(MVT::i1) => MVT::i1, 5809 // and for other integer types getRegisterType() => MVT::i32. 5810 // Extend i1 and ensure callee will get i32. 5811 if (Arg.getValueType() == MVT::i1) 5812 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5813 dl, MVT::i32, Arg); 5814 5815 if (VA.isRegLoc()) { 5816 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5817 // Put argument in a physical register. 5818 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5819 bool IsLE = Subtarget.isLittleEndian(); 5820 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5821 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5822 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5823 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5824 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5825 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5826 SVal.getValue(0))); 5827 } else 5828 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5829 } else { 5830 // Put argument in the parameter list area of the current stack frame. 5831 assert(VA.isMemLoc()); 5832 unsigned LocMemOffset = VA.getLocMemOffset(); 5833 5834 if (!IsTailCall) { 5835 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5836 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5837 StackPtr, PtrOff); 5838 5839 MemOpChains.push_back( 5840 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5841 } else { 5842 // Calculate and remember argument location. 5843 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5844 TailCallArguments); 5845 } 5846 } 5847 } 5848 5849 if (!MemOpChains.empty()) 5850 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5851 5852 // Build a sequence of copy-to-reg nodes chained together with token chain 5853 // and flag operands which copy the outgoing args into the appropriate regs. 5854 SDValue InFlag; 5855 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5856 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5857 RegsToPass[i].second, InFlag); 5858 InFlag = Chain.getValue(1); 5859 } 5860 5861 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5862 // registers. 5863 if (IsVarArg) { 5864 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5865 SDValue Ops[] = { Chain, InFlag }; 5866 5867 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5868 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5869 5870 InFlag = Chain.getValue(1); 5871 } 5872 5873 if (IsTailCall) 5874 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5875 TailCallArguments); 5876 5877 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5878 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5879 } 5880 5881 // Copy an argument into memory, being careful to do this outside the 5882 // call sequence for the call to which the argument belongs. 5883 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5884 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5885 SelectionDAG &DAG, const SDLoc &dl) const { 5886 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5887 CallSeqStart.getNode()->getOperand(0), 5888 Flags, DAG, dl); 5889 // The MEMCPY must go outside the CALLSEQ_START..END. 5890 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5891 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5892 SDLoc(MemcpyCall)); 5893 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5894 NewCallSeqStart.getNode()); 5895 return NewCallSeqStart; 5896 } 5897 5898 SDValue PPCTargetLowering::LowerCall_64SVR4( 5899 SDValue Chain, SDValue Callee, CallFlags CFlags, 5900 const SmallVectorImpl<ISD::OutputArg> &Outs, 5901 const SmallVectorImpl<SDValue> &OutVals, 5902 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5903 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5904 const CallBase *CB) const { 5905 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5906 bool isLittleEndian = Subtarget.isLittleEndian(); 5907 unsigned NumOps = Outs.size(); 5908 bool IsSibCall = false; 5909 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5910 5911 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5912 unsigned PtrByteSize = 8; 5913 5914 MachineFunction &MF = DAG.getMachineFunction(); 5915 5916 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5917 IsSibCall = true; 5918 5919 // Mark this function as potentially containing a function that contains a 5920 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5921 // and restoring the callers stack pointer in this functions epilog. This is 5922 // done because by tail calling the called function might overwrite the value 5923 // in this function's (MF) stack pointer stack slot 0(SP). 5924 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5925 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5926 5927 assert(!(IsFastCall && CFlags.IsVarArg) && 5928 "fastcc not supported on varargs functions"); 5929 5930 // Count how many bytes are to be pushed on the stack, including the linkage 5931 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5932 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5933 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5934 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5935 unsigned NumBytes = LinkageSize; 5936 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5937 5938 static const MCPhysReg GPR[] = { 5939 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5940 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5941 }; 5942 static const MCPhysReg VR[] = { 5943 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5944 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5945 }; 5946 5947 const unsigned NumGPRs = array_lengthof(GPR); 5948 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5949 const unsigned NumVRs = array_lengthof(VR); 5950 5951 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5952 // can be passed to the callee in registers. 5953 // For the fast calling convention, there is another check below. 5954 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5955 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5956 if (!HasParameterArea) { 5957 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5958 unsigned AvailableFPRs = NumFPRs; 5959 unsigned AvailableVRs = NumVRs; 5960 unsigned NumBytesTmp = NumBytes; 5961 for (unsigned i = 0; i != NumOps; ++i) { 5962 if (Outs[i].Flags.isNest()) continue; 5963 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5964 PtrByteSize, LinkageSize, ParamAreaSize, 5965 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5966 HasParameterArea = true; 5967 } 5968 } 5969 5970 // When using the fast calling convention, we don't provide backing for 5971 // arguments that will be in registers. 5972 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5973 5974 // Avoid allocating parameter area for fastcc functions if all the arguments 5975 // can be passed in the registers. 5976 if (IsFastCall) 5977 HasParameterArea = false; 5978 5979 // Add up all the space actually used. 5980 for (unsigned i = 0; i != NumOps; ++i) { 5981 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5982 EVT ArgVT = Outs[i].VT; 5983 EVT OrigVT = Outs[i].ArgVT; 5984 5985 if (Flags.isNest()) 5986 continue; 5987 5988 if (IsFastCall) { 5989 if (Flags.isByVal()) { 5990 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5991 if (NumGPRsUsed > NumGPRs) 5992 HasParameterArea = true; 5993 } else { 5994 switch (ArgVT.getSimpleVT().SimpleTy) { 5995 default: llvm_unreachable("Unexpected ValueType for argument!"); 5996 case MVT::i1: 5997 case MVT::i32: 5998 case MVT::i64: 5999 if (++NumGPRsUsed <= NumGPRs) 6000 continue; 6001 break; 6002 case MVT::v4i32: 6003 case MVT::v8i16: 6004 case MVT::v16i8: 6005 case MVT::v2f64: 6006 case MVT::v2i64: 6007 case MVT::v1i128: 6008 case MVT::f128: 6009 if (++NumVRsUsed <= NumVRs) 6010 continue; 6011 break; 6012 case MVT::v4f32: 6013 if (++NumVRsUsed <= NumVRs) 6014 continue; 6015 break; 6016 case MVT::f32: 6017 case MVT::f64: 6018 if (++NumFPRsUsed <= NumFPRs) 6019 continue; 6020 break; 6021 } 6022 HasParameterArea = true; 6023 } 6024 } 6025 6026 /* Respect alignment of argument on the stack. */ 6027 auto Alignement = 6028 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6029 NumBytes = alignTo(NumBytes, Alignement); 6030 6031 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6032 if (Flags.isInConsecutiveRegsLast()) 6033 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6034 } 6035 6036 unsigned NumBytesActuallyUsed = NumBytes; 6037 6038 // In the old ELFv1 ABI, 6039 // the prolog code of the callee may store up to 8 GPR argument registers to 6040 // the stack, allowing va_start to index over them in memory if its varargs. 6041 // Because we cannot tell if this is needed on the caller side, we have to 6042 // conservatively assume that it is needed. As such, make sure we have at 6043 // least enough stack space for the caller to store the 8 GPRs. 6044 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6045 // really requires memory operands, e.g. a vararg function. 6046 if (HasParameterArea) 6047 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6048 else 6049 NumBytes = LinkageSize; 6050 6051 // Tail call needs the stack to be aligned. 6052 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6053 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6054 6055 int SPDiff = 0; 6056 6057 // Calculate by how many bytes the stack has to be adjusted in case of tail 6058 // call optimization. 6059 if (!IsSibCall) 6060 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6061 6062 // To protect arguments on the stack from being clobbered in a tail call, 6063 // force all the loads to happen before doing any other lowering. 6064 if (CFlags.IsTailCall) 6065 Chain = DAG.getStackArgumentTokenFactor(Chain); 6066 6067 // Adjust the stack pointer for the new arguments... 6068 // These operations are automatically eliminated by the prolog/epilog pass 6069 if (!IsSibCall) 6070 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6071 SDValue CallSeqStart = Chain; 6072 6073 // Load the return address and frame pointer so it can be move somewhere else 6074 // later. 6075 SDValue LROp, FPOp; 6076 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6077 6078 // Set up a copy of the stack pointer for use loading and storing any 6079 // arguments that may not fit in the registers available for argument 6080 // passing. 6081 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6082 6083 // Figure out which arguments are going to go in registers, and which in 6084 // memory. Also, if this is a vararg function, floating point operations 6085 // must be stored to our stack, and loaded into integer regs as well, if 6086 // any integer regs are available for argument passing. 6087 unsigned ArgOffset = LinkageSize; 6088 6089 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6090 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6091 6092 SmallVector<SDValue, 8> MemOpChains; 6093 for (unsigned i = 0; i != NumOps; ++i) { 6094 SDValue Arg = OutVals[i]; 6095 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6096 EVT ArgVT = Outs[i].VT; 6097 EVT OrigVT = Outs[i].ArgVT; 6098 6099 // PtrOff will be used to store the current argument to the stack if a 6100 // register cannot be found for it. 6101 SDValue PtrOff; 6102 6103 // We re-align the argument offset for each argument, except when using the 6104 // fast calling convention, when we need to make sure we do that only when 6105 // we'll actually use a stack slot. 6106 auto ComputePtrOff = [&]() { 6107 /* Respect alignment of argument on the stack. */ 6108 auto Alignment = 6109 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6110 ArgOffset = alignTo(ArgOffset, Alignment); 6111 6112 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6113 6114 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6115 }; 6116 6117 if (!IsFastCall) { 6118 ComputePtrOff(); 6119 6120 /* Compute GPR index associated with argument offset. */ 6121 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6122 GPR_idx = std::min(GPR_idx, NumGPRs); 6123 } 6124 6125 // Promote integers to 64-bit values. 6126 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6127 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6128 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6129 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6130 } 6131 6132 // FIXME memcpy is used way more than necessary. Correctness first. 6133 // Note: "by value" is code for passing a structure by value, not 6134 // basic types. 6135 if (Flags.isByVal()) { 6136 // Note: Size includes alignment padding, so 6137 // struct x { short a; char b; } 6138 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6139 // These are the proper values we need for right-justifying the 6140 // aggregate in a parameter register. 6141 unsigned Size = Flags.getByValSize(); 6142 6143 // An empty aggregate parameter takes up no storage and no 6144 // registers. 6145 if (Size == 0) 6146 continue; 6147 6148 if (IsFastCall) 6149 ComputePtrOff(); 6150 6151 // All aggregates smaller than 8 bytes must be passed right-justified. 6152 if (Size==1 || Size==2 || Size==4) { 6153 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6154 if (GPR_idx != NumGPRs) { 6155 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6156 MachinePointerInfo(), VT); 6157 MemOpChains.push_back(Load.getValue(1)); 6158 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6159 6160 ArgOffset += PtrByteSize; 6161 continue; 6162 } 6163 } 6164 6165 if (GPR_idx == NumGPRs && Size < 8) { 6166 SDValue AddPtr = PtrOff; 6167 if (!isLittleEndian) { 6168 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6169 PtrOff.getValueType()); 6170 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6171 } 6172 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6173 CallSeqStart, 6174 Flags, DAG, dl); 6175 ArgOffset += PtrByteSize; 6176 continue; 6177 } 6178 // Copy entire object into memory. There are cases where gcc-generated 6179 // code assumes it is there, even if it could be put entirely into 6180 // registers. (This is not what the doc says.) 6181 6182 // FIXME: The above statement is likely due to a misunderstanding of the 6183 // documents. All arguments must be copied into the parameter area BY 6184 // THE CALLEE in the event that the callee takes the address of any 6185 // formal argument. That has not yet been implemented. However, it is 6186 // reasonable to use the stack area as a staging area for the register 6187 // load. 6188 6189 // Skip this for small aggregates, as we will use the same slot for a 6190 // right-justified copy, below. 6191 if (Size >= 8) 6192 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6193 CallSeqStart, 6194 Flags, DAG, dl); 6195 6196 // When a register is available, pass a small aggregate right-justified. 6197 if (Size < 8 && GPR_idx != NumGPRs) { 6198 // The easiest way to get this right-justified in a register 6199 // is to copy the structure into the rightmost portion of a 6200 // local variable slot, then load the whole slot into the 6201 // register. 6202 // FIXME: The memcpy seems to produce pretty awful code for 6203 // small aggregates, particularly for packed ones. 6204 // FIXME: It would be preferable to use the slot in the 6205 // parameter save area instead of a new local variable. 6206 SDValue AddPtr = PtrOff; 6207 if (!isLittleEndian) { 6208 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6209 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6210 } 6211 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6212 CallSeqStart, 6213 Flags, DAG, dl); 6214 6215 // Load the slot into the register. 6216 SDValue Load = 6217 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6218 MemOpChains.push_back(Load.getValue(1)); 6219 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6220 6221 // Done with this argument. 6222 ArgOffset += PtrByteSize; 6223 continue; 6224 } 6225 6226 // For aggregates larger than PtrByteSize, copy the pieces of the 6227 // object that fit into registers from the parameter save area. 6228 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6229 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6230 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6231 if (GPR_idx != NumGPRs) { 6232 SDValue Load = 6233 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6234 MemOpChains.push_back(Load.getValue(1)); 6235 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6236 ArgOffset += PtrByteSize; 6237 } else { 6238 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6239 break; 6240 } 6241 } 6242 continue; 6243 } 6244 6245 switch (Arg.getSimpleValueType().SimpleTy) { 6246 default: llvm_unreachable("Unexpected ValueType for argument!"); 6247 case MVT::i1: 6248 case MVT::i32: 6249 case MVT::i64: 6250 if (Flags.isNest()) { 6251 // The 'nest' parameter, if any, is passed in R11. 6252 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6253 break; 6254 } 6255 6256 // These can be scalar arguments or elements of an integer array type 6257 // passed directly. Clang may use those instead of "byval" aggregate 6258 // types to avoid forcing arguments to memory unnecessarily. 6259 if (GPR_idx != NumGPRs) { 6260 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6261 } else { 6262 if (IsFastCall) 6263 ComputePtrOff(); 6264 6265 assert(HasParameterArea && 6266 "Parameter area must exist to pass an argument in memory."); 6267 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6268 true, CFlags.IsTailCall, false, MemOpChains, 6269 TailCallArguments, dl); 6270 if (IsFastCall) 6271 ArgOffset += PtrByteSize; 6272 } 6273 if (!IsFastCall) 6274 ArgOffset += PtrByteSize; 6275 break; 6276 case MVT::f32: 6277 case MVT::f64: { 6278 // These can be scalar arguments or elements of a float array type 6279 // passed directly. The latter are used to implement ELFv2 homogenous 6280 // float aggregates. 6281 6282 // Named arguments go into FPRs first, and once they overflow, the 6283 // remaining arguments go into GPRs and then the parameter save area. 6284 // Unnamed arguments for vararg functions always go to GPRs and 6285 // then the parameter save area. For now, put all arguments to vararg 6286 // routines always in both locations (FPR *and* GPR or stack slot). 6287 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6288 bool NeededLoad = false; 6289 6290 // First load the argument into the next available FPR. 6291 if (FPR_idx != NumFPRs) 6292 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6293 6294 // Next, load the argument into GPR or stack slot if needed. 6295 if (!NeedGPROrStack) 6296 ; 6297 else if (GPR_idx != NumGPRs && !IsFastCall) { 6298 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6299 // once we support fp <-> gpr moves. 6300 6301 // In the non-vararg case, this can only ever happen in the 6302 // presence of f32 array types, since otherwise we never run 6303 // out of FPRs before running out of GPRs. 6304 SDValue ArgVal; 6305 6306 // Double values are always passed in a single GPR. 6307 if (Arg.getValueType() != MVT::f32) { 6308 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6309 6310 // Non-array float values are extended and passed in a GPR. 6311 } else if (!Flags.isInConsecutiveRegs()) { 6312 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6313 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6314 6315 // If we have an array of floats, we collect every odd element 6316 // together with its predecessor into one GPR. 6317 } else if (ArgOffset % PtrByteSize != 0) { 6318 SDValue Lo, Hi; 6319 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6320 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6321 if (!isLittleEndian) 6322 std::swap(Lo, Hi); 6323 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6324 6325 // The final element, if even, goes into the first half of a GPR. 6326 } else if (Flags.isInConsecutiveRegsLast()) { 6327 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6328 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6329 if (!isLittleEndian) 6330 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6331 DAG.getConstant(32, dl, MVT::i32)); 6332 6333 // Non-final even elements are skipped; they will be handled 6334 // together the with subsequent argument on the next go-around. 6335 } else 6336 ArgVal = SDValue(); 6337 6338 if (ArgVal.getNode()) 6339 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6340 } else { 6341 if (IsFastCall) 6342 ComputePtrOff(); 6343 6344 // Single-precision floating-point values are mapped to the 6345 // second (rightmost) word of the stack doubleword. 6346 if (Arg.getValueType() == MVT::f32 && 6347 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6348 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6349 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6350 } 6351 6352 assert(HasParameterArea && 6353 "Parameter area must exist to pass an argument in memory."); 6354 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6355 true, CFlags.IsTailCall, false, MemOpChains, 6356 TailCallArguments, dl); 6357 6358 NeededLoad = true; 6359 } 6360 // When passing an array of floats, the array occupies consecutive 6361 // space in the argument area; only round up to the next doubleword 6362 // at the end of the array. Otherwise, each float takes 8 bytes. 6363 if (!IsFastCall || NeededLoad) { 6364 ArgOffset += (Arg.getValueType() == MVT::f32 && 6365 Flags.isInConsecutiveRegs()) ? 4 : 8; 6366 if (Flags.isInConsecutiveRegsLast()) 6367 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6368 } 6369 break; 6370 } 6371 case MVT::v4f32: 6372 case MVT::v4i32: 6373 case MVT::v8i16: 6374 case MVT::v16i8: 6375 case MVT::v2f64: 6376 case MVT::v2i64: 6377 case MVT::v1i128: 6378 case MVT::f128: 6379 // These can be scalar arguments or elements of a vector array type 6380 // passed directly. The latter are used to implement ELFv2 homogenous 6381 // vector aggregates. 6382 6383 // For a varargs call, named arguments go into VRs or on the stack as 6384 // usual; unnamed arguments always go to the stack or the corresponding 6385 // GPRs when within range. For now, we always put the value in both 6386 // locations (or even all three). 6387 if (CFlags.IsVarArg) { 6388 assert(HasParameterArea && 6389 "Parameter area must exist if we have a varargs call."); 6390 // We could elide this store in the case where the object fits 6391 // entirely in R registers. Maybe later. 6392 SDValue Store = 6393 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6394 MemOpChains.push_back(Store); 6395 if (VR_idx != NumVRs) { 6396 SDValue Load = 6397 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6398 MemOpChains.push_back(Load.getValue(1)); 6399 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6400 } 6401 ArgOffset += 16; 6402 for (unsigned i=0; i<16; i+=PtrByteSize) { 6403 if (GPR_idx == NumGPRs) 6404 break; 6405 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6406 DAG.getConstant(i, dl, PtrVT)); 6407 SDValue Load = 6408 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6409 MemOpChains.push_back(Load.getValue(1)); 6410 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6411 } 6412 break; 6413 } 6414 6415 // Non-varargs Altivec params go into VRs or on the stack. 6416 if (VR_idx != NumVRs) { 6417 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6418 } else { 6419 if (IsFastCall) 6420 ComputePtrOff(); 6421 6422 assert(HasParameterArea && 6423 "Parameter area must exist to pass an argument in memory."); 6424 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6425 true, CFlags.IsTailCall, true, MemOpChains, 6426 TailCallArguments, dl); 6427 if (IsFastCall) 6428 ArgOffset += 16; 6429 } 6430 6431 if (!IsFastCall) 6432 ArgOffset += 16; 6433 break; 6434 } 6435 } 6436 6437 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6438 "mismatch in size of parameter area"); 6439 (void)NumBytesActuallyUsed; 6440 6441 if (!MemOpChains.empty()) 6442 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6443 6444 // Check if this is an indirect call (MTCTR/BCTRL). 6445 // See prepareDescriptorIndirectCall and buildCallOperands for more 6446 // information about calls through function pointers in the 64-bit SVR4 ABI. 6447 if (CFlags.IsIndirect) { 6448 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6449 // caller in the TOC save area. 6450 if (isTOCSaveRestoreRequired(Subtarget)) { 6451 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6452 // Load r2 into a virtual register and store it to the TOC save area. 6453 setUsesTOCBasePtr(DAG); 6454 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6455 // TOC save area offset. 6456 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6457 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6458 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6459 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6460 MachinePointerInfo::getStack( 6461 DAG.getMachineFunction(), TOCSaveOffset)); 6462 } 6463 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6464 // This does not mean the MTCTR instruction must use R12; it's easier 6465 // to model this as an extra parameter, so do that. 6466 if (isELFv2ABI && !CFlags.IsPatchPoint) 6467 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6468 } 6469 6470 // Build a sequence of copy-to-reg nodes chained together with token chain 6471 // and flag operands which copy the outgoing args into the appropriate regs. 6472 SDValue InFlag; 6473 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6474 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6475 RegsToPass[i].second, InFlag); 6476 InFlag = Chain.getValue(1); 6477 } 6478 6479 if (CFlags.IsTailCall && !IsSibCall) 6480 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6481 TailCallArguments); 6482 6483 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6484 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6485 } 6486 6487 SDValue PPCTargetLowering::LowerCall_Darwin( 6488 SDValue Chain, SDValue Callee, CallFlags CFlags, 6489 const SmallVectorImpl<ISD::OutputArg> &Outs, 6490 const SmallVectorImpl<SDValue> &OutVals, 6491 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6492 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6493 const CallBase *CB) const { 6494 unsigned NumOps = Outs.size(); 6495 6496 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6497 bool isPPC64 = PtrVT == MVT::i64; 6498 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6499 6500 MachineFunction &MF = DAG.getMachineFunction(); 6501 6502 // Mark this function as potentially containing a function that contains a 6503 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6504 // and restoring the callers stack pointer in this functions epilog. This is 6505 // done because by tail calling the called function might overwrite the value 6506 // in this function's (MF) stack pointer stack slot 0(SP). 6507 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6508 CFlags.CallConv == CallingConv::Fast) 6509 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6510 6511 // Count how many bytes are to be pushed on the stack, including the linkage 6512 // area, and parameter passing area. We start with 24/48 bytes, which is 6513 // prereserved space for [SP][CR][LR][3 x unused]. 6514 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6515 unsigned NumBytes = LinkageSize; 6516 6517 // Add up all the space actually used. 6518 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6519 // they all go in registers, but we must reserve stack space for them for 6520 // possible use by the caller. In varargs or 64-bit calls, parameters are 6521 // assigned stack space in order, with padding so Altivec parameters are 6522 // 16-byte aligned. 6523 unsigned nAltivecParamsAtEnd = 0; 6524 for (unsigned i = 0; i != NumOps; ++i) { 6525 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6526 EVT ArgVT = Outs[i].VT; 6527 // Varargs Altivec parameters are padded to a 16 byte boundary. 6528 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6529 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6530 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6531 if (!CFlags.IsVarArg && !isPPC64) { 6532 // Non-varargs Altivec parameters go after all the non-Altivec 6533 // parameters; handle those later so we know how much padding we need. 6534 nAltivecParamsAtEnd++; 6535 continue; 6536 } 6537 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6538 NumBytes = ((NumBytes+15)/16)*16; 6539 } 6540 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6541 } 6542 6543 // Allow for Altivec parameters at the end, if needed. 6544 if (nAltivecParamsAtEnd) { 6545 NumBytes = ((NumBytes+15)/16)*16; 6546 NumBytes += 16*nAltivecParamsAtEnd; 6547 } 6548 6549 // The prolog code of the callee may store up to 8 GPR argument registers to 6550 // the stack, allowing va_start to index over them in memory if its varargs. 6551 // Because we cannot tell if this is needed on the caller side, we have to 6552 // conservatively assume that it is needed. As such, make sure we have at 6553 // least enough stack space for the caller to store the 8 GPRs. 6554 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6555 6556 // Tail call needs the stack to be aligned. 6557 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6558 CFlags.CallConv == CallingConv::Fast) 6559 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6560 6561 // Calculate by how many bytes the stack has to be adjusted in case of tail 6562 // call optimization. 6563 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6564 6565 // To protect arguments on the stack from being clobbered in a tail call, 6566 // force all the loads to happen before doing any other lowering. 6567 if (CFlags.IsTailCall) 6568 Chain = DAG.getStackArgumentTokenFactor(Chain); 6569 6570 // Adjust the stack pointer for the new arguments... 6571 // These operations are automatically eliminated by the prolog/epilog pass 6572 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6573 SDValue CallSeqStart = Chain; 6574 6575 // Load the return address and frame pointer so it can be move somewhere else 6576 // later. 6577 SDValue LROp, FPOp; 6578 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6579 6580 // Set up a copy of the stack pointer for use loading and storing any 6581 // arguments that may not fit in the registers available for argument 6582 // passing. 6583 SDValue StackPtr; 6584 if (isPPC64) 6585 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6586 else 6587 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6588 6589 // Figure out which arguments are going to go in registers, and which in 6590 // memory. Also, if this is a vararg function, floating point operations 6591 // must be stored to our stack, and loaded into integer regs as well, if 6592 // any integer regs are available for argument passing. 6593 unsigned ArgOffset = LinkageSize; 6594 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6595 6596 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6597 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6598 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6599 }; 6600 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6601 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6602 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6603 }; 6604 static const MCPhysReg VR[] = { 6605 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6606 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6607 }; 6608 const unsigned NumGPRs = array_lengthof(GPR_32); 6609 const unsigned NumFPRs = 13; 6610 const unsigned NumVRs = array_lengthof(VR); 6611 6612 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6613 6614 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6615 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6616 6617 SmallVector<SDValue, 8> MemOpChains; 6618 for (unsigned i = 0; i != NumOps; ++i) { 6619 SDValue Arg = OutVals[i]; 6620 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6621 6622 // PtrOff will be used to store the current argument to the stack if a 6623 // register cannot be found for it. 6624 SDValue PtrOff; 6625 6626 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6627 6628 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6629 6630 // On PPC64, promote integers to 64-bit values. 6631 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6632 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6633 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6634 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6635 } 6636 6637 // FIXME memcpy is used way more than necessary. Correctness first. 6638 // Note: "by value" is code for passing a structure by value, not 6639 // basic types. 6640 if (Flags.isByVal()) { 6641 unsigned Size = Flags.getByValSize(); 6642 // Very small objects are passed right-justified. Everything else is 6643 // passed left-justified. 6644 if (Size==1 || Size==2) { 6645 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6646 if (GPR_idx != NumGPRs) { 6647 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6648 MachinePointerInfo(), VT); 6649 MemOpChains.push_back(Load.getValue(1)); 6650 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6651 6652 ArgOffset += PtrByteSize; 6653 } else { 6654 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6655 PtrOff.getValueType()); 6656 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6657 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6658 CallSeqStart, 6659 Flags, DAG, dl); 6660 ArgOffset += PtrByteSize; 6661 } 6662 continue; 6663 } 6664 // Copy entire object into memory. There are cases where gcc-generated 6665 // code assumes it is there, even if it could be put entirely into 6666 // registers. (This is not what the doc says.) 6667 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6668 CallSeqStart, 6669 Flags, DAG, dl); 6670 6671 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6672 // copy the pieces of the object that fit into registers from the 6673 // parameter save area. 6674 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6675 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6676 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6677 if (GPR_idx != NumGPRs) { 6678 SDValue Load = 6679 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6680 MemOpChains.push_back(Load.getValue(1)); 6681 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6682 ArgOffset += PtrByteSize; 6683 } else { 6684 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6685 break; 6686 } 6687 } 6688 continue; 6689 } 6690 6691 switch (Arg.getSimpleValueType().SimpleTy) { 6692 default: llvm_unreachable("Unexpected ValueType for argument!"); 6693 case MVT::i1: 6694 case MVT::i32: 6695 case MVT::i64: 6696 if (GPR_idx != NumGPRs) { 6697 if (Arg.getValueType() == MVT::i1) 6698 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6699 6700 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6701 } else { 6702 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6703 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6704 TailCallArguments, dl); 6705 } 6706 ArgOffset += PtrByteSize; 6707 break; 6708 case MVT::f32: 6709 case MVT::f64: 6710 if (FPR_idx != NumFPRs) { 6711 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6712 6713 if (CFlags.IsVarArg) { 6714 SDValue Store = 6715 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6716 MemOpChains.push_back(Store); 6717 6718 // Float varargs are always shadowed in available integer registers 6719 if (GPR_idx != NumGPRs) { 6720 SDValue Load = 6721 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6722 MemOpChains.push_back(Load.getValue(1)); 6723 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6724 } 6725 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6726 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6727 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6728 SDValue Load = 6729 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6730 MemOpChains.push_back(Load.getValue(1)); 6731 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6732 } 6733 } else { 6734 // If we have any FPRs remaining, we may also have GPRs remaining. 6735 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6736 // GPRs. 6737 if (GPR_idx != NumGPRs) 6738 ++GPR_idx; 6739 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6740 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6741 ++GPR_idx; 6742 } 6743 } else 6744 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6745 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6746 TailCallArguments, dl); 6747 if (isPPC64) 6748 ArgOffset += 8; 6749 else 6750 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6751 break; 6752 case MVT::v4f32: 6753 case MVT::v4i32: 6754 case MVT::v8i16: 6755 case MVT::v16i8: 6756 if (CFlags.IsVarArg) { 6757 // These go aligned on the stack, or in the corresponding R registers 6758 // when within range. The Darwin PPC ABI doc claims they also go in 6759 // V registers; in fact gcc does this only for arguments that are 6760 // prototyped, not for those that match the ... We do it for all 6761 // arguments, seems to work. 6762 while (ArgOffset % 16 !=0) { 6763 ArgOffset += PtrByteSize; 6764 if (GPR_idx != NumGPRs) 6765 GPR_idx++; 6766 } 6767 // We could elide this store in the case where the object fits 6768 // entirely in R registers. Maybe later. 6769 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6770 DAG.getConstant(ArgOffset, dl, PtrVT)); 6771 SDValue Store = 6772 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6773 MemOpChains.push_back(Store); 6774 if (VR_idx != NumVRs) { 6775 SDValue Load = 6776 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6777 MemOpChains.push_back(Load.getValue(1)); 6778 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6779 } 6780 ArgOffset += 16; 6781 for (unsigned i=0; i<16; i+=PtrByteSize) { 6782 if (GPR_idx == NumGPRs) 6783 break; 6784 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6785 DAG.getConstant(i, dl, PtrVT)); 6786 SDValue Load = 6787 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6788 MemOpChains.push_back(Load.getValue(1)); 6789 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6790 } 6791 break; 6792 } 6793 6794 // Non-varargs Altivec params generally go in registers, but have 6795 // stack space allocated at the end. 6796 if (VR_idx != NumVRs) { 6797 // Doesn't have GPR space allocated. 6798 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6799 } else if (nAltivecParamsAtEnd==0) { 6800 // We are emitting Altivec params in order. 6801 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6802 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6803 TailCallArguments, dl); 6804 ArgOffset += 16; 6805 } 6806 break; 6807 } 6808 } 6809 // If all Altivec parameters fit in registers, as they usually do, 6810 // they get stack space following the non-Altivec parameters. We 6811 // don't track this here because nobody below needs it. 6812 // If there are more Altivec parameters than fit in registers emit 6813 // the stores here. 6814 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6815 unsigned j = 0; 6816 // Offset is aligned; skip 1st 12 params which go in V registers. 6817 ArgOffset = ((ArgOffset+15)/16)*16; 6818 ArgOffset += 12*16; 6819 for (unsigned i = 0; i != NumOps; ++i) { 6820 SDValue Arg = OutVals[i]; 6821 EVT ArgType = Outs[i].VT; 6822 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6823 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6824 if (++j > NumVRs) { 6825 SDValue PtrOff; 6826 // We are emitting Altivec params in order. 6827 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6828 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6829 TailCallArguments, dl); 6830 ArgOffset += 16; 6831 } 6832 } 6833 } 6834 } 6835 6836 if (!MemOpChains.empty()) 6837 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6838 6839 // On Darwin, R12 must contain the address of an indirect callee. This does 6840 // not mean the MTCTR instruction must use R12; it's easier to model this as 6841 // an extra parameter, so do that. 6842 if (CFlags.IsIndirect) { 6843 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6844 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6845 PPC::R12), Callee)); 6846 } 6847 6848 // Build a sequence of copy-to-reg nodes chained together with token chain 6849 // and flag operands which copy the outgoing args into the appropriate regs. 6850 SDValue InFlag; 6851 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6852 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6853 RegsToPass[i].second, InFlag); 6854 InFlag = Chain.getValue(1); 6855 } 6856 6857 if (CFlags.IsTailCall) 6858 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6859 TailCallArguments); 6860 6861 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6862 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6863 } 6864 6865 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6866 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6867 CCState &State) { 6868 6869 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6870 State.getMachineFunction().getSubtarget()); 6871 const bool IsPPC64 = Subtarget.isPPC64(); 6872 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6873 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6874 6875 assert((!ValVT.isInteger() || 6876 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6877 "Integer argument exceeds register size: should have been legalized"); 6878 6879 if (ValVT == MVT::f128) 6880 report_fatal_error("f128 is unimplemented on AIX."); 6881 6882 if (ArgFlags.isNest()) 6883 report_fatal_error("Nest arguments are unimplemented."); 6884 6885 if (ValVT.isVector() || LocVT.isVector()) 6886 report_fatal_error("Vector arguments are unimplemented on AIX."); 6887 6888 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6889 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6890 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6891 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6892 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6893 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6894 6895 if (ArgFlags.isByVal()) { 6896 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6897 report_fatal_error("Pass-by-value arguments with alignment greater than " 6898 "register width are not supported."); 6899 6900 const unsigned ByValSize = ArgFlags.getByValSize(); 6901 6902 // An empty aggregate parameter takes up no storage and no registers, 6903 // but needs a MemLoc for a stack slot for the formal arguments side. 6904 if (ByValSize == 0) { 6905 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6906 State.getNextStackOffset(), RegVT, 6907 LocInfo)); 6908 return false; 6909 } 6910 6911 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6912 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6913 for (const unsigned E = Offset + StackSize; Offset < E; 6914 Offset += PtrAlign.value()) { 6915 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6916 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6917 else { 6918 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6919 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6920 LocInfo)); 6921 break; 6922 } 6923 } 6924 return false; 6925 } 6926 6927 // Arguments always reserve parameter save area. 6928 switch (ValVT.SimpleTy) { 6929 default: 6930 report_fatal_error("Unhandled value type for argument."); 6931 case MVT::i64: 6932 // i64 arguments should have been split to i32 for PPC32. 6933 assert(IsPPC64 && "PPC32 should have split i64 values."); 6934 LLVM_FALLTHROUGH; 6935 case MVT::i1: 6936 case MVT::i32: { 6937 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6938 // AIX integer arguments are always passed in register width. 6939 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6940 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6941 : CCValAssign::LocInfo::ZExt; 6942 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6943 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6944 else 6945 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6946 6947 return false; 6948 } 6949 case MVT::f32: 6950 case MVT::f64: { 6951 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6952 const unsigned StoreSize = LocVT.getStoreSize(); 6953 // Floats are always 4-byte aligned in the PSA on AIX. 6954 // This includes f64 in 64-bit mode for ABI compatibility. 6955 const unsigned Offset = 6956 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6957 unsigned FReg = State.AllocateReg(FPR); 6958 if (FReg) 6959 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6960 6961 // Reserve and initialize GPRs or initialize the PSA as required. 6962 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6963 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6964 assert(FReg && "An FPR should be available when a GPR is reserved."); 6965 if (State.isVarArg()) { 6966 // Successfully reserved GPRs are only initialized for vararg calls. 6967 // Custom handling is required for: 6968 // f64 in PPC32 needs to be split into 2 GPRs. 6969 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6970 State.addLoc( 6971 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6972 } 6973 } else { 6974 // If there are insufficient GPRs, the PSA needs to be initialized. 6975 // Initialization occurs even if an FPR was initialized for 6976 // compatibility with the AIX XL compiler. The full memory for the 6977 // argument will be initialized even if a prior word is saved in GPR. 6978 // A custom memLoc is used when the argument also passes in FPR so 6979 // that the callee handling can skip over it easily. 6980 State.addLoc( 6981 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6982 LocInfo) 6983 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6984 break; 6985 } 6986 } 6987 6988 return false; 6989 } 6990 } 6991 return true; 6992 } 6993 6994 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6995 bool IsPPC64) { 6996 assert((IsPPC64 || SVT != MVT::i64) && 6997 "i64 should have been split for 32-bit codegen."); 6998 6999 switch (SVT) { 7000 default: 7001 report_fatal_error("Unexpected value type for formal argument"); 7002 case MVT::i1: 7003 case MVT::i32: 7004 case MVT::i64: 7005 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7006 case MVT::f32: 7007 return &PPC::F4RCRegClass; 7008 case MVT::f64: 7009 return &PPC::F8RCRegClass; 7010 } 7011 } 7012 7013 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 7014 SelectionDAG &DAG, SDValue ArgValue, 7015 MVT LocVT, const SDLoc &dl) { 7016 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 7017 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 7018 7019 if (Flags.isSExt()) 7020 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 7021 DAG.getValueType(ValVT)); 7022 else if (Flags.isZExt()) 7023 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 7024 DAG.getValueType(ValVT)); 7025 7026 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 7027 } 7028 7029 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 7030 const unsigned LASize = FL->getLinkageSize(); 7031 7032 if (PPC::GPRCRegClass.contains(Reg)) { 7033 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 7034 "Reg must be a valid argument register!"); 7035 return LASize + 4 * (Reg - PPC::R3); 7036 } 7037 7038 if (PPC::G8RCRegClass.contains(Reg)) { 7039 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 7040 "Reg must be a valid argument register!"); 7041 return LASize + 8 * (Reg - PPC::X3); 7042 } 7043 7044 llvm_unreachable("Only general purpose registers expected."); 7045 } 7046 7047 // AIX ABI Stack Frame Layout: 7048 // 7049 // Low Memory +--------------------------------------------+ 7050 // SP +---> | Back chain | ---+ 7051 // | +--------------------------------------------+ | 7052 // | | Saved Condition Register | | 7053 // | +--------------------------------------------+ | 7054 // | | Saved Linkage Register | | 7055 // | +--------------------------------------------+ | Linkage Area 7056 // | | Reserved for compilers | | 7057 // | +--------------------------------------------+ | 7058 // | | Reserved for binders | | 7059 // | +--------------------------------------------+ | 7060 // | | Saved TOC pointer | ---+ 7061 // | +--------------------------------------------+ 7062 // | | Parameter save area | 7063 // | +--------------------------------------------+ 7064 // | | Alloca space | 7065 // | +--------------------------------------------+ 7066 // | | Local variable space | 7067 // | +--------------------------------------------+ 7068 // | | Float/int conversion temporary | 7069 // | +--------------------------------------------+ 7070 // | | Save area for AltiVec registers | 7071 // | +--------------------------------------------+ 7072 // | | AltiVec alignment padding | 7073 // | +--------------------------------------------+ 7074 // | | Save area for VRSAVE register | 7075 // | +--------------------------------------------+ 7076 // | | Save area for General Purpose registers | 7077 // | +--------------------------------------------+ 7078 // | | Save area for Floating Point registers | 7079 // | +--------------------------------------------+ 7080 // +---- | Back chain | 7081 // High Memory +--------------------------------------------+ 7082 // 7083 // Specifications: 7084 // AIX 7.2 Assembler Language Reference 7085 // Subroutine linkage convention 7086 7087 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7088 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7089 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7090 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7091 7092 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7093 CallConv == CallingConv::Fast) && 7094 "Unexpected calling convention!"); 7095 7096 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7097 report_fatal_error("Tail call support is unimplemented on AIX."); 7098 7099 if (useSoftFloat()) 7100 report_fatal_error("Soft float support is unimplemented on AIX."); 7101 7102 const PPCSubtarget &Subtarget = 7103 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7104 7105 const bool IsPPC64 = Subtarget.isPPC64(); 7106 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7107 7108 // Assign locations to all of the incoming arguments. 7109 SmallVector<CCValAssign, 16> ArgLocs; 7110 MachineFunction &MF = DAG.getMachineFunction(); 7111 MachineFrameInfo &MFI = MF.getFrameInfo(); 7112 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7113 7114 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7115 // Reserve space for the linkage area on the stack. 7116 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7117 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7118 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7119 7120 SmallVector<SDValue, 8> MemOps; 7121 7122 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7123 CCValAssign &VA = ArgLocs[I++]; 7124 MVT LocVT = VA.getLocVT(); 7125 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7126 7127 // For compatibility with the AIX XL compiler, the float args in the 7128 // parameter save area are initialized even if the argument is available 7129 // in register. The caller is required to initialize both the register 7130 // and memory, however, the callee can choose to expect it in either. 7131 // The memloc is dismissed here because the argument is retrieved from 7132 // the register. 7133 if (VA.isMemLoc() && VA.needsCustom()) 7134 continue; 7135 7136 if (Flags.isByVal() && VA.isMemLoc()) { 7137 const unsigned Size = 7138 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7139 PtrByteSize); 7140 const int FI = MF.getFrameInfo().CreateFixedObject( 7141 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7142 /* IsAliased */ true); 7143 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7144 InVals.push_back(FIN); 7145 7146 continue; 7147 } 7148 7149 if (Flags.isByVal()) { 7150 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7151 7152 const MCPhysReg ArgReg = VA.getLocReg(); 7153 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7154 7155 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7156 report_fatal_error("Over aligned byvals not supported yet."); 7157 7158 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7159 const int FI = MF.getFrameInfo().CreateFixedObject( 7160 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7161 /* IsAliased */ true); 7162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7163 InVals.push_back(FIN); 7164 7165 // Add live ins for all the RegLocs for the same ByVal. 7166 const TargetRegisterClass *RegClass = 7167 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7168 7169 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7170 unsigned Offset) { 7171 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7172 // Since the callers side has left justified the aggregate in the 7173 // register, we can simply store the entire register into the stack 7174 // slot. 7175 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7176 // The store to the fixedstack object is needed becuase accessing a 7177 // field of the ByVal will use a gep and load. Ideally we will optimize 7178 // to extracting the value from the register directly, and elide the 7179 // stores when the arguments address is not taken, but that will need to 7180 // be future work. 7181 SDValue Store = DAG.getStore( 7182 CopyFrom.getValue(1), dl, CopyFrom, 7183 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7184 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7185 7186 MemOps.push_back(Store); 7187 }; 7188 7189 unsigned Offset = 0; 7190 HandleRegLoc(VA.getLocReg(), Offset); 7191 Offset += PtrByteSize; 7192 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7193 Offset += PtrByteSize) { 7194 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7195 "RegLocs should be for ByVal argument."); 7196 7197 const CCValAssign RL = ArgLocs[I++]; 7198 HandleRegLoc(RL.getLocReg(), Offset); 7199 } 7200 7201 if (Offset != StackSize) { 7202 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7203 "Expected MemLoc for remaining bytes."); 7204 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7205 // Consume the MemLoc.The InVal has already been emitted, so nothing 7206 // more needs to be done. 7207 ++I; 7208 } 7209 7210 continue; 7211 } 7212 7213 EVT ValVT = VA.getValVT(); 7214 if (VA.isRegLoc() && !VA.needsCustom()) { 7215 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7216 unsigned VReg = 7217 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7218 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7219 if (ValVT.isScalarInteger() && 7220 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7221 ArgValue = 7222 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7223 } 7224 InVals.push_back(ArgValue); 7225 continue; 7226 } 7227 if (VA.isMemLoc()) { 7228 const unsigned LocSize = LocVT.getStoreSize(); 7229 const unsigned ValSize = ValVT.getStoreSize(); 7230 assert((ValSize <= LocSize) && 7231 "Object size is larger than size of MemLoc"); 7232 int CurArgOffset = VA.getLocMemOffset(); 7233 // Objects are right-justified because AIX is big-endian. 7234 if (LocSize > ValSize) 7235 CurArgOffset += LocSize - ValSize; 7236 // Potential tail calls could cause overwriting of argument stack slots. 7237 const bool IsImmutable = 7238 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7239 (CallConv == CallingConv::Fast)); 7240 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7241 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7242 SDValue ArgValue = 7243 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7244 InVals.push_back(ArgValue); 7245 continue; 7246 } 7247 } 7248 7249 // On AIX a minimum of 8 words is saved to the parameter save area. 7250 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7251 // Area that is at least reserved in the caller of this function. 7252 unsigned CallerReservedArea = 7253 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7254 7255 // Set the size that is at least reserved in caller of this function. Tail 7256 // call optimized function's reserved stack space needs to be aligned so 7257 // that taking the difference between two stack areas will result in an 7258 // aligned stack. 7259 CallerReservedArea = 7260 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7261 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7262 FuncInfo->setMinReservedArea(CallerReservedArea); 7263 7264 if (isVarArg) { 7265 FuncInfo->setVarArgsFrameIndex( 7266 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7267 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7268 7269 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7270 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7271 7272 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7273 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7274 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7275 7276 // The fixed integer arguments of a variadic function are stored to the 7277 // VarArgsFrameIndex on the stack so that they may be loaded by 7278 // dereferencing the result of va_next. 7279 for (unsigned GPRIndex = 7280 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7281 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7282 7283 const unsigned VReg = 7284 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7285 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7286 7287 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7288 SDValue Store = 7289 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7290 MemOps.push_back(Store); 7291 // Increment the address for the next argument to store. 7292 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7293 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7294 } 7295 } 7296 7297 if (!MemOps.empty()) 7298 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7299 7300 return Chain; 7301 } 7302 7303 SDValue PPCTargetLowering::LowerCall_AIX( 7304 SDValue Chain, SDValue Callee, CallFlags CFlags, 7305 const SmallVectorImpl<ISD::OutputArg> &Outs, 7306 const SmallVectorImpl<SDValue> &OutVals, 7307 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7308 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7309 const CallBase *CB) const { 7310 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7311 // AIX ABI stack frame layout. 7312 7313 assert((CFlags.CallConv == CallingConv::C || 7314 CFlags.CallConv == CallingConv::Cold || 7315 CFlags.CallConv == CallingConv::Fast) && 7316 "Unexpected calling convention!"); 7317 7318 if (CFlags.IsPatchPoint) 7319 report_fatal_error("This call type is unimplemented on AIX."); 7320 7321 const PPCSubtarget& Subtarget = 7322 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7323 if (Subtarget.hasAltivec()) 7324 report_fatal_error("Altivec support is unimplemented on AIX."); 7325 7326 MachineFunction &MF = DAG.getMachineFunction(); 7327 SmallVector<CCValAssign, 16> ArgLocs; 7328 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7329 *DAG.getContext()); 7330 7331 // Reserve space for the linkage save area (LSA) on the stack. 7332 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7333 // [SP][CR][LR][2 x reserved][TOC]. 7334 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7335 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7336 const bool IsPPC64 = Subtarget.isPPC64(); 7337 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7338 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7339 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7340 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7341 7342 // The prolog code of the callee may store up to 8 GPR argument registers to 7343 // the stack, allowing va_start to index over them in memory if the callee 7344 // is variadic. 7345 // Because we cannot tell if this is needed on the caller side, we have to 7346 // conservatively assume that it is needed. As such, make sure we have at 7347 // least enough stack space for the caller to store the 8 GPRs. 7348 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7349 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7350 CCInfo.getNextStackOffset()); 7351 7352 // Adjust the stack pointer for the new arguments... 7353 // These operations are automatically eliminated by the prolog/epilog pass. 7354 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7355 SDValue CallSeqStart = Chain; 7356 7357 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7358 SmallVector<SDValue, 8> MemOpChains; 7359 7360 // Set up a copy of the stack pointer for loading and storing any 7361 // arguments that may not fit in the registers available for argument 7362 // passing. 7363 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7364 : DAG.getRegister(PPC::R1, MVT::i32); 7365 7366 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7367 const unsigned ValNo = ArgLocs[I].getValNo(); 7368 SDValue Arg = OutVals[ValNo]; 7369 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7370 7371 if (Flags.isByVal()) { 7372 const unsigned ByValSize = Flags.getByValSize(); 7373 7374 // Nothing to do for zero-sized ByVals on the caller side. 7375 if (!ByValSize) { 7376 ++I; 7377 continue; 7378 } 7379 7380 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7381 return DAG.getExtLoad( 7382 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7383 (LoadOffset != 0) 7384 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7385 : Arg, 7386 MachinePointerInfo(), VT); 7387 }; 7388 7389 unsigned LoadOffset = 0; 7390 7391 // Initialize registers, which are fully occupied by the by-val argument. 7392 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7393 SDValue Load = GetLoad(PtrVT, LoadOffset); 7394 MemOpChains.push_back(Load.getValue(1)); 7395 LoadOffset += PtrByteSize; 7396 const CCValAssign &ByValVA = ArgLocs[I++]; 7397 assert(ByValVA.getValNo() == ValNo && 7398 "Unexpected location for pass-by-value argument."); 7399 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7400 } 7401 7402 if (LoadOffset == ByValSize) 7403 continue; 7404 7405 // There must be one more loc to handle the remainder. 7406 assert(ArgLocs[I].getValNo() == ValNo && 7407 "Expected additional location for by-value argument."); 7408 7409 if (ArgLocs[I].isMemLoc()) { 7410 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7411 const CCValAssign &ByValVA = ArgLocs[I++]; 7412 ISD::ArgFlagsTy MemcpyFlags = Flags; 7413 // Only memcpy the bytes that don't pass in register. 7414 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7415 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7416 (LoadOffset != 0) 7417 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7418 : Arg, 7419 DAG.getObjectPtrOffset(dl, StackPtr, 7420 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7421 CallSeqStart, MemcpyFlags, DAG, dl); 7422 continue; 7423 } 7424 7425 // Initialize the final register residue. 7426 // Any residue that occupies the final by-val arg register must be 7427 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7428 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7429 // 2 and 1 byte loads. 7430 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7431 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7432 "Unexpected register residue for by-value argument."); 7433 SDValue ResidueVal; 7434 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7435 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7436 const MVT VT = 7437 N == 1 ? MVT::i8 7438 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7439 SDValue Load = GetLoad(VT, LoadOffset); 7440 MemOpChains.push_back(Load.getValue(1)); 7441 LoadOffset += N; 7442 Bytes += N; 7443 7444 // By-val arguments are passed left-justfied in register. 7445 // Every load here needs to be shifted, otherwise a full register load 7446 // should have been used. 7447 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7448 "Unexpected load emitted during handling of pass-by-value " 7449 "argument."); 7450 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7451 EVT ShiftAmountTy = 7452 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7453 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7454 SDValue ShiftedLoad = 7455 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7456 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7457 ShiftedLoad) 7458 : ShiftedLoad; 7459 } 7460 7461 const CCValAssign &ByValVA = ArgLocs[I++]; 7462 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7463 continue; 7464 } 7465 7466 CCValAssign &VA = ArgLocs[I++]; 7467 const MVT LocVT = VA.getLocVT(); 7468 const MVT ValVT = VA.getValVT(); 7469 7470 switch (VA.getLocInfo()) { 7471 default: 7472 report_fatal_error("Unexpected argument extension type."); 7473 case CCValAssign::Full: 7474 break; 7475 case CCValAssign::ZExt: 7476 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7477 break; 7478 case CCValAssign::SExt: 7479 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7480 break; 7481 } 7482 7483 if (VA.isRegLoc() && !VA.needsCustom()) { 7484 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7485 continue; 7486 } 7487 7488 if (VA.isMemLoc()) { 7489 SDValue PtrOff = 7490 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7491 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7492 MemOpChains.push_back( 7493 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7494 7495 continue; 7496 } 7497 7498 // Custom handling is used for GPR initializations for vararg float 7499 // arguments. 7500 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7501 ValVT.isFloatingPoint() && LocVT.isInteger() && 7502 "Unexpected register handling for calling convention."); 7503 7504 SDValue ArgAsInt = 7505 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7506 7507 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7508 // f32 in 32-bit GPR 7509 // f64 in 64-bit GPR 7510 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7511 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7512 // f32 in 64-bit GPR. 7513 RegsToPass.push_back(std::make_pair( 7514 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7515 else { 7516 // f64 in two 32-bit GPRs 7517 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7518 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7519 "Unexpected custom register for argument!"); 7520 CCValAssign &GPR1 = VA; 7521 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7522 DAG.getConstant(32, dl, MVT::i8)); 7523 RegsToPass.push_back(std::make_pair( 7524 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7525 7526 if (I != E) { 7527 // If only 1 GPR was available, there will only be one custom GPR and 7528 // the argument will also pass in memory. 7529 CCValAssign &PeekArg = ArgLocs[I]; 7530 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7531 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7532 CCValAssign &GPR2 = ArgLocs[I++]; 7533 RegsToPass.push_back(std::make_pair( 7534 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7535 } 7536 } 7537 } 7538 } 7539 7540 if (!MemOpChains.empty()) 7541 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7542 7543 // For indirect calls, we need to save the TOC base to the stack for 7544 // restoration after the call. 7545 if (CFlags.IsIndirect) { 7546 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7547 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7548 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7549 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7550 const unsigned TOCSaveOffset = 7551 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7552 7553 setUsesTOCBasePtr(DAG); 7554 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7555 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7556 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7557 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7558 Chain = DAG.getStore( 7559 Val.getValue(1), dl, Val, AddPtr, 7560 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7561 } 7562 7563 // Build a sequence of copy-to-reg nodes chained together with token chain 7564 // and flag operands which copy the outgoing args into the appropriate regs. 7565 SDValue InFlag; 7566 for (auto Reg : RegsToPass) { 7567 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7568 InFlag = Chain.getValue(1); 7569 } 7570 7571 const int SPDiff = 0; 7572 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7573 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7574 } 7575 7576 bool 7577 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7578 MachineFunction &MF, bool isVarArg, 7579 const SmallVectorImpl<ISD::OutputArg> &Outs, 7580 LLVMContext &Context) const { 7581 SmallVector<CCValAssign, 16> RVLocs; 7582 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7583 return CCInfo.CheckReturn( 7584 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7585 ? RetCC_PPC_Cold 7586 : RetCC_PPC); 7587 } 7588 7589 SDValue 7590 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7591 bool isVarArg, 7592 const SmallVectorImpl<ISD::OutputArg> &Outs, 7593 const SmallVectorImpl<SDValue> &OutVals, 7594 const SDLoc &dl, SelectionDAG &DAG) const { 7595 SmallVector<CCValAssign, 16> RVLocs; 7596 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7597 *DAG.getContext()); 7598 CCInfo.AnalyzeReturn(Outs, 7599 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7600 ? RetCC_PPC_Cold 7601 : RetCC_PPC); 7602 7603 SDValue Flag; 7604 SmallVector<SDValue, 4> RetOps(1, Chain); 7605 7606 // Copy the result values into the output registers. 7607 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7608 CCValAssign &VA = RVLocs[i]; 7609 assert(VA.isRegLoc() && "Can only return in registers!"); 7610 7611 SDValue Arg = OutVals[RealResIdx]; 7612 7613 switch (VA.getLocInfo()) { 7614 default: llvm_unreachable("Unknown loc info!"); 7615 case CCValAssign::Full: break; 7616 case CCValAssign::AExt: 7617 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7618 break; 7619 case CCValAssign::ZExt: 7620 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7621 break; 7622 case CCValAssign::SExt: 7623 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7624 break; 7625 } 7626 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7627 bool isLittleEndian = Subtarget.isLittleEndian(); 7628 // Legalize ret f64 -> ret 2 x i32. 7629 SDValue SVal = 7630 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7631 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7632 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7633 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7634 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7635 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7636 Flag = Chain.getValue(1); 7637 VA = RVLocs[++i]; // skip ahead to next loc 7638 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7639 } else 7640 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7641 Flag = Chain.getValue(1); 7642 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7643 } 7644 7645 RetOps[0] = Chain; // Update chain. 7646 7647 // Add the flag if we have it. 7648 if (Flag.getNode()) 7649 RetOps.push_back(Flag); 7650 7651 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7652 } 7653 7654 SDValue 7655 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7656 SelectionDAG &DAG) const { 7657 SDLoc dl(Op); 7658 7659 // Get the correct type for integers. 7660 EVT IntVT = Op.getValueType(); 7661 7662 // Get the inputs. 7663 SDValue Chain = Op.getOperand(0); 7664 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7665 // Build a DYNAREAOFFSET node. 7666 SDValue Ops[2] = {Chain, FPSIdx}; 7667 SDVTList VTs = DAG.getVTList(IntVT); 7668 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7669 } 7670 7671 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7672 SelectionDAG &DAG) const { 7673 // When we pop the dynamic allocation we need to restore the SP link. 7674 SDLoc dl(Op); 7675 7676 // Get the correct type for pointers. 7677 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7678 7679 // Construct the stack pointer operand. 7680 bool isPPC64 = Subtarget.isPPC64(); 7681 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7682 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7683 7684 // Get the operands for the STACKRESTORE. 7685 SDValue Chain = Op.getOperand(0); 7686 SDValue SaveSP = Op.getOperand(1); 7687 7688 // Load the old link SP. 7689 SDValue LoadLinkSP = 7690 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7691 7692 // Restore the stack pointer. 7693 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7694 7695 // Store the old link SP. 7696 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7697 } 7698 7699 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7700 MachineFunction &MF = DAG.getMachineFunction(); 7701 bool isPPC64 = Subtarget.isPPC64(); 7702 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7703 7704 // Get current frame pointer save index. The users of this index will be 7705 // primarily DYNALLOC instructions. 7706 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7707 int RASI = FI->getReturnAddrSaveIndex(); 7708 7709 // If the frame pointer save index hasn't been defined yet. 7710 if (!RASI) { 7711 // Find out what the fix offset of the frame pointer save area. 7712 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7713 // Allocate the frame index for frame pointer save area. 7714 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7715 // Save the result. 7716 FI->setReturnAddrSaveIndex(RASI); 7717 } 7718 return DAG.getFrameIndex(RASI, PtrVT); 7719 } 7720 7721 SDValue 7722 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7723 MachineFunction &MF = DAG.getMachineFunction(); 7724 bool isPPC64 = Subtarget.isPPC64(); 7725 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7726 7727 // Get current frame pointer save index. The users of this index will be 7728 // primarily DYNALLOC instructions. 7729 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7730 int FPSI = FI->getFramePointerSaveIndex(); 7731 7732 // If the frame pointer save index hasn't been defined yet. 7733 if (!FPSI) { 7734 // Find out what the fix offset of the frame pointer save area. 7735 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7736 // Allocate the frame index for frame pointer save area. 7737 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7738 // Save the result. 7739 FI->setFramePointerSaveIndex(FPSI); 7740 } 7741 return DAG.getFrameIndex(FPSI, PtrVT); 7742 } 7743 7744 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7745 SelectionDAG &DAG) const { 7746 MachineFunction &MF = DAG.getMachineFunction(); 7747 // Get the inputs. 7748 SDValue Chain = Op.getOperand(0); 7749 SDValue Size = Op.getOperand(1); 7750 SDLoc dl(Op); 7751 7752 // Get the correct type for pointers. 7753 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7754 // Negate the size. 7755 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7756 DAG.getConstant(0, dl, PtrVT), Size); 7757 // Construct a node for the frame pointer save index. 7758 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7759 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7760 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7761 if (hasInlineStackProbe(MF)) 7762 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7763 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7764 } 7765 7766 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7767 SelectionDAG &DAG) const { 7768 MachineFunction &MF = DAG.getMachineFunction(); 7769 7770 bool isPPC64 = Subtarget.isPPC64(); 7771 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7772 7773 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7774 return DAG.getFrameIndex(FI, PtrVT); 7775 } 7776 7777 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7778 SelectionDAG &DAG) const { 7779 SDLoc DL(Op); 7780 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7781 DAG.getVTList(MVT::i32, MVT::Other), 7782 Op.getOperand(0), Op.getOperand(1)); 7783 } 7784 7785 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7786 SelectionDAG &DAG) const { 7787 SDLoc DL(Op); 7788 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7789 Op.getOperand(0), Op.getOperand(1)); 7790 } 7791 7792 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7793 7794 assert(Op.getValueType() == MVT::i1 && 7795 "Custom lowering only for i1 loads"); 7796 7797 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7798 7799 SDLoc dl(Op); 7800 LoadSDNode *LD = cast<LoadSDNode>(Op); 7801 7802 SDValue Chain = LD->getChain(); 7803 SDValue BasePtr = LD->getBasePtr(); 7804 MachineMemOperand *MMO = LD->getMemOperand(); 7805 7806 SDValue NewLD = 7807 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7808 BasePtr, MVT::i8, MMO); 7809 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7810 7811 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7812 return DAG.getMergeValues(Ops, dl); 7813 } 7814 7815 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7816 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7817 "Custom lowering only for i1 stores"); 7818 7819 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7820 7821 SDLoc dl(Op); 7822 StoreSDNode *ST = cast<StoreSDNode>(Op); 7823 7824 SDValue Chain = ST->getChain(); 7825 SDValue BasePtr = ST->getBasePtr(); 7826 SDValue Value = ST->getValue(); 7827 MachineMemOperand *MMO = ST->getMemOperand(); 7828 7829 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7830 Value); 7831 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7832 } 7833 7834 // FIXME: Remove this once the ANDI glue bug is fixed: 7835 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7836 assert(Op.getValueType() == MVT::i1 && 7837 "Custom lowering only for i1 results"); 7838 7839 SDLoc DL(Op); 7840 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7841 } 7842 7843 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7844 SelectionDAG &DAG) const { 7845 7846 // Implements a vector truncate that fits in a vector register as a shuffle. 7847 // We want to legalize vector truncates down to where the source fits in 7848 // a vector register (and target is therefore smaller than vector register 7849 // size). At that point legalization will try to custom lower the sub-legal 7850 // result and get here - where we can contain the truncate as a single target 7851 // operation. 7852 7853 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7854 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7855 // 7856 // We will implement it for big-endian ordering as this (where x denotes 7857 // undefined): 7858 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7859 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7860 // 7861 // The same operation in little-endian ordering will be: 7862 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7863 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7864 7865 EVT TrgVT = Op.getValueType(); 7866 assert(TrgVT.isVector() && "Vector type expected."); 7867 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7868 EVT EltVT = TrgVT.getVectorElementType(); 7869 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7870 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7871 !isPowerOf2_32(EltVT.getSizeInBits())) 7872 return SDValue(); 7873 7874 SDValue N1 = Op.getOperand(0); 7875 EVT SrcVT = N1.getValueType(); 7876 unsigned SrcSize = SrcVT.getSizeInBits(); 7877 if (SrcSize > 256 || 7878 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7879 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7880 return SDValue(); 7881 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7882 return SDValue(); 7883 7884 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7885 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7886 7887 SDLoc DL(Op); 7888 SDValue Op1, Op2; 7889 if (SrcSize == 256) { 7890 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7891 EVT SplitVT = 7892 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7893 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7894 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7895 DAG.getConstant(0, DL, VecIdxTy)); 7896 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7897 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7898 } 7899 else { 7900 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7901 Op2 = DAG.getUNDEF(WideVT); 7902 } 7903 7904 // First list the elements we want to keep. 7905 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7906 SmallVector<int, 16> ShuffV; 7907 if (Subtarget.isLittleEndian()) 7908 for (unsigned i = 0; i < TrgNumElts; ++i) 7909 ShuffV.push_back(i * SizeMult); 7910 else 7911 for (unsigned i = 1; i <= TrgNumElts; ++i) 7912 ShuffV.push_back(i * SizeMult - 1); 7913 7914 // Populate the remaining elements with undefs. 7915 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7916 // ShuffV.push_back(i + WideNumElts); 7917 ShuffV.push_back(WideNumElts + 1); 7918 7919 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7920 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7921 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7922 } 7923 7924 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7925 /// possible. 7926 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7927 // Not FP, or using SPE? Not a fsel. 7928 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7929 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7930 return Op; 7931 7932 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7933 7934 EVT ResVT = Op.getValueType(); 7935 EVT CmpVT = Op.getOperand(0).getValueType(); 7936 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7937 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7938 SDLoc dl(Op); 7939 SDNodeFlags Flags = Op.getNode()->getFlags(); 7940 7941 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7942 // presence of infinities. 7943 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7944 switch (CC) { 7945 default: 7946 break; 7947 case ISD::SETOGT: 7948 case ISD::SETGT: 7949 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7950 case ISD::SETOLT: 7951 case ISD::SETLT: 7952 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7953 } 7954 } 7955 7956 // We might be able to do better than this under some circumstances, but in 7957 // general, fsel-based lowering of select is a finite-math-only optimization. 7958 // For more information, see section F.3 of the 2.06 ISA specification. 7959 // With ISA 3.0 7960 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7961 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7962 return Op; 7963 7964 // If the RHS of the comparison is a 0.0, we don't need to do the 7965 // subtraction at all. 7966 SDValue Sel1; 7967 if (isFloatingPointZero(RHS)) 7968 switch (CC) { 7969 default: break; // SETUO etc aren't handled by fsel. 7970 case ISD::SETNE: 7971 std::swap(TV, FV); 7972 LLVM_FALLTHROUGH; 7973 case ISD::SETEQ: 7974 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7975 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7976 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7977 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7978 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7979 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7980 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7981 case ISD::SETULT: 7982 case ISD::SETLT: 7983 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7984 LLVM_FALLTHROUGH; 7985 case ISD::SETOGE: 7986 case ISD::SETGE: 7987 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7988 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7989 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7990 case ISD::SETUGT: 7991 case ISD::SETGT: 7992 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7993 LLVM_FALLTHROUGH; 7994 case ISD::SETOLE: 7995 case ISD::SETLE: 7996 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7997 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7998 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7999 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 8000 } 8001 8002 SDValue Cmp; 8003 switch (CC) { 8004 default: break; // SETUO etc aren't handled by fsel. 8005 case ISD::SETNE: 8006 std::swap(TV, FV); 8007 LLVM_FALLTHROUGH; 8008 case ISD::SETEQ: 8009 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8010 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8011 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8012 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8013 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8014 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8015 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8016 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8017 case ISD::SETULT: 8018 case ISD::SETLT: 8019 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8020 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8021 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8022 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8023 case ISD::SETOGE: 8024 case ISD::SETGE: 8025 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8026 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8027 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8028 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8029 case ISD::SETUGT: 8030 case ISD::SETGT: 8031 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8032 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8033 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8034 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8035 case ISD::SETOLE: 8036 case ISD::SETLE: 8037 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8038 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8039 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8040 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8041 } 8042 return Op; 8043 } 8044 8045 static unsigned getPPCStrictOpcode(unsigned Opc) { 8046 switch (Opc) { 8047 default: 8048 llvm_unreachable("No strict version of this opcode!"); 8049 case PPCISD::FCTIDZ: 8050 return PPCISD::STRICT_FCTIDZ; 8051 case PPCISD::FCTIWZ: 8052 return PPCISD::STRICT_FCTIWZ; 8053 case PPCISD::FCTIDUZ: 8054 return PPCISD::STRICT_FCTIDUZ; 8055 case PPCISD::FCTIWUZ: 8056 return PPCISD::STRICT_FCTIWUZ; 8057 case PPCISD::FCFID: 8058 return PPCISD::STRICT_FCFID; 8059 case PPCISD::FCFIDU: 8060 return PPCISD::STRICT_FCFIDU; 8061 case PPCISD::FCFIDS: 8062 return PPCISD::STRICT_FCFIDS; 8063 case PPCISD::FCFIDUS: 8064 return PPCISD::STRICT_FCFIDUS; 8065 } 8066 } 8067 8068 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8069 const PPCSubtarget &Subtarget) { 8070 SDLoc dl(Op); 8071 bool IsStrict = Op->isStrictFPOpcode(); 8072 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8073 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8074 // For strict nodes, source is the second operand. 8075 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8076 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8077 assert(Src.getValueType().isFloatingPoint()); 8078 if (Src.getValueType() == MVT::f32) { 8079 if (IsStrict) { 8080 Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other}, 8081 {Chain, Src}); 8082 Chain = Src.getValue(1); 8083 } else 8084 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8085 } 8086 SDValue Conv; 8087 unsigned Opc = ISD::DELETED_NODE; 8088 switch (Op.getSimpleValueType().SimpleTy) { 8089 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8090 case MVT::i32: 8091 Opc = IsSigned ? PPCISD::FCTIWZ 8092 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8093 break; 8094 case MVT::i64: 8095 assert((IsSigned || Subtarget.hasFPCVT()) && 8096 "i64 FP_TO_UINT is supported only with FPCVT"); 8097 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8098 } 8099 if (IsStrict) { 8100 Opc = getPPCStrictOpcode(Opc); 8101 Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src}); 8102 } else { 8103 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8104 } 8105 return Conv; 8106 } 8107 8108 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8109 SelectionDAG &DAG, 8110 const SDLoc &dl) const { 8111 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8112 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8113 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8114 bool IsStrict = Op->isStrictFPOpcode(); 8115 8116 // Convert the FP value to an int value through memory. 8117 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8118 (IsSigned || Subtarget.hasFPCVT()); 8119 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8120 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8121 MachinePointerInfo MPI = 8122 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8123 8124 // Emit a store to the stack slot. 8125 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8126 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8127 if (i32Stack) { 8128 MachineFunction &MF = DAG.getMachineFunction(); 8129 Alignment = Align(4); 8130 MachineMemOperand *MMO = 8131 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8132 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8133 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8134 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8135 } else 8136 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8137 8138 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8139 // add in a bias on big endian. 8140 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8141 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8142 DAG.getConstant(4, dl, FIPtr.getValueType())); 8143 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8144 } 8145 8146 RLI.Chain = Chain; 8147 RLI.Ptr = FIPtr; 8148 RLI.MPI = MPI; 8149 RLI.Alignment = Alignment; 8150 } 8151 8152 /// Custom lowers floating point to integer conversions to use 8153 /// the direct move instructions available in ISA 2.07 to avoid the 8154 /// need for load/store combinations. 8155 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8156 SelectionDAG &DAG, 8157 const SDLoc &dl) const { 8158 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8159 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8160 if (Op->isStrictFPOpcode()) 8161 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8162 else 8163 return Mov; 8164 } 8165 8166 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8167 const SDLoc &dl) const { 8168 bool IsStrict = Op->isStrictFPOpcode(); 8169 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8170 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8171 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8172 // FP to INT conversions are legal for f128. 8173 if (Src.getValueType() == MVT::f128) 8174 return Op; 8175 8176 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8177 // PPC (the libcall is not available). 8178 if (Src.getValueType() == MVT::ppcf128 && !IsStrict) { 8179 if (Op.getValueType() == MVT::i32) { 8180 if (IsSigned) { 8181 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8182 DAG.getIntPtrConstant(0, dl)); 8183 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8184 DAG.getIntPtrConstant(1, dl)); 8185 8186 // Add the two halves of the long double in round-to-zero mode. 8187 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8188 8189 // Now use a smaller FP_TO_SINT. 8190 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8191 } else { 8192 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8193 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8194 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8195 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8196 // FIXME: generated code sucks. 8197 // TODO: Are there fast-math-flags to propagate to this FSUB? 8198 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp); 8199 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8200 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8201 DAG.getConstant(0x80000000, dl, MVT::i32)); 8202 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8203 return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE); 8204 } 8205 } 8206 8207 return SDValue(); 8208 } 8209 8210 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8211 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8212 8213 ReuseLoadInfo RLI; 8214 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8215 8216 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8217 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8218 } 8219 8220 // We're trying to insert a regular store, S, and then a load, L. If the 8221 // incoming value, O, is a load, we might just be able to have our load use the 8222 // address used by O. However, we don't know if anything else will store to 8223 // that address before we can load from it. To prevent this situation, we need 8224 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8225 // the same chain operand as O, we create a token factor from the chain results 8226 // of O and L, and we replace all uses of O's chain result with that token 8227 // factor (see spliceIntoChain below for this last part). 8228 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8229 ReuseLoadInfo &RLI, 8230 SelectionDAG &DAG, 8231 ISD::LoadExtType ET) const { 8232 // Conservatively skip reusing for constrained FP nodes. 8233 if (Op->isStrictFPOpcode()) 8234 return false; 8235 8236 SDLoc dl(Op); 8237 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8238 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8239 if (ET == ISD::NON_EXTLOAD && 8240 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8241 isOperationLegalOrCustom(Op.getOpcode(), 8242 Op.getOperand(0).getValueType())) { 8243 8244 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8245 return true; 8246 } 8247 8248 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8249 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8250 LD->isNonTemporal()) 8251 return false; 8252 if (LD->getMemoryVT() != MemVT) 8253 return false; 8254 8255 RLI.Ptr = LD->getBasePtr(); 8256 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8257 assert(LD->getAddressingMode() == ISD::PRE_INC && 8258 "Non-pre-inc AM on PPC?"); 8259 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8260 LD->getOffset()); 8261 } 8262 8263 RLI.Chain = LD->getChain(); 8264 RLI.MPI = LD->getPointerInfo(); 8265 RLI.IsDereferenceable = LD->isDereferenceable(); 8266 RLI.IsInvariant = LD->isInvariant(); 8267 RLI.Alignment = LD->getAlign(); 8268 RLI.AAInfo = LD->getAAInfo(); 8269 RLI.Ranges = LD->getRanges(); 8270 8271 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8272 return true; 8273 } 8274 8275 // Given the head of the old chain, ResChain, insert a token factor containing 8276 // it and NewResChain, and make users of ResChain now be users of that token 8277 // factor. 8278 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8279 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8280 SDValue NewResChain, 8281 SelectionDAG &DAG) const { 8282 if (!ResChain) 8283 return; 8284 8285 SDLoc dl(NewResChain); 8286 8287 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8288 NewResChain, DAG.getUNDEF(MVT::Other)); 8289 assert(TF.getNode() != NewResChain.getNode() && 8290 "A new TF really is required here"); 8291 8292 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8293 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8294 } 8295 8296 /// Analyze profitability of direct move 8297 /// prefer float load to int load plus direct move 8298 /// when there is no integer use of int load 8299 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8300 SDNode *Origin = Op.getOperand(0).getNode(); 8301 if (Origin->getOpcode() != ISD::LOAD) 8302 return true; 8303 8304 // If there is no LXSIBZX/LXSIHZX, like Power8, 8305 // prefer direct move if the memory size is 1 or 2 bytes. 8306 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8307 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8308 return true; 8309 8310 for (SDNode::use_iterator UI = Origin->use_begin(), 8311 UE = Origin->use_end(); 8312 UI != UE; ++UI) { 8313 8314 // Only look at the users of the loaded value. 8315 if (UI.getUse().get().getResNo() != 0) 8316 continue; 8317 8318 if (UI->getOpcode() != ISD::SINT_TO_FP && 8319 UI->getOpcode() != ISD::UINT_TO_FP && 8320 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8321 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8322 return true; 8323 } 8324 8325 return false; 8326 } 8327 8328 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8329 const PPCSubtarget &Subtarget, 8330 SDValue Chain = SDValue()) { 8331 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8332 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8333 SDLoc dl(Op); 8334 // If we have FCFIDS, then use it when converting to single-precision. 8335 // Otherwise, convert to double-precision and then round. 8336 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8337 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8338 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8339 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8340 if (Op->isStrictFPOpcode()) { 8341 if (!Chain) 8342 Chain = Op.getOperand(0); 8343 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, {ConvTy, MVT::Other}, 8344 {Chain, Src}); 8345 } else 8346 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8347 } 8348 8349 /// Custom lowers integer to floating point conversions to use 8350 /// the direct move instructions available in ISA 2.07 to avoid the 8351 /// need for load/store combinations. 8352 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8353 SelectionDAG &DAG, 8354 const SDLoc &dl) const { 8355 assert((Op.getValueType() == MVT::f32 || 8356 Op.getValueType() == MVT::f64) && 8357 "Invalid floating point type as target of conversion"); 8358 assert(Subtarget.hasFPCVT() && 8359 "Int to FP conversions with direct moves require FPCVT"); 8360 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8361 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8362 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8363 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8364 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8365 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8366 return convertIntToFP(Op, Mov, DAG, Subtarget); 8367 } 8368 8369 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8370 8371 EVT VecVT = Vec.getValueType(); 8372 assert(VecVT.isVector() && "Expected a vector type."); 8373 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8374 8375 EVT EltVT = VecVT.getVectorElementType(); 8376 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8377 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8378 8379 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8380 SmallVector<SDValue, 16> Ops(NumConcat); 8381 Ops[0] = Vec; 8382 SDValue UndefVec = DAG.getUNDEF(VecVT); 8383 for (unsigned i = 1; i < NumConcat; ++i) 8384 Ops[i] = UndefVec; 8385 8386 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8387 } 8388 8389 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8390 const SDLoc &dl) const { 8391 bool IsStrict = Op->isStrictFPOpcode(); 8392 unsigned Opc = Op.getOpcode(); 8393 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8394 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8395 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8396 "Unexpected conversion type"); 8397 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8398 "Supports conversions to v2f64/v4f32 only."); 8399 8400 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8401 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8402 8403 SDValue Wide = widenVec(DAG, Src, dl); 8404 EVT WideVT = Wide.getValueType(); 8405 unsigned WideNumElts = WideVT.getVectorNumElements(); 8406 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8407 8408 SmallVector<int, 16> ShuffV; 8409 for (unsigned i = 0; i < WideNumElts; ++i) 8410 ShuffV.push_back(i + WideNumElts); 8411 8412 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8413 int SaveElts = FourEltRes ? 4 : 2; 8414 if (Subtarget.isLittleEndian()) 8415 for (int i = 0; i < SaveElts; i++) 8416 ShuffV[i * Stride] = i; 8417 else 8418 for (int i = 1; i <= SaveElts; i++) 8419 ShuffV[i * Stride - 1] = i - 1; 8420 8421 SDValue ShuffleSrc2 = 8422 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8423 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8424 8425 SDValue Extend; 8426 if (SignedConv) { 8427 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8428 EVT ExtVT = Src.getValueType(); 8429 if (Subtarget.hasP9Altivec()) 8430 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8431 IntermediateVT.getVectorNumElements()); 8432 8433 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8434 DAG.getValueType(ExtVT)); 8435 } else 8436 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8437 8438 if (IsStrict) 8439 return DAG.getNode(Opc, dl, {Op.getValueType(), MVT::Other}, 8440 {Op.getOperand(0), Extend}); 8441 8442 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8443 } 8444 8445 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8446 SelectionDAG &DAG) const { 8447 SDLoc dl(Op); 8448 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8449 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8450 bool IsStrict = Op->isStrictFPOpcode(); 8451 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8452 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8453 8454 EVT InVT = Src.getValueType(); 8455 EVT OutVT = Op.getValueType(); 8456 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8457 isOperationCustom(Op.getOpcode(), InVT)) 8458 return LowerINT_TO_FPVector(Op, DAG, dl); 8459 8460 // Conversions to f128 are legal. 8461 if (Op.getValueType() == MVT::f128) 8462 return Op; 8463 8464 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8465 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8466 return SDValue(); 8467 8468 if (Src.getValueType() == MVT::i1) 8469 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8470 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8471 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8472 8473 // If we have direct moves, we can do all the conversion, skip the store/load 8474 // however, without FPCVT we can't do most conversions. 8475 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8476 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8477 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8478 8479 assert((IsSigned || Subtarget.hasFPCVT()) && 8480 "UINT_TO_FP is supported only with FPCVT"); 8481 8482 if (Src.getValueType() == MVT::i64) { 8483 SDValue SINT = Src; 8484 // When converting to single-precision, we actually need to convert 8485 // to double-precision first and then round to single-precision. 8486 // To avoid double-rounding effects during that operation, we have 8487 // to prepare the input operand. Bits that might be truncated when 8488 // converting to double-precision are replaced by a bit that won't 8489 // be lost at this stage, but is below the single-precision rounding 8490 // position. 8491 // 8492 // However, if -enable-unsafe-fp-math is in effect, accept double 8493 // rounding to avoid the extra overhead. 8494 if (Op.getValueType() == MVT::f32 && 8495 !Subtarget.hasFPCVT() && 8496 !DAG.getTarget().Options.UnsafeFPMath) { 8497 8498 // Twiddle input to make sure the low 11 bits are zero. (If this 8499 // is the case, we are guaranteed the value will fit into the 53 bit 8500 // mantissa of an IEEE double-precision value without rounding.) 8501 // If any of those low 11 bits were not zero originally, make sure 8502 // bit 12 (value 2048) is set instead, so that the final rounding 8503 // to single-precision gets the correct result. 8504 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8505 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8506 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8507 Round, DAG.getConstant(2047, dl, MVT::i64)); 8508 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8509 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8510 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8511 8512 // However, we cannot use that value unconditionally: if the magnitude 8513 // of the input value is small, the bit-twiddling we did above might 8514 // end up visibly changing the output. Fortunately, in that case, we 8515 // don't need to twiddle bits since the original input will convert 8516 // exactly to double-precision floating-point already. Therefore, 8517 // construct a conditional to use the original value if the top 11 8518 // bits are all sign-bit copies, and use the rounded value computed 8519 // above otherwise. 8520 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8521 SINT, DAG.getConstant(53, dl, MVT::i32)); 8522 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8523 Cond, DAG.getConstant(1, dl, MVT::i64)); 8524 Cond = DAG.getSetCC( 8525 dl, 8526 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8527 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8528 8529 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8530 } 8531 8532 ReuseLoadInfo RLI; 8533 SDValue Bits; 8534 8535 MachineFunction &MF = DAG.getMachineFunction(); 8536 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8537 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8538 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8539 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8540 } else if (Subtarget.hasLFIWAX() && 8541 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8542 MachineMemOperand *MMO = 8543 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8544 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8545 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8546 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8547 DAG.getVTList(MVT::f64, MVT::Other), 8548 Ops, MVT::i32, MMO); 8549 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8550 } else if (Subtarget.hasFPCVT() && 8551 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8552 MachineMemOperand *MMO = 8553 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8554 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8555 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8556 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8557 DAG.getVTList(MVT::f64, MVT::Other), 8558 Ops, MVT::i32, MMO); 8559 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8560 } else if (((Subtarget.hasLFIWAX() && 8561 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8562 (Subtarget.hasFPCVT() && 8563 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8564 SINT.getOperand(0).getValueType() == MVT::i32) { 8565 MachineFrameInfo &MFI = MF.getFrameInfo(); 8566 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8567 8568 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8569 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8570 8571 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8572 MachinePointerInfo::getFixedStack( 8573 DAG.getMachineFunction(), FrameIdx)); 8574 Chain = Store; 8575 8576 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8577 "Expected an i32 store"); 8578 8579 RLI.Ptr = FIdx; 8580 RLI.Chain = Chain; 8581 RLI.MPI = 8582 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8583 RLI.Alignment = Align(4); 8584 8585 MachineMemOperand *MMO = 8586 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8587 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8588 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8589 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8590 PPCISD::LFIWZX : PPCISD::LFIWAX, 8591 dl, DAG.getVTList(MVT::f64, MVT::Other), 8592 Ops, MVT::i32, MMO); 8593 Chain = Bits.getValue(1); 8594 } else 8595 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8596 8597 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8598 if (IsStrict) 8599 Chain = FP.getValue(1); 8600 8601 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8602 if (IsStrict) 8603 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8604 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8605 else 8606 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8607 DAG.getIntPtrConstant(0, dl)); 8608 } 8609 return FP; 8610 } 8611 8612 assert(Src.getValueType() == MVT::i32 && 8613 "Unhandled INT_TO_FP type in custom expander!"); 8614 // Since we only generate this in 64-bit mode, we can take advantage of 8615 // 64-bit registers. In particular, sign extend the input value into the 8616 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8617 // then lfd it and fcfid it. 8618 MachineFunction &MF = DAG.getMachineFunction(); 8619 MachineFrameInfo &MFI = MF.getFrameInfo(); 8620 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8621 8622 SDValue Ld; 8623 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8624 ReuseLoadInfo RLI; 8625 bool ReusingLoad; 8626 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8627 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8628 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8629 8630 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8631 MachinePointerInfo::getFixedStack( 8632 DAG.getMachineFunction(), FrameIdx)); 8633 Chain = Store; 8634 8635 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8636 "Expected an i32 store"); 8637 8638 RLI.Ptr = FIdx; 8639 RLI.Chain = Chain; 8640 RLI.MPI = 8641 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8642 RLI.Alignment = Align(4); 8643 } 8644 8645 MachineMemOperand *MMO = 8646 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8647 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8648 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8649 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8650 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8651 MVT::i32, MMO); 8652 Chain = Ld.getValue(1); 8653 if (ReusingLoad) 8654 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8655 } else { 8656 assert(Subtarget.isPPC64() && 8657 "i32->FP without LFIWAX supported only on PPC64"); 8658 8659 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8660 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8661 8662 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8663 8664 // STD the extended value into the stack slot. 8665 SDValue Store = DAG.getStore( 8666 Chain, dl, Ext64, FIdx, 8667 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8668 Chain = Store; 8669 8670 // Load the value as a double. 8671 Ld = DAG.getLoad( 8672 MVT::f64, dl, Chain, FIdx, 8673 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8674 Chain = Ld.getValue(1); 8675 } 8676 8677 // FCFID it and return it. 8678 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8679 if (IsStrict) 8680 Chain = FP.getValue(1); 8681 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8682 if (IsStrict) 8683 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other}, 8684 {Chain, FP, DAG.getIntPtrConstant(0, dl)}); 8685 else 8686 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8687 DAG.getIntPtrConstant(0, dl)); 8688 } 8689 return FP; 8690 } 8691 8692 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8693 SelectionDAG &DAG) const { 8694 SDLoc dl(Op); 8695 /* 8696 The rounding mode is in bits 30:31 of FPSR, and has the following 8697 settings: 8698 00 Round to nearest 8699 01 Round to 0 8700 10 Round to +inf 8701 11 Round to -inf 8702 8703 FLT_ROUNDS, on the other hand, expects the following: 8704 -1 Undefined 8705 0 Round to 0 8706 1 Round to nearest 8707 2 Round to +inf 8708 3 Round to -inf 8709 8710 To perform the conversion, we do: 8711 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8712 */ 8713 8714 MachineFunction &MF = DAG.getMachineFunction(); 8715 EVT VT = Op.getValueType(); 8716 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8717 8718 // Save FP Control Word to register 8719 SDValue Chain = Op.getOperand(0); 8720 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8721 Chain = MFFS.getValue(1); 8722 8723 // Save FP register to stack slot 8724 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8725 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8726 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8727 8728 // Load FP Control Word from low 32 bits of stack slot. 8729 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8730 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8731 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8732 Chain = CWD.getValue(1); 8733 8734 // Transform as necessary 8735 SDValue CWD1 = 8736 DAG.getNode(ISD::AND, dl, MVT::i32, 8737 CWD, DAG.getConstant(3, dl, MVT::i32)); 8738 SDValue CWD2 = 8739 DAG.getNode(ISD::SRL, dl, MVT::i32, 8740 DAG.getNode(ISD::AND, dl, MVT::i32, 8741 DAG.getNode(ISD::XOR, dl, MVT::i32, 8742 CWD, DAG.getConstant(3, dl, MVT::i32)), 8743 DAG.getConstant(3, dl, MVT::i32)), 8744 DAG.getConstant(1, dl, MVT::i32)); 8745 8746 SDValue RetVal = 8747 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8748 8749 RetVal = 8750 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8751 dl, VT, RetVal); 8752 8753 return DAG.getMergeValues({RetVal, Chain}, dl); 8754 } 8755 8756 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8757 EVT VT = Op.getValueType(); 8758 unsigned BitWidth = VT.getSizeInBits(); 8759 SDLoc dl(Op); 8760 assert(Op.getNumOperands() == 3 && 8761 VT == Op.getOperand(1).getValueType() && 8762 "Unexpected SHL!"); 8763 8764 // Expand into a bunch of logical ops. Note that these ops 8765 // depend on the PPC behavior for oversized shift amounts. 8766 SDValue Lo = Op.getOperand(0); 8767 SDValue Hi = Op.getOperand(1); 8768 SDValue Amt = Op.getOperand(2); 8769 EVT AmtVT = Amt.getValueType(); 8770 8771 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8772 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8773 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8774 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8775 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8776 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8777 DAG.getConstant(-BitWidth, dl, AmtVT)); 8778 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8779 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8780 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8781 SDValue OutOps[] = { OutLo, OutHi }; 8782 return DAG.getMergeValues(OutOps, dl); 8783 } 8784 8785 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8786 EVT VT = Op.getValueType(); 8787 SDLoc dl(Op); 8788 unsigned BitWidth = VT.getSizeInBits(); 8789 assert(Op.getNumOperands() == 3 && 8790 VT == Op.getOperand(1).getValueType() && 8791 "Unexpected SRL!"); 8792 8793 // Expand into a bunch of logical ops. Note that these ops 8794 // depend on the PPC behavior for oversized shift amounts. 8795 SDValue Lo = Op.getOperand(0); 8796 SDValue Hi = Op.getOperand(1); 8797 SDValue Amt = Op.getOperand(2); 8798 EVT AmtVT = Amt.getValueType(); 8799 8800 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8801 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8802 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8803 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8804 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8805 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8806 DAG.getConstant(-BitWidth, dl, AmtVT)); 8807 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8808 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8809 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8810 SDValue OutOps[] = { OutLo, OutHi }; 8811 return DAG.getMergeValues(OutOps, dl); 8812 } 8813 8814 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8815 SDLoc dl(Op); 8816 EVT VT = Op.getValueType(); 8817 unsigned BitWidth = VT.getSizeInBits(); 8818 assert(Op.getNumOperands() == 3 && 8819 VT == Op.getOperand(1).getValueType() && 8820 "Unexpected SRA!"); 8821 8822 // Expand into a bunch of logical ops, followed by a select_cc. 8823 SDValue Lo = Op.getOperand(0); 8824 SDValue Hi = Op.getOperand(1); 8825 SDValue Amt = Op.getOperand(2); 8826 EVT AmtVT = Amt.getValueType(); 8827 8828 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8829 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8830 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8831 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8832 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8833 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8834 DAG.getConstant(-BitWidth, dl, AmtVT)); 8835 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8836 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8837 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8838 Tmp4, Tmp6, ISD::SETLE); 8839 SDValue OutOps[] = { OutLo, OutHi }; 8840 return DAG.getMergeValues(OutOps, dl); 8841 } 8842 8843 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8844 SelectionDAG &DAG) const { 8845 SDLoc dl(Op); 8846 EVT VT = Op.getValueType(); 8847 unsigned BitWidth = VT.getSizeInBits(); 8848 8849 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8850 SDValue X = Op.getOperand(0); 8851 SDValue Y = Op.getOperand(1); 8852 SDValue Z = Op.getOperand(2); 8853 EVT AmtVT = Z.getValueType(); 8854 8855 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8856 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8857 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8858 // on PowerPC shift by BW being well defined. 8859 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8860 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8861 SDValue SubZ = 8862 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8863 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8864 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8865 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8866 } 8867 8868 //===----------------------------------------------------------------------===// 8869 // Vector related lowering. 8870 // 8871 8872 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8873 /// element size of SplatSize. Cast the result to VT. 8874 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8875 SelectionDAG &DAG, const SDLoc &dl) { 8876 static const MVT VTys[] = { // canonical VT to use for each size. 8877 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8878 }; 8879 8880 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8881 8882 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8883 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8884 SplatSize = 1; 8885 Val = 0xFF; 8886 } 8887 8888 EVT CanonicalVT = VTys[SplatSize-1]; 8889 8890 // Build a canonical splat for this value. 8891 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8892 } 8893 8894 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8895 /// specified intrinsic ID. 8896 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8897 const SDLoc &dl, EVT DestVT = MVT::Other) { 8898 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8899 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8900 DAG.getConstant(IID, dl, MVT::i32), Op); 8901 } 8902 8903 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8904 /// specified intrinsic ID. 8905 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8906 SelectionDAG &DAG, const SDLoc &dl, 8907 EVT DestVT = MVT::Other) { 8908 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8909 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8910 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8911 } 8912 8913 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8914 /// specified intrinsic ID. 8915 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8916 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8917 EVT DestVT = MVT::Other) { 8918 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8919 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8920 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8921 } 8922 8923 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8924 /// amount. The result has the specified value type. 8925 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8926 SelectionDAG &DAG, const SDLoc &dl) { 8927 // Force LHS/RHS to be the right type. 8928 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8929 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8930 8931 int Ops[16]; 8932 for (unsigned i = 0; i != 16; ++i) 8933 Ops[i] = i + Amt; 8934 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8935 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8936 } 8937 8938 /// Do we have an efficient pattern in a .td file for this node? 8939 /// 8940 /// \param V - pointer to the BuildVectorSDNode being matched 8941 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8942 /// 8943 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8944 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8945 /// the opposite is true (expansion is beneficial) are: 8946 /// - The node builds a vector out of integers that are not 32 or 64-bits 8947 /// - The node builds a vector out of constants 8948 /// - The node is a "load-and-splat" 8949 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8950 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8951 bool HasDirectMove, 8952 bool HasP8Vector) { 8953 EVT VecVT = V->getValueType(0); 8954 bool RightType = VecVT == MVT::v2f64 || 8955 (HasP8Vector && VecVT == MVT::v4f32) || 8956 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8957 if (!RightType) 8958 return false; 8959 8960 bool IsSplat = true; 8961 bool IsLoad = false; 8962 SDValue Op0 = V->getOperand(0); 8963 8964 // This function is called in a block that confirms the node is not a constant 8965 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8966 // different constants. 8967 if (V->isConstant()) 8968 return false; 8969 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8970 if (V->getOperand(i).isUndef()) 8971 return false; 8972 // We want to expand nodes that represent load-and-splat even if the 8973 // loaded value is a floating point truncation or conversion to int. 8974 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8975 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8976 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8977 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8978 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8979 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8980 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8981 IsLoad = true; 8982 // If the operands are different or the input is not a load and has more 8983 // uses than just this BV node, then it isn't a splat. 8984 if (V->getOperand(i) != Op0 || 8985 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8986 IsSplat = false; 8987 } 8988 return !(IsSplat && IsLoad); 8989 } 8990 8991 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8992 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8993 8994 SDLoc dl(Op); 8995 SDValue Op0 = Op->getOperand(0); 8996 8997 if ((Op.getValueType() != MVT::f128) || 8998 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8999 (Op0.getOperand(0).getValueType() != MVT::i64) || 9000 (Op0.getOperand(1).getValueType() != MVT::i64)) 9001 return SDValue(); 9002 9003 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9004 Op0.getOperand(1)); 9005 } 9006 9007 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9008 const SDValue *InputLoad = &Op; 9009 if (InputLoad->getOpcode() == ISD::BITCAST) 9010 InputLoad = &InputLoad->getOperand(0); 9011 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9012 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9013 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9014 InputLoad = &InputLoad->getOperand(0); 9015 } 9016 if (InputLoad->getOpcode() != ISD::LOAD) 9017 return nullptr; 9018 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9019 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9020 } 9021 9022 // Convert the argument APFloat to a single precision APFloat if there is no 9023 // loss in information during the conversion to single precision APFloat and the 9024 // resulting number is not a denormal number. Return true if successful. 9025 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9026 APFloat APFloatToConvert = ArgAPFloat; 9027 bool LosesInfo = true; 9028 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9029 &LosesInfo); 9030 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9031 if (Success) 9032 ArgAPFloat = APFloatToConvert; 9033 return Success; 9034 } 9035 9036 // Bitcast the argument APInt to a double and convert it to a single precision 9037 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9038 // argument if there is no loss in information during the conversion from 9039 // double to single precision APFloat and the resulting number is not a denormal 9040 // number. Return true if successful. 9041 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9042 double DpValue = ArgAPInt.bitsToDouble(); 9043 APFloat APFloatDp(DpValue); 9044 bool Success = convertToNonDenormSingle(APFloatDp); 9045 if (Success) 9046 ArgAPInt = APFloatDp.bitcastToAPInt(); 9047 return Success; 9048 } 9049 9050 // If this is a case we can't handle, return null and let the default 9051 // expansion code take care of it. If we CAN select this case, and if it 9052 // selects to a single instruction, return Op. Otherwise, if we can codegen 9053 // this case more efficiently than a constant pool load, lower it to the 9054 // sequence of ops that should be used. 9055 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9056 SelectionDAG &DAG) const { 9057 SDLoc dl(Op); 9058 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9059 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9060 9061 // Check if this is a splat of a constant value. 9062 APInt APSplatBits, APSplatUndef; 9063 unsigned SplatBitSize; 9064 bool HasAnyUndefs; 9065 bool BVNIsConstantSplat = 9066 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9067 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9068 9069 // If it is a splat of a double, check if we can shrink it to a 32 bit 9070 // non-denormal float which when converted back to double gives us the same 9071 // double. This is to exploit the XXSPLTIDP instruction. 9072 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 9073 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 9074 convertToNonDenormSingle(APSplatBits)) { 9075 SDValue SplatNode = DAG.getNode( 9076 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9077 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9078 return DAG.getBitcast(Op.getValueType(), SplatNode); 9079 } 9080 9081 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9082 9083 bool IsPermutedLoad = false; 9084 const SDValue *InputLoad = 9085 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 9086 // Handle load-and-splat patterns as we have instructions that will do this 9087 // in one go. 9088 if (InputLoad && DAG.isSplatValue(Op, true)) { 9089 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9090 9091 // We have handling for 4 and 8 byte elements. 9092 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 9093 9094 // Checking for a single use of this load, we have to check for vector 9095 // width (128 bits) / ElementSize uses (since each operand of the 9096 // BUILD_VECTOR is a separate use of the value. 9097 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 9098 ((Subtarget.hasVSX() && ElementSize == 64) || 9099 (Subtarget.hasP9Vector() && ElementSize == 32))) { 9100 SDValue Ops[] = { 9101 LD->getChain(), // Chain 9102 LD->getBasePtr(), // Ptr 9103 DAG.getValueType(Op.getValueType()) // VT 9104 }; 9105 return 9106 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 9107 DAG.getVTList(Op.getValueType(), MVT::Other), 9108 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9109 } 9110 } 9111 9112 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 9113 // lowered to VSX instructions under certain conditions. 9114 // Without VSX, there is no pattern more efficient than expanding the node. 9115 if (Subtarget.hasVSX() && 9116 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9117 Subtarget.hasP8Vector())) 9118 return Op; 9119 return SDValue(); 9120 } 9121 9122 uint64_t SplatBits = APSplatBits.getZExtValue(); 9123 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9124 unsigned SplatSize = SplatBitSize / 8; 9125 9126 // First, handle single instruction cases. 9127 9128 // All zeros? 9129 if (SplatBits == 0) { 9130 // Canonicalize all zero vectors to be v4i32. 9131 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9132 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9133 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9134 } 9135 return Op; 9136 } 9137 9138 // We have XXSPLTIW for constant splats four bytes wide. 9139 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9140 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9141 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9142 // turned into a 4-byte splat of 0xABABABAB. 9143 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9144 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9145 Op.getValueType(), DAG, dl); 9146 9147 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9148 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9149 dl); 9150 9151 // We have XXSPLTIB for constant splats one byte wide. 9152 if (Subtarget.hasP9Vector() && SplatSize == 1) 9153 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9154 dl); 9155 9156 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9157 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9158 (32-SplatBitSize)); 9159 if (SextVal >= -16 && SextVal <= 15) 9160 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9161 dl); 9162 9163 // Two instruction sequences. 9164 9165 // If this value is in the range [-32,30] and is even, use: 9166 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9167 // If this value is in the range [17,31] and is odd, use: 9168 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9169 // If this value is in the range [-31,-17] and is odd, use: 9170 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9171 // Note the last two are three-instruction sequences. 9172 if (SextVal >= -32 && SextVal <= 31) { 9173 // To avoid having these optimizations undone by constant folding, 9174 // we convert to a pseudo that will be expanded later into one of 9175 // the above forms. 9176 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9177 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9178 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9179 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9180 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9181 if (VT == Op.getValueType()) 9182 return RetVal; 9183 else 9184 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9185 } 9186 9187 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9188 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9189 // for fneg/fabs. 9190 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9191 // Make -1 and vspltisw -1: 9192 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9193 9194 // Make the VSLW intrinsic, computing 0x8000_0000. 9195 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9196 OnesV, DAG, dl); 9197 9198 // xor by OnesV to invert it. 9199 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9200 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9201 } 9202 9203 // Check to see if this is a wide variety of vsplti*, binop self cases. 9204 static const signed char SplatCsts[] = { 9205 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9206 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9207 }; 9208 9209 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9210 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9211 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9212 int i = SplatCsts[idx]; 9213 9214 // Figure out what shift amount will be used by altivec if shifted by i in 9215 // this splat size. 9216 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9217 9218 // vsplti + shl self. 9219 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9220 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9221 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9222 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9223 Intrinsic::ppc_altivec_vslw 9224 }; 9225 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9226 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9227 } 9228 9229 // vsplti + srl self. 9230 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9231 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9232 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9233 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9234 Intrinsic::ppc_altivec_vsrw 9235 }; 9236 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9237 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9238 } 9239 9240 // vsplti + sra self. 9241 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9242 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9243 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9244 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9245 Intrinsic::ppc_altivec_vsraw 9246 }; 9247 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9248 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9249 } 9250 9251 // vsplti + rol self. 9252 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9253 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9254 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9255 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9256 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9257 Intrinsic::ppc_altivec_vrlw 9258 }; 9259 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9260 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9261 } 9262 9263 // t = vsplti c, result = vsldoi t, t, 1 9264 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9265 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9266 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9267 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9268 } 9269 // t = vsplti c, result = vsldoi t, t, 2 9270 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9271 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9272 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9273 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9274 } 9275 // t = vsplti c, result = vsldoi t, t, 3 9276 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9277 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9278 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9279 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9280 } 9281 } 9282 9283 return SDValue(); 9284 } 9285 9286 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9287 /// the specified operations to build the shuffle. 9288 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9289 SDValue RHS, SelectionDAG &DAG, 9290 const SDLoc &dl) { 9291 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9292 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9293 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9294 9295 enum { 9296 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9297 OP_VMRGHW, 9298 OP_VMRGLW, 9299 OP_VSPLTISW0, 9300 OP_VSPLTISW1, 9301 OP_VSPLTISW2, 9302 OP_VSPLTISW3, 9303 OP_VSLDOI4, 9304 OP_VSLDOI8, 9305 OP_VSLDOI12 9306 }; 9307 9308 if (OpNum == OP_COPY) { 9309 if (LHSID == (1*9+2)*9+3) return LHS; 9310 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9311 return RHS; 9312 } 9313 9314 SDValue OpLHS, OpRHS; 9315 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9316 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9317 9318 int ShufIdxs[16]; 9319 switch (OpNum) { 9320 default: llvm_unreachable("Unknown i32 permute!"); 9321 case OP_VMRGHW: 9322 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9323 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9324 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9325 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9326 break; 9327 case OP_VMRGLW: 9328 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9329 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9330 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9331 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9332 break; 9333 case OP_VSPLTISW0: 9334 for (unsigned i = 0; i != 16; ++i) 9335 ShufIdxs[i] = (i&3)+0; 9336 break; 9337 case OP_VSPLTISW1: 9338 for (unsigned i = 0; i != 16; ++i) 9339 ShufIdxs[i] = (i&3)+4; 9340 break; 9341 case OP_VSPLTISW2: 9342 for (unsigned i = 0; i != 16; ++i) 9343 ShufIdxs[i] = (i&3)+8; 9344 break; 9345 case OP_VSPLTISW3: 9346 for (unsigned i = 0; i != 16; ++i) 9347 ShufIdxs[i] = (i&3)+12; 9348 break; 9349 case OP_VSLDOI4: 9350 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9351 case OP_VSLDOI8: 9352 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9353 case OP_VSLDOI12: 9354 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9355 } 9356 EVT VT = OpLHS.getValueType(); 9357 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9358 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9359 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9360 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9361 } 9362 9363 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9364 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9365 /// SDValue. 9366 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9367 SelectionDAG &DAG) const { 9368 const unsigned BytesInVector = 16; 9369 bool IsLE = Subtarget.isLittleEndian(); 9370 SDLoc dl(N); 9371 SDValue V1 = N->getOperand(0); 9372 SDValue V2 = N->getOperand(1); 9373 unsigned ShiftElts = 0, InsertAtByte = 0; 9374 bool Swap = false; 9375 9376 // Shifts required to get the byte we want at element 7. 9377 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9378 0, 15, 14, 13, 12, 11, 10, 9}; 9379 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9380 1, 2, 3, 4, 5, 6, 7, 8}; 9381 9382 ArrayRef<int> Mask = N->getMask(); 9383 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9384 9385 // For each mask element, find out if we're just inserting something 9386 // from V2 into V1 or vice versa. 9387 // Possible permutations inserting an element from V2 into V1: 9388 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9389 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9390 // ... 9391 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9392 // Inserting from V1 into V2 will be similar, except mask range will be 9393 // [16,31]. 9394 9395 bool FoundCandidate = false; 9396 // If both vector operands for the shuffle are the same vector, the mask 9397 // will contain only elements from the first one and the second one will be 9398 // undef. 9399 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9400 // Go through the mask of half-words to find an element that's being moved 9401 // from one vector to the other. 9402 for (unsigned i = 0; i < BytesInVector; ++i) { 9403 unsigned CurrentElement = Mask[i]; 9404 // If 2nd operand is undefined, we should only look for element 7 in the 9405 // Mask. 9406 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9407 continue; 9408 9409 bool OtherElementsInOrder = true; 9410 // Examine the other elements in the Mask to see if they're in original 9411 // order. 9412 for (unsigned j = 0; j < BytesInVector; ++j) { 9413 if (j == i) 9414 continue; 9415 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9416 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9417 // in which we always assume we're always picking from the 1st operand. 9418 int MaskOffset = 9419 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9420 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9421 OtherElementsInOrder = false; 9422 break; 9423 } 9424 } 9425 // If other elements are in original order, we record the number of shifts 9426 // we need to get the element we want into element 7. Also record which byte 9427 // in the vector we should insert into. 9428 if (OtherElementsInOrder) { 9429 // If 2nd operand is undefined, we assume no shifts and no swapping. 9430 if (V2.isUndef()) { 9431 ShiftElts = 0; 9432 Swap = false; 9433 } else { 9434 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9435 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9436 : BigEndianShifts[CurrentElement & 0xF]; 9437 Swap = CurrentElement < BytesInVector; 9438 } 9439 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9440 FoundCandidate = true; 9441 break; 9442 } 9443 } 9444 9445 if (!FoundCandidate) 9446 return SDValue(); 9447 9448 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9449 // optionally with VECSHL if shift is required. 9450 if (Swap) 9451 std::swap(V1, V2); 9452 if (V2.isUndef()) 9453 V2 = V1; 9454 if (ShiftElts) { 9455 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9456 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9457 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9458 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9459 } 9460 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9461 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9462 } 9463 9464 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9465 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9466 /// SDValue. 9467 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9468 SelectionDAG &DAG) const { 9469 const unsigned NumHalfWords = 8; 9470 const unsigned BytesInVector = NumHalfWords * 2; 9471 // Check that the shuffle is on half-words. 9472 if (!isNByteElemShuffleMask(N, 2, 1)) 9473 return SDValue(); 9474 9475 bool IsLE = Subtarget.isLittleEndian(); 9476 SDLoc dl(N); 9477 SDValue V1 = N->getOperand(0); 9478 SDValue V2 = N->getOperand(1); 9479 unsigned ShiftElts = 0, InsertAtByte = 0; 9480 bool Swap = false; 9481 9482 // Shifts required to get the half-word we want at element 3. 9483 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9484 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9485 9486 uint32_t Mask = 0; 9487 uint32_t OriginalOrderLow = 0x1234567; 9488 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9489 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9490 // 32-bit space, only need 4-bit nibbles per element. 9491 for (unsigned i = 0; i < NumHalfWords; ++i) { 9492 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9493 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9494 } 9495 9496 // For each mask element, find out if we're just inserting something 9497 // from V2 into V1 or vice versa. Possible permutations inserting an element 9498 // from V2 into V1: 9499 // X, 1, 2, 3, 4, 5, 6, 7 9500 // 0, X, 2, 3, 4, 5, 6, 7 9501 // 0, 1, X, 3, 4, 5, 6, 7 9502 // 0, 1, 2, X, 4, 5, 6, 7 9503 // 0, 1, 2, 3, X, 5, 6, 7 9504 // 0, 1, 2, 3, 4, X, 6, 7 9505 // 0, 1, 2, 3, 4, 5, X, 7 9506 // 0, 1, 2, 3, 4, 5, 6, X 9507 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9508 9509 bool FoundCandidate = false; 9510 // Go through the mask of half-words to find an element that's being moved 9511 // from one vector to the other. 9512 for (unsigned i = 0; i < NumHalfWords; ++i) { 9513 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9514 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9515 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9516 uint32_t TargetOrder = 0x0; 9517 9518 // If both vector operands for the shuffle are the same vector, the mask 9519 // will contain only elements from the first one and the second one will be 9520 // undef. 9521 if (V2.isUndef()) { 9522 ShiftElts = 0; 9523 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9524 TargetOrder = OriginalOrderLow; 9525 Swap = false; 9526 // Skip if not the correct element or mask of other elements don't equal 9527 // to our expected order. 9528 if (MaskOneElt == VINSERTHSrcElem && 9529 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9530 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9531 FoundCandidate = true; 9532 break; 9533 } 9534 } else { // If both operands are defined. 9535 // Target order is [8,15] if the current mask is between [0,7]. 9536 TargetOrder = 9537 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9538 // Skip if mask of other elements don't equal our expected order. 9539 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9540 // We only need the last 3 bits for the number of shifts. 9541 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9542 : BigEndianShifts[MaskOneElt & 0x7]; 9543 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9544 Swap = MaskOneElt < NumHalfWords; 9545 FoundCandidate = true; 9546 break; 9547 } 9548 } 9549 } 9550 9551 if (!FoundCandidate) 9552 return SDValue(); 9553 9554 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9555 // optionally with VECSHL if shift is required. 9556 if (Swap) 9557 std::swap(V1, V2); 9558 if (V2.isUndef()) 9559 V2 = V1; 9560 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9561 if (ShiftElts) { 9562 // Double ShiftElts because we're left shifting on v16i8 type. 9563 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9564 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9565 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9566 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9567 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9568 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9569 } 9570 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9571 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9572 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9573 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9574 } 9575 9576 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9577 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9578 /// return the default SDValue. 9579 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9580 SelectionDAG &DAG) const { 9581 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9582 // to v16i8. Peek through the bitcasts to get the actual operands. 9583 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9584 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9585 9586 auto ShuffleMask = SVN->getMask(); 9587 SDValue VecShuffle(SVN, 0); 9588 SDLoc DL(SVN); 9589 9590 // Check that we have a four byte shuffle. 9591 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9592 return SDValue(); 9593 9594 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9595 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9596 std::swap(LHS, RHS); 9597 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9598 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9599 } 9600 9601 // Ensure that the RHS is a vector of constants. 9602 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9603 if (!BVN) 9604 return SDValue(); 9605 9606 // Check if RHS is a splat of 4-bytes (or smaller). 9607 APInt APSplatValue, APSplatUndef; 9608 unsigned SplatBitSize; 9609 bool HasAnyUndefs; 9610 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9611 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9612 SplatBitSize > 32) 9613 return SDValue(); 9614 9615 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9616 // The instruction splats a constant C into two words of the source vector 9617 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9618 // Thus we check that the shuffle mask is the equivalent of 9619 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9620 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9621 // within each word are consecutive, so we only need to check the first byte. 9622 SDValue Index; 9623 bool IsLE = Subtarget.isLittleEndian(); 9624 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9625 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9626 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9627 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9628 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9629 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9630 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9631 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9632 else 9633 return SDValue(); 9634 9635 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9636 // for XXSPLTI32DX. 9637 unsigned SplatVal = APSplatValue.getZExtValue(); 9638 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9639 SplatVal |= (SplatVal << SplatBitSize); 9640 9641 SDValue SplatNode = DAG.getNode( 9642 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9643 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9644 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9645 } 9646 9647 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9648 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9649 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9650 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9651 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9652 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9653 assert(Op.getValueType() == MVT::v1i128 && 9654 "Only set v1i128 as custom, other type shouldn't reach here!"); 9655 SDLoc dl(Op); 9656 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9657 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9658 unsigned SHLAmt = N1.getConstantOperandVal(0); 9659 if (SHLAmt % 8 == 0) { 9660 SmallVector<int, 16> Mask(16, 0); 9661 std::iota(Mask.begin(), Mask.end(), 0); 9662 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9663 if (SDValue Shuffle = 9664 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9665 DAG.getUNDEF(MVT::v16i8), Mask)) 9666 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9667 } 9668 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9669 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9670 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9671 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9672 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9673 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9674 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9675 } 9676 9677 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9678 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9679 /// return the code it can be lowered into. Worst case, it can always be 9680 /// lowered into a vperm. 9681 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9682 SelectionDAG &DAG) const { 9683 SDLoc dl(Op); 9684 SDValue V1 = Op.getOperand(0); 9685 SDValue V2 = Op.getOperand(1); 9686 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9687 9688 // Any nodes that were combined in the target-independent combiner prior 9689 // to vector legalization will not be sent to the target combine. Try to 9690 // combine it here. 9691 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9692 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9693 return NewShuffle; 9694 Op = NewShuffle; 9695 SVOp = cast<ShuffleVectorSDNode>(Op); 9696 V1 = Op.getOperand(0); 9697 V2 = Op.getOperand(1); 9698 } 9699 EVT VT = Op.getValueType(); 9700 bool isLittleEndian = Subtarget.isLittleEndian(); 9701 9702 unsigned ShiftElts, InsertAtByte; 9703 bool Swap = false; 9704 9705 // If this is a load-and-splat, we can do that with a single instruction 9706 // in some cases. However if the load has multiple uses, we don't want to 9707 // combine it because that will just produce multiple loads. 9708 bool IsPermutedLoad = false; 9709 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9710 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9711 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9712 InputLoad->hasOneUse()) { 9713 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9714 int SplatIdx = 9715 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9716 9717 // The splat index for permuted loads will be in the left half of the vector 9718 // which is strictly wider than the loaded value by 8 bytes. So we need to 9719 // adjust the splat index to point to the correct address in memory. 9720 if (IsPermutedLoad) { 9721 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9722 SplatIdx += IsFourByte ? 2 : 1; 9723 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9724 "Splat of a value outside of the loaded memory"); 9725 } 9726 9727 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9728 // For 4-byte load-and-splat, we need Power9. 9729 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9730 uint64_t Offset = 0; 9731 if (IsFourByte) 9732 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9733 else 9734 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9735 9736 SDValue BasePtr = LD->getBasePtr(); 9737 if (Offset != 0) 9738 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9739 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9740 SDValue Ops[] = { 9741 LD->getChain(), // Chain 9742 BasePtr, // BasePtr 9743 DAG.getValueType(Op.getValueType()) // VT 9744 }; 9745 SDVTList VTL = 9746 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9747 SDValue LdSplt = 9748 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9749 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9750 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9751 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9752 return LdSplt; 9753 } 9754 } 9755 if (Subtarget.hasP9Vector() && 9756 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9757 isLittleEndian)) { 9758 if (Swap) 9759 std::swap(V1, V2); 9760 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9761 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9762 if (ShiftElts) { 9763 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9764 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9765 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9766 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9767 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9768 } 9769 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9770 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9771 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9772 } 9773 9774 if (Subtarget.hasPrefixInstrs()) { 9775 SDValue SplatInsertNode; 9776 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9777 return SplatInsertNode; 9778 } 9779 9780 if (Subtarget.hasP9Altivec()) { 9781 SDValue NewISDNode; 9782 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9783 return NewISDNode; 9784 9785 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9786 return NewISDNode; 9787 } 9788 9789 if (Subtarget.hasVSX() && 9790 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9791 if (Swap) 9792 std::swap(V1, V2); 9793 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9794 SDValue Conv2 = 9795 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9796 9797 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9798 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9799 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9800 } 9801 9802 if (Subtarget.hasVSX() && 9803 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9804 if (Swap) 9805 std::swap(V1, V2); 9806 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9807 SDValue Conv2 = 9808 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9809 9810 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9811 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9812 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9813 } 9814 9815 if (Subtarget.hasP9Vector()) { 9816 if (PPC::isXXBRHShuffleMask(SVOp)) { 9817 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9818 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9819 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9820 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9821 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9822 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9823 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9824 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9825 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9826 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9827 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9828 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9829 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9830 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9831 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9832 } 9833 } 9834 9835 if (Subtarget.hasVSX()) { 9836 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9837 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9838 9839 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9840 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9841 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9842 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9843 } 9844 9845 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9846 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9847 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9848 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9849 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9850 } 9851 } 9852 9853 // Cases that are handled by instructions that take permute immediates 9854 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9855 // selected by the instruction selector. 9856 if (V2.isUndef()) { 9857 if (PPC::isSplatShuffleMask(SVOp, 1) || 9858 PPC::isSplatShuffleMask(SVOp, 2) || 9859 PPC::isSplatShuffleMask(SVOp, 4) || 9860 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9861 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9862 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9863 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9864 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9865 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9866 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9867 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9868 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9869 (Subtarget.hasP8Altivec() && ( 9870 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9871 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9872 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9873 return Op; 9874 } 9875 } 9876 9877 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9878 // and produce a fixed permutation. If any of these match, do not lower to 9879 // VPERM. 9880 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9881 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9882 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9883 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9884 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9885 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9886 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9887 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9888 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9889 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9890 (Subtarget.hasP8Altivec() && ( 9891 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9892 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9893 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9894 return Op; 9895 9896 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9897 // perfect shuffle table to emit an optimal matching sequence. 9898 ArrayRef<int> PermMask = SVOp->getMask(); 9899 9900 unsigned PFIndexes[4]; 9901 bool isFourElementShuffle = true; 9902 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9903 unsigned EltNo = 8; // Start out undef. 9904 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9905 if (PermMask[i*4+j] < 0) 9906 continue; // Undef, ignore it. 9907 9908 unsigned ByteSource = PermMask[i*4+j]; 9909 if ((ByteSource & 3) != j) { 9910 isFourElementShuffle = false; 9911 break; 9912 } 9913 9914 if (EltNo == 8) { 9915 EltNo = ByteSource/4; 9916 } else if (EltNo != ByteSource/4) { 9917 isFourElementShuffle = false; 9918 break; 9919 } 9920 } 9921 PFIndexes[i] = EltNo; 9922 } 9923 9924 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9925 // perfect shuffle vector to determine if it is cost effective to do this as 9926 // discrete instructions, or whether we should use a vperm. 9927 // For now, we skip this for little endian until such time as we have a 9928 // little-endian perfect shuffle table. 9929 if (isFourElementShuffle && !isLittleEndian) { 9930 // Compute the index in the perfect shuffle table. 9931 unsigned PFTableIndex = 9932 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9933 9934 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9935 unsigned Cost = (PFEntry >> 30); 9936 9937 // Determining when to avoid vperm is tricky. Many things affect the cost 9938 // of vperm, particularly how many times the perm mask needs to be computed. 9939 // For example, if the perm mask can be hoisted out of a loop or is already 9940 // used (perhaps because there are multiple permutes with the same shuffle 9941 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9942 // the loop requires an extra register. 9943 // 9944 // As a compromise, we only emit discrete instructions if the shuffle can be 9945 // generated in 3 or fewer operations. When we have loop information 9946 // available, if this block is within a loop, we should avoid using vperm 9947 // for 3-operation perms and use a constant pool load instead. 9948 if (Cost < 3) 9949 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9950 } 9951 9952 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9953 // vector that will get spilled to the constant pool. 9954 if (V2.isUndef()) V2 = V1; 9955 9956 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9957 // that it is in input element units, not in bytes. Convert now. 9958 9959 // For little endian, the order of the input vectors is reversed, and 9960 // the permutation mask is complemented with respect to 31. This is 9961 // necessary to produce proper semantics with the big-endian-biased vperm 9962 // instruction. 9963 EVT EltVT = V1.getValueType().getVectorElementType(); 9964 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9965 9966 SmallVector<SDValue, 16> ResultMask; 9967 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9968 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9969 9970 for (unsigned j = 0; j != BytesPerElement; ++j) 9971 if (isLittleEndian) 9972 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9973 dl, MVT::i32)); 9974 else 9975 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9976 MVT::i32)); 9977 } 9978 9979 ShufflesHandledWithVPERM++; 9980 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9981 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9982 LLVM_DEBUG(SVOp->dump()); 9983 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9984 LLVM_DEBUG(VPermMask.dump()); 9985 9986 if (isLittleEndian) 9987 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9988 V2, V1, VPermMask); 9989 else 9990 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9991 V1, V2, VPermMask); 9992 } 9993 9994 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9995 /// vector comparison. If it is, return true and fill in Opc/isDot with 9996 /// information about the intrinsic. 9997 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9998 bool &isDot, const PPCSubtarget &Subtarget) { 9999 unsigned IntrinsicID = 10000 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10001 CompareOpc = -1; 10002 isDot = false; 10003 switch (IntrinsicID) { 10004 default: 10005 return false; 10006 // Comparison predicates. 10007 case Intrinsic::ppc_altivec_vcmpbfp_p: 10008 CompareOpc = 966; 10009 isDot = true; 10010 break; 10011 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10012 CompareOpc = 198; 10013 isDot = true; 10014 break; 10015 case Intrinsic::ppc_altivec_vcmpequb_p: 10016 CompareOpc = 6; 10017 isDot = true; 10018 break; 10019 case Intrinsic::ppc_altivec_vcmpequh_p: 10020 CompareOpc = 70; 10021 isDot = true; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpequw_p: 10024 CompareOpc = 134; 10025 isDot = true; 10026 break; 10027 case Intrinsic::ppc_altivec_vcmpequd_p: 10028 if (Subtarget.hasP8Altivec()) { 10029 CompareOpc = 199; 10030 isDot = true; 10031 } else 10032 return false; 10033 break; 10034 case Intrinsic::ppc_altivec_vcmpneb_p: 10035 case Intrinsic::ppc_altivec_vcmpneh_p: 10036 case Intrinsic::ppc_altivec_vcmpnew_p: 10037 case Intrinsic::ppc_altivec_vcmpnezb_p: 10038 case Intrinsic::ppc_altivec_vcmpnezh_p: 10039 case Intrinsic::ppc_altivec_vcmpnezw_p: 10040 if (Subtarget.hasP9Altivec()) { 10041 switch (IntrinsicID) { 10042 default: 10043 llvm_unreachable("Unknown comparison intrinsic."); 10044 case Intrinsic::ppc_altivec_vcmpneb_p: 10045 CompareOpc = 7; 10046 break; 10047 case Intrinsic::ppc_altivec_vcmpneh_p: 10048 CompareOpc = 71; 10049 break; 10050 case Intrinsic::ppc_altivec_vcmpnew_p: 10051 CompareOpc = 135; 10052 break; 10053 case Intrinsic::ppc_altivec_vcmpnezb_p: 10054 CompareOpc = 263; 10055 break; 10056 case Intrinsic::ppc_altivec_vcmpnezh_p: 10057 CompareOpc = 327; 10058 break; 10059 case Intrinsic::ppc_altivec_vcmpnezw_p: 10060 CompareOpc = 391; 10061 break; 10062 } 10063 isDot = true; 10064 } else 10065 return false; 10066 break; 10067 case Intrinsic::ppc_altivec_vcmpgefp_p: 10068 CompareOpc = 454; 10069 isDot = true; 10070 break; 10071 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10072 CompareOpc = 710; 10073 isDot = true; 10074 break; 10075 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10076 CompareOpc = 774; 10077 isDot = true; 10078 break; 10079 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10080 CompareOpc = 838; 10081 isDot = true; 10082 break; 10083 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10084 CompareOpc = 902; 10085 isDot = true; 10086 break; 10087 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10088 if (Subtarget.hasP8Altivec()) { 10089 CompareOpc = 967; 10090 isDot = true; 10091 } else 10092 return false; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpgtub_p: 10095 CompareOpc = 518; 10096 isDot = true; 10097 break; 10098 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10099 CompareOpc = 582; 10100 isDot = true; 10101 break; 10102 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10103 CompareOpc = 646; 10104 isDot = true; 10105 break; 10106 case Intrinsic::ppc_altivec_vcmpgtud_p: 10107 if (Subtarget.hasP8Altivec()) { 10108 CompareOpc = 711; 10109 isDot = true; 10110 } else 10111 return false; 10112 break; 10113 10114 // VSX predicate comparisons use the same infrastructure 10115 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10116 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10117 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10118 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10119 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10120 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10121 if (Subtarget.hasVSX()) { 10122 switch (IntrinsicID) { 10123 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10124 CompareOpc = 99; 10125 break; 10126 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10127 CompareOpc = 115; 10128 break; 10129 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10130 CompareOpc = 107; 10131 break; 10132 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10133 CompareOpc = 67; 10134 break; 10135 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10136 CompareOpc = 83; 10137 break; 10138 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10139 CompareOpc = 75; 10140 break; 10141 } 10142 isDot = true; 10143 } else 10144 return false; 10145 break; 10146 10147 // Normal Comparisons. 10148 case Intrinsic::ppc_altivec_vcmpbfp: 10149 CompareOpc = 966; 10150 break; 10151 case Intrinsic::ppc_altivec_vcmpeqfp: 10152 CompareOpc = 198; 10153 break; 10154 case Intrinsic::ppc_altivec_vcmpequb: 10155 CompareOpc = 6; 10156 break; 10157 case Intrinsic::ppc_altivec_vcmpequh: 10158 CompareOpc = 70; 10159 break; 10160 case Intrinsic::ppc_altivec_vcmpequw: 10161 CompareOpc = 134; 10162 break; 10163 case Intrinsic::ppc_altivec_vcmpequd: 10164 if (Subtarget.hasP8Altivec()) 10165 CompareOpc = 199; 10166 else 10167 return false; 10168 break; 10169 case Intrinsic::ppc_altivec_vcmpneb: 10170 case Intrinsic::ppc_altivec_vcmpneh: 10171 case Intrinsic::ppc_altivec_vcmpnew: 10172 case Intrinsic::ppc_altivec_vcmpnezb: 10173 case Intrinsic::ppc_altivec_vcmpnezh: 10174 case Intrinsic::ppc_altivec_vcmpnezw: 10175 if (Subtarget.hasP9Altivec()) 10176 switch (IntrinsicID) { 10177 default: 10178 llvm_unreachable("Unknown comparison intrinsic."); 10179 case Intrinsic::ppc_altivec_vcmpneb: 10180 CompareOpc = 7; 10181 break; 10182 case Intrinsic::ppc_altivec_vcmpneh: 10183 CompareOpc = 71; 10184 break; 10185 case Intrinsic::ppc_altivec_vcmpnew: 10186 CompareOpc = 135; 10187 break; 10188 case Intrinsic::ppc_altivec_vcmpnezb: 10189 CompareOpc = 263; 10190 break; 10191 case Intrinsic::ppc_altivec_vcmpnezh: 10192 CompareOpc = 327; 10193 break; 10194 case Intrinsic::ppc_altivec_vcmpnezw: 10195 CompareOpc = 391; 10196 break; 10197 } 10198 else 10199 return false; 10200 break; 10201 case Intrinsic::ppc_altivec_vcmpgefp: 10202 CompareOpc = 454; 10203 break; 10204 case Intrinsic::ppc_altivec_vcmpgtfp: 10205 CompareOpc = 710; 10206 break; 10207 case Intrinsic::ppc_altivec_vcmpgtsb: 10208 CompareOpc = 774; 10209 break; 10210 case Intrinsic::ppc_altivec_vcmpgtsh: 10211 CompareOpc = 838; 10212 break; 10213 case Intrinsic::ppc_altivec_vcmpgtsw: 10214 CompareOpc = 902; 10215 break; 10216 case Intrinsic::ppc_altivec_vcmpgtsd: 10217 if (Subtarget.hasP8Altivec()) 10218 CompareOpc = 967; 10219 else 10220 return false; 10221 break; 10222 case Intrinsic::ppc_altivec_vcmpgtub: 10223 CompareOpc = 518; 10224 break; 10225 case Intrinsic::ppc_altivec_vcmpgtuh: 10226 CompareOpc = 582; 10227 break; 10228 case Intrinsic::ppc_altivec_vcmpgtuw: 10229 CompareOpc = 646; 10230 break; 10231 case Intrinsic::ppc_altivec_vcmpgtud: 10232 if (Subtarget.hasP8Altivec()) 10233 CompareOpc = 711; 10234 else 10235 return false; 10236 break; 10237 } 10238 return true; 10239 } 10240 10241 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10242 /// lower, do it, otherwise return null. 10243 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10244 SelectionDAG &DAG) const { 10245 unsigned IntrinsicID = 10246 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10247 10248 SDLoc dl(Op); 10249 10250 if (IntrinsicID == Intrinsic::thread_pointer) { 10251 // Reads the thread pointer register, used for __builtin_thread_pointer. 10252 if (Subtarget.isPPC64()) 10253 return DAG.getRegister(PPC::X13, MVT::i64); 10254 return DAG.getRegister(PPC::R2, MVT::i32); 10255 } 10256 10257 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10258 // opcode number of the comparison. 10259 int CompareOpc; 10260 bool isDot; 10261 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10262 return SDValue(); // Don't custom lower most intrinsics. 10263 10264 // If this is a non-dot comparison, make the VCMP node and we are done. 10265 if (!isDot) { 10266 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10267 Op.getOperand(1), Op.getOperand(2), 10268 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10269 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10270 } 10271 10272 // Create the PPCISD altivec 'dot' comparison node. 10273 SDValue Ops[] = { 10274 Op.getOperand(2), // LHS 10275 Op.getOperand(3), // RHS 10276 DAG.getConstant(CompareOpc, dl, MVT::i32) 10277 }; 10278 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10279 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10280 10281 // Now that we have the comparison, emit a copy from the CR to a GPR. 10282 // This is flagged to the above dot comparison. 10283 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10284 DAG.getRegister(PPC::CR6, MVT::i32), 10285 CompNode.getValue(1)); 10286 10287 // Unpack the result based on how the target uses it. 10288 unsigned BitNo; // Bit # of CR6. 10289 bool InvertBit; // Invert result? 10290 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10291 default: // Can't happen, don't crash on invalid number though. 10292 case 0: // Return the value of the EQ bit of CR6. 10293 BitNo = 0; InvertBit = false; 10294 break; 10295 case 1: // Return the inverted value of the EQ bit of CR6. 10296 BitNo = 0; InvertBit = true; 10297 break; 10298 case 2: // Return the value of the LT bit of CR6. 10299 BitNo = 2; InvertBit = false; 10300 break; 10301 case 3: // Return the inverted value of the LT bit of CR6. 10302 BitNo = 2; InvertBit = true; 10303 break; 10304 } 10305 10306 // Shift the bit into the low position. 10307 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10308 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10309 // Isolate the bit. 10310 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10311 DAG.getConstant(1, dl, MVT::i32)); 10312 10313 // If we are supposed to, toggle the bit. 10314 if (InvertBit) 10315 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10316 DAG.getConstant(1, dl, MVT::i32)); 10317 return Flags; 10318 } 10319 10320 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10321 SelectionDAG &DAG) const { 10322 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10323 // the beginning of the argument list. 10324 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10325 SDLoc DL(Op); 10326 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10327 case Intrinsic::ppc_cfence: { 10328 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10329 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10330 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10331 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10332 Op.getOperand(ArgStart + 1)), 10333 Op.getOperand(0)), 10334 0); 10335 } 10336 default: 10337 break; 10338 } 10339 return SDValue(); 10340 } 10341 10342 // Lower scalar BSWAP64 to xxbrd. 10343 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10344 SDLoc dl(Op); 10345 // MTVSRDD 10346 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10347 Op.getOperand(0)); 10348 // XXBRD 10349 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10350 // MFVSRD 10351 int VectorIndex = 0; 10352 if (Subtarget.isLittleEndian()) 10353 VectorIndex = 1; 10354 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10355 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10356 return Op; 10357 } 10358 10359 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10360 // compared to a value that is atomically loaded (atomic loads zero-extend). 10361 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10362 SelectionDAG &DAG) const { 10363 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10364 "Expecting an atomic compare-and-swap here."); 10365 SDLoc dl(Op); 10366 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10367 EVT MemVT = AtomicNode->getMemoryVT(); 10368 if (MemVT.getSizeInBits() >= 32) 10369 return Op; 10370 10371 SDValue CmpOp = Op.getOperand(2); 10372 // If this is already correctly zero-extended, leave it alone. 10373 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10374 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10375 return Op; 10376 10377 // Clear the high bits of the compare operand. 10378 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10379 SDValue NewCmpOp = 10380 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10381 DAG.getConstant(MaskVal, dl, MVT::i32)); 10382 10383 // Replace the existing compare operand with the properly zero-extended one. 10384 SmallVector<SDValue, 4> Ops; 10385 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10386 Ops.push_back(AtomicNode->getOperand(i)); 10387 Ops[2] = NewCmpOp; 10388 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10389 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10390 auto NodeTy = 10391 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10392 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10393 } 10394 10395 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10396 SelectionDAG &DAG) const { 10397 SDLoc dl(Op); 10398 // Create a stack slot that is 16-byte aligned. 10399 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10400 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10401 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10402 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10403 10404 // Store the input value into Value#0 of the stack slot. 10405 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10406 MachinePointerInfo()); 10407 // Load it out. 10408 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10409 } 10410 10411 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10412 SelectionDAG &DAG) const { 10413 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10414 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10415 10416 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10417 // We have legal lowering for constant indices but not for variable ones. 10418 if (!C) 10419 return SDValue(); 10420 10421 EVT VT = Op.getValueType(); 10422 SDLoc dl(Op); 10423 SDValue V1 = Op.getOperand(0); 10424 SDValue V2 = Op.getOperand(1); 10425 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10426 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10427 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10428 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10429 unsigned InsertAtElement = C->getZExtValue(); 10430 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10431 if (Subtarget.isLittleEndian()) { 10432 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10433 } 10434 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10435 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10436 } 10437 return Op; 10438 } 10439 10440 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10441 SDLoc dl(Op); 10442 if (Op.getValueType() == MVT::v4i32) { 10443 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10444 10445 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10446 // +16 as shift amt. 10447 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10448 SDValue RHSSwap = // = vrlw RHS, 16 10449 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10450 10451 // Shrinkify inputs to v8i16. 10452 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10453 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10454 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10455 10456 // Low parts multiplied together, generating 32-bit results (we ignore the 10457 // top parts). 10458 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10459 LHS, RHS, DAG, dl, MVT::v4i32); 10460 10461 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10462 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10463 // Shift the high parts up 16 bits. 10464 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10465 Neg16, DAG, dl); 10466 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10467 } else if (Op.getValueType() == MVT::v16i8) { 10468 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10469 bool isLittleEndian = Subtarget.isLittleEndian(); 10470 10471 // Multiply the even 8-bit parts, producing 16-bit sums. 10472 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10473 LHS, RHS, DAG, dl, MVT::v8i16); 10474 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10475 10476 // Multiply the odd 8-bit parts, producing 16-bit sums. 10477 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10478 LHS, RHS, DAG, dl, MVT::v8i16); 10479 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10480 10481 // Merge the results together. Because vmuleub and vmuloub are 10482 // instructions with a big-endian bias, we must reverse the 10483 // element numbering and reverse the meaning of "odd" and "even" 10484 // when generating little endian code. 10485 int Ops[16]; 10486 for (unsigned i = 0; i != 8; ++i) { 10487 if (isLittleEndian) { 10488 Ops[i*2 ] = 2*i; 10489 Ops[i*2+1] = 2*i+16; 10490 } else { 10491 Ops[i*2 ] = 2*i+1; 10492 Ops[i*2+1] = 2*i+1+16; 10493 } 10494 } 10495 if (isLittleEndian) 10496 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10497 else 10498 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10499 } else { 10500 llvm_unreachable("Unknown mul to lower!"); 10501 } 10502 } 10503 10504 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10505 10506 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10507 10508 EVT VT = Op.getValueType(); 10509 assert(VT.isVector() && 10510 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10511 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10512 VT == MVT::v16i8) && 10513 "Unexpected vector element type!"); 10514 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10515 "Current subtarget doesn't support smax v2i64!"); 10516 10517 // For vector abs, it can be lowered to: 10518 // abs x 10519 // ==> 10520 // y = -x 10521 // smax(x, y) 10522 10523 SDLoc dl(Op); 10524 SDValue X = Op.getOperand(0); 10525 SDValue Zero = DAG.getConstant(0, dl, VT); 10526 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10527 10528 // SMAX patch https://reviews.llvm.org/D47332 10529 // hasn't landed yet, so use intrinsic first here. 10530 // TODO: Should use SMAX directly once SMAX patch landed 10531 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10532 if (VT == MVT::v2i64) 10533 BifID = Intrinsic::ppc_altivec_vmaxsd; 10534 else if (VT == MVT::v8i16) 10535 BifID = Intrinsic::ppc_altivec_vmaxsh; 10536 else if (VT == MVT::v16i8) 10537 BifID = Intrinsic::ppc_altivec_vmaxsb; 10538 10539 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10540 } 10541 10542 // Custom lowering for fpext vf32 to v2f64 10543 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10544 10545 assert(Op.getOpcode() == ISD::FP_EXTEND && 10546 "Should only be called for ISD::FP_EXTEND"); 10547 10548 // FIXME: handle extends from half precision float vectors on P9. 10549 // We only want to custom lower an extend from v2f32 to v2f64. 10550 if (Op.getValueType() != MVT::v2f64 || 10551 Op.getOperand(0).getValueType() != MVT::v2f32) 10552 return SDValue(); 10553 10554 SDLoc dl(Op); 10555 SDValue Op0 = Op.getOperand(0); 10556 10557 switch (Op0.getOpcode()) { 10558 default: 10559 return SDValue(); 10560 case ISD::EXTRACT_SUBVECTOR: { 10561 assert(Op0.getNumOperands() == 2 && 10562 isa<ConstantSDNode>(Op0->getOperand(1)) && 10563 "Node should have 2 operands with second one being a constant!"); 10564 10565 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10566 return SDValue(); 10567 10568 // Custom lower is only done for high or low doubleword. 10569 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10570 if (Idx % 2 != 0) 10571 return SDValue(); 10572 10573 // Since input is v4f32, at this point Idx is either 0 or 2. 10574 // Shift to get the doubleword position we want. 10575 int DWord = Idx >> 1; 10576 10577 // High and low word positions are different on little endian. 10578 if (Subtarget.isLittleEndian()) 10579 DWord ^= 0x1; 10580 10581 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10582 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10583 } 10584 case ISD::FADD: 10585 case ISD::FMUL: 10586 case ISD::FSUB: { 10587 SDValue NewLoad[2]; 10588 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10589 // Ensure both input are loads. 10590 SDValue LdOp = Op0.getOperand(i); 10591 if (LdOp.getOpcode() != ISD::LOAD) 10592 return SDValue(); 10593 // Generate new load node. 10594 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10595 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10596 NewLoad[i] = DAG.getMemIntrinsicNode( 10597 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10598 LD->getMemoryVT(), LD->getMemOperand()); 10599 } 10600 SDValue NewOp = 10601 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10602 NewLoad[1], Op0.getNode()->getFlags()); 10603 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10604 DAG.getConstant(0, dl, MVT::i32)); 10605 } 10606 case ISD::LOAD: { 10607 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10608 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10609 SDValue NewLd = DAG.getMemIntrinsicNode( 10610 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10611 LD->getMemoryVT(), LD->getMemOperand()); 10612 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10613 DAG.getConstant(0, dl, MVT::i32)); 10614 } 10615 } 10616 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10617 } 10618 10619 /// LowerOperation - Provide custom lowering hooks for some operations. 10620 /// 10621 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10622 switch (Op.getOpcode()) { 10623 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10624 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10625 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10626 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10627 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10628 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10629 case ISD::SETCC: return LowerSETCC(Op, DAG); 10630 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10631 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10632 10633 // Variable argument lowering. 10634 case ISD::VASTART: return LowerVASTART(Op, DAG); 10635 case ISD::VAARG: return LowerVAARG(Op, DAG); 10636 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10637 10638 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10639 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10640 case ISD::GET_DYNAMIC_AREA_OFFSET: 10641 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10642 10643 // Exception handling lowering. 10644 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10645 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10646 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10647 10648 case ISD::LOAD: return LowerLOAD(Op, DAG); 10649 case ISD::STORE: return LowerSTORE(Op, DAG); 10650 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10651 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10652 case ISD::STRICT_FP_TO_UINT: 10653 case ISD::STRICT_FP_TO_SINT: 10654 case ISD::FP_TO_UINT: 10655 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10656 case ISD::STRICT_UINT_TO_FP: 10657 case ISD::STRICT_SINT_TO_FP: 10658 case ISD::UINT_TO_FP: 10659 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10660 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10661 10662 // Lower 64-bit shifts. 10663 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10664 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10665 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10666 10667 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10668 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10669 10670 // Vector-related lowering. 10671 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10672 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10673 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10674 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10675 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10676 case ISD::MUL: return LowerMUL(Op, DAG); 10677 case ISD::ABS: return LowerABS(Op, DAG); 10678 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10679 case ISD::ROTL: return LowerROTL(Op, DAG); 10680 10681 // For counter-based loop handling. 10682 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10683 10684 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10685 10686 // Frame & Return address. 10687 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10688 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10689 10690 case ISD::INTRINSIC_VOID: 10691 return LowerINTRINSIC_VOID(Op, DAG); 10692 case ISD::BSWAP: 10693 return LowerBSWAP(Op, DAG); 10694 case ISD::ATOMIC_CMP_SWAP: 10695 return LowerATOMIC_CMP_SWAP(Op, DAG); 10696 } 10697 } 10698 10699 void PPCTargetLowering::LowerOperationWrapper(SDNode *N, 10700 SmallVectorImpl<SDValue> &Results, 10701 SelectionDAG &DAG) const { 10702 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10703 10704 if (!Res.getNode()) 10705 return; 10706 10707 // Take the return value as-is if original node has only one result. 10708 if (N->getNumValues() == 1) { 10709 Results.push_back(Res); 10710 return; 10711 } 10712 10713 // New node should have the same number of results. 10714 assert((N->getNumValues() == Res->getNumValues()) && 10715 "Lowering returned the wrong number of results!"); 10716 10717 for (unsigned i = 0; i < N->getNumValues(); ++i) 10718 Results.push_back(Res.getValue(i)); 10719 } 10720 10721 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10722 SmallVectorImpl<SDValue>&Results, 10723 SelectionDAG &DAG) const { 10724 SDLoc dl(N); 10725 switch (N->getOpcode()) { 10726 default: 10727 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10728 case ISD::READCYCLECOUNTER: { 10729 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10730 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10731 10732 Results.push_back( 10733 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10734 Results.push_back(RTB.getValue(2)); 10735 break; 10736 } 10737 case ISD::INTRINSIC_W_CHAIN: { 10738 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10739 Intrinsic::loop_decrement) 10740 break; 10741 10742 assert(N->getValueType(0) == MVT::i1 && 10743 "Unexpected result type for CTR decrement intrinsic"); 10744 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10745 N->getValueType(0)); 10746 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10747 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10748 N->getOperand(1)); 10749 10750 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10751 Results.push_back(NewInt.getValue(1)); 10752 break; 10753 } 10754 case ISD::VAARG: { 10755 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10756 return; 10757 10758 EVT VT = N->getValueType(0); 10759 10760 if (VT == MVT::i64) { 10761 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10762 10763 Results.push_back(NewNode); 10764 Results.push_back(NewNode.getValue(1)); 10765 } 10766 return; 10767 } 10768 case ISD::STRICT_FP_TO_SINT: 10769 case ISD::STRICT_FP_TO_UINT: 10770 case ISD::FP_TO_SINT: 10771 case ISD::FP_TO_UINT: 10772 // LowerFP_TO_INT() can only handle f32 and f64. 10773 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10774 MVT::ppcf128) 10775 return; 10776 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10777 return; 10778 case ISD::TRUNCATE: { 10779 if (!N->getValueType(0).isVector()) 10780 return; 10781 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 10782 if (Lowered) 10783 Results.push_back(Lowered); 10784 return; 10785 } 10786 case ISD::BITCAST: 10787 // Don't handle bitcast here. 10788 return; 10789 case ISD::FP_EXTEND: 10790 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10791 if (Lowered) 10792 Results.push_back(Lowered); 10793 return; 10794 } 10795 } 10796 10797 //===----------------------------------------------------------------------===// 10798 // Other Lowering Code 10799 //===----------------------------------------------------------------------===// 10800 10801 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10802 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10803 Function *Func = Intrinsic::getDeclaration(M, Id); 10804 return Builder.CreateCall(Func, {}); 10805 } 10806 10807 // The mappings for emitLeading/TrailingFence is taken from 10808 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10809 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10810 Instruction *Inst, 10811 AtomicOrdering Ord) const { 10812 if (Ord == AtomicOrdering::SequentiallyConsistent) 10813 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10814 if (isReleaseOrStronger(Ord)) 10815 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10816 return nullptr; 10817 } 10818 10819 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10820 Instruction *Inst, 10821 AtomicOrdering Ord) const { 10822 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10823 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10824 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10825 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10826 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10827 return Builder.CreateCall( 10828 Intrinsic::getDeclaration( 10829 Builder.GetInsertBlock()->getParent()->getParent(), 10830 Intrinsic::ppc_cfence, {Inst->getType()}), 10831 {Inst}); 10832 // FIXME: Can use isync for rmw operation. 10833 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10834 } 10835 return nullptr; 10836 } 10837 10838 MachineBasicBlock * 10839 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10840 unsigned AtomicSize, 10841 unsigned BinOpcode, 10842 unsigned CmpOpcode, 10843 unsigned CmpPred) const { 10844 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10845 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10846 10847 auto LoadMnemonic = PPC::LDARX; 10848 auto StoreMnemonic = PPC::STDCX; 10849 switch (AtomicSize) { 10850 default: 10851 llvm_unreachable("Unexpected size of atomic entity"); 10852 case 1: 10853 LoadMnemonic = PPC::LBARX; 10854 StoreMnemonic = PPC::STBCX; 10855 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10856 break; 10857 case 2: 10858 LoadMnemonic = PPC::LHARX; 10859 StoreMnemonic = PPC::STHCX; 10860 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10861 break; 10862 case 4: 10863 LoadMnemonic = PPC::LWARX; 10864 StoreMnemonic = PPC::STWCX; 10865 break; 10866 case 8: 10867 LoadMnemonic = PPC::LDARX; 10868 StoreMnemonic = PPC::STDCX; 10869 break; 10870 } 10871 10872 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10873 MachineFunction *F = BB->getParent(); 10874 MachineFunction::iterator It = ++BB->getIterator(); 10875 10876 Register dest = MI.getOperand(0).getReg(); 10877 Register ptrA = MI.getOperand(1).getReg(); 10878 Register ptrB = MI.getOperand(2).getReg(); 10879 Register incr = MI.getOperand(3).getReg(); 10880 DebugLoc dl = MI.getDebugLoc(); 10881 10882 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10883 MachineBasicBlock *loop2MBB = 10884 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10885 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10886 F->insert(It, loopMBB); 10887 if (CmpOpcode) 10888 F->insert(It, loop2MBB); 10889 F->insert(It, exitMBB); 10890 exitMBB->splice(exitMBB->begin(), BB, 10891 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10892 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10893 10894 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10895 Register TmpReg = (!BinOpcode) ? incr : 10896 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10897 : &PPC::GPRCRegClass); 10898 10899 // thisMBB: 10900 // ... 10901 // fallthrough --> loopMBB 10902 BB->addSuccessor(loopMBB); 10903 10904 // loopMBB: 10905 // l[wd]arx dest, ptr 10906 // add r0, dest, incr 10907 // st[wd]cx. r0, ptr 10908 // bne- loopMBB 10909 // fallthrough --> exitMBB 10910 10911 // For max/min... 10912 // loopMBB: 10913 // l[wd]arx dest, ptr 10914 // cmpl?[wd] incr, dest 10915 // bgt exitMBB 10916 // loop2MBB: 10917 // st[wd]cx. dest, ptr 10918 // bne- loopMBB 10919 // fallthrough --> exitMBB 10920 10921 BB = loopMBB; 10922 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10923 .addReg(ptrA).addReg(ptrB); 10924 if (BinOpcode) 10925 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10926 if (CmpOpcode) { 10927 // Signed comparisons of byte or halfword values must be sign-extended. 10928 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10929 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10930 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10931 ExtReg).addReg(dest); 10932 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10933 .addReg(incr).addReg(ExtReg); 10934 } else 10935 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10936 .addReg(incr).addReg(dest); 10937 10938 BuildMI(BB, dl, TII->get(PPC::BCC)) 10939 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10940 BB->addSuccessor(loop2MBB); 10941 BB->addSuccessor(exitMBB); 10942 BB = loop2MBB; 10943 } 10944 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10945 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10946 BuildMI(BB, dl, TII->get(PPC::BCC)) 10947 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10948 BB->addSuccessor(loopMBB); 10949 BB->addSuccessor(exitMBB); 10950 10951 // exitMBB: 10952 // ... 10953 BB = exitMBB; 10954 return BB; 10955 } 10956 10957 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10958 MachineInstr &MI, MachineBasicBlock *BB, 10959 bool is8bit, // operation 10960 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10961 // If we support part-word atomic mnemonics, just use them 10962 if (Subtarget.hasPartwordAtomics()) 10963 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10964 CmpPred); 10965 10966 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10967 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10968 // In 64 bit mode we have to use 64 bits for addresses, even though the 10969 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10970 // registers without caring whether they're 32 or 64, but here we're 10971 // doing actual arithmetic on the addresses. 10972 bool is64bit = Subtarget.isPPC64(); 10973 bool isLittleEndian = Subtarget.isLittleEndian(); 10974 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10975 10976 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10977 MachineFunction *F = BB->getParent(); 10978 MachineFunction::iterator It = ++BB->getIterator(); 10979 10980 Register dest = MI.getOperand(0).getReg(); 10981 Register ptrA = MI.getOperand(1).getReg(); 10982 Register ptrB = MI.getOperand(2).getReg(); 10983 Register incr = MI.getOperand(3).getReg(); 10984 DebugLoc dl = MI.getDebugLoc(); 10985 10986 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10987 MachineBasicBlock *loop2MBB = 10988 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10989 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10990 F->insert(It, loopMBB); 10991 if (CmpOpcode) 10992 F->insert(It, loop2MBB); 10993 F->insert(It, exitMBB); 10994 exitMBB->splice(exitMBB->begin(), BB, 10995 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10996 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10997 10998 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10999 const TargetRegisterClass *RC = 11000 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11001 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11002 11003 Register PtrReg = RegInfo.createVirtualRegister(RC); 11004 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11005 Register ShiftReg = 11006 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11007 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11008 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11009 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11010 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11011 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11012 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11013 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11014 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11015 Register Ptr1Reg; 11016 Register TmpReg = 11017 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11018 11019 // thisMBB: 11020 // ... 11021 // fallthrough --> loopMBB 11022 BB->addSuccessor(loopMBB); 11023 11024 // The 4-byte load must be aligned, while a char or short may be 11025 // anywhere in the word. Hence all this nasty bookkeeping code. 11026 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11027 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11028 // xori shift, shift1, 24 [16] 11029 // rlwinm ptr, ptr1, 0, 0, 29 11030 // slw incr2, incr, shift 11031 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11032 // slw mask, mask2, shift 11033 // loopMBB: 11034 // lwarx tmpDest, ptr 11035 // add tmp, tmpDest, incr2 11036 // andc tmp2, tmpDest, mask 11037 // and tmp3, tmp, mask 11038 // or tmp4, tmp3, tmp2 11039 // stwcx. tmp4, ptr 11040 // bne- loopMBB 11041 // fallthrough --> exitMBB 11042 // srw dest, tmpDest, shift 11043 if (ptrA != ZeroReg) { 11044 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11045 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11046 .addReg(ptrA) 11047 .addReg(ptrB); 11048 } else { 11049 Ptr1Reg = ptrB; 11050 } 11051 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11052 // mode. 11053 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11054 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11055 .addImm(3) 11056 .addImm(27) 11057 .addImm(is8bit ? 28 : 27); 11058 if (!isLittleEndian) 11059 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11060 .addReg(Shift1Reg) 11061 .addImm(is8bit ? 24 : 16); 11062 if (is64bit) 11063 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11064 .addReg(Ptr1Reg) 11065 .addImm(0) 11066 .addImm(61); 11067 else 11068 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11069 .addReg(Ptr1Reg) 11070 .addImm(0) 11071 .addImm(0) 11072 .addImm(29); 11073 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11074 if (is8bit) 11075 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11076 else { 11077 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11078 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11079 .addReg(Mask3Reg) 11080 .addImm(65535); 11081 } 11082 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11083 .addReg(Mask2Reg) 11084 .addReg(ShiftReg); 11085 11086 BB = loopMBB; 11087 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11088 .addReg(ZeroReg) 11089 .addReg(PtrReg); 11090 if (BinOpcode) 11091 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11092 .addReg(Incr2Reg) 11093 .addReg(TmpDestReg); 11094 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11095 .addReg(TmpDestReg) 11096 .addReg(MaskReg); 11097 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11098 if (CmpOpcode) { 11099 // For unsigned comparisons, we can directly compare the shifted values. 11100 // For signed comparisons we shift and sign extend. 11101 Register SReg = RegInfo.createVirtualRegister(GPRC); 11102 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11103 .addReg(TmpDestReg) 11104 .addReg(MaskReg); 11105 unsigned ValueReg = SReg; 11106 unsigned CmpReg = Incr2Reg; 11107 if (CmpOpcode == PPC::CMPW) { 11108 ValueReg = RegInfo.createVirtualRegister(GPRC); 11109 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11110 .addReg(SReg) 11111 .addReg(ShiftReg); 11112 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11113 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11114 .addReg(ValueReg); 11115 ValueReg = ValueSReg; 11116 CmpReg = incr; 11117 } 11118 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 11119 .addReg(CmpReg) 11120 .addReg(ValueReg); 11121 BuildMI(BB, dl, TII->get(PPC::BCC)) 11122 .addImm(CmpPred) 11123 .addReg(PPC::CR0) 11124 .addMBB(exitMBB); 11125 BB->addSuccessor(loop2MBB); 11126 BB->addSuccessor(exitMBB); 11127 BB = loop2MBB; 11128 } 11129 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11130 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11131 .addReg(Tmp4Reg) 11132 .addReg(ZeroReg) 11133 .addReg(PtrReg); 11134 BuildMI(BB, dl, TII->get(PPC::BCC)) 11135 .addImm(PPC::PRED_NE) 11136 .addReg(PPC::CR0) 11137 .addMBB(loopMBB); 11138 BB->addSuccessor(loopMBB); 11139 BB->addSuccessor(exitMBB); 11140 11141 // exitMBB: 11142 // ... 11143 BB = exitMBB; 11144 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11145 .addReg(TmpDestReg) 11146 .addReg(ShiftReg); 11147 return BB; 11148 } 11149 11150 llvm::MachineBasicBlock * 11151 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11152 MachineBasicBlock *MBB) const { 11153 DebugLoc DL = MI.getDebugLoc(); 11154 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11155 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11156 11157 MachineFunction *MF = MBB->getParent(); 11158 MachineRegisterInfo &MRI = MF->getRegInfo(); 11159 11160 const BasicBlock *BB = MBB->getBasicBlock(); 11161 MachineFunction::iterator I = ++MBB->getIterator(); 11162 11163 Register DstReg = MI.getOperand(0).getReg(); 11164 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11165 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11166 Register mainDstReg = MRI.createVirtualRegister(RC); 11167 Register restoreDstReg = MRI.createVirtualRegister(RC); 11168 11169 MVT PVT = getPointerTy(MF->getDataLayout()); 11170 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11171 "Invalid Pointer Size!"); 11172 // For v = setjmp(buf), we generate 11173 // 11174 // thisMBB: 11175 // SjLjSetup mainMBB 11176 // bl mainMBB 11177 // v_restore = 1 11178 // b sinkMBB 11179 // 11180 // mainMBB: 11181 // buf[LabelOffset] = LR 11182 // v_main = 0 11183 // 11184 // sinkMBB: 11185 // v = phi(main, restore) 11186 // 11187 11188 MachineBasicBlock *thisMBB = MBB; 11189 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11190 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11191 MF->insert(I, mainMBB); 11192 MF->insert(I, sinkMBB); 11193 11194 MachineInstrBuilder MIB; 11195 11196 // Transfer the remainder of BB and its successor edges to sinkMBB. 11197 sinkMBB->splice(sinkMBB->begin(), MBB, 11198 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11199 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11200 11201 // Note that the structure of the jmp_buf used here is not compatible 11202 // with that used by libc, and is not designed to be. Specifically, it 11203 // stores only those 'reserved' registers that LLVM does not otherwise 11204 // understand how to spill. Also, by convention, by the time this 11205 // intrinsic is called, Clang has already stored the frame address in the 11206 // first slot of the buffer and stack address in the third. Following the 11207 // X86 target code, we'll store the jump address in the second slot. We also 11208 // need to save the TOC pointer (R2) to handle jumps between shared 11209 // libraries, and that will be stored in the fourth slot. The thread 11210 // identifier (R13) is not affected. 11211 11212 // thisMBB: 11213 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11214 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11215 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11216 11217 // Prepare IP either in reg. 11218 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11219 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11220 Register BufReg = MI.getOperand(1).getReg(); 11221 11222 if (Subtarget.is64BitELFABI()) { 11223 setUsesTOCBasePtr(*MBB->getParent()); 11224 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11225 .addReg(PPC::X2) 11226 .addImm(TOCOffset) 11227 .addReg(BufReg) 11228 .cloneMemRefs(MI); 11229 } 11230 11231 // Naked functions never have a base pointer, and so we use r1. For all 11232 // other functions, this decision must be delayed until during PEI. 11233 unsigned BaseReg; 11234 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11235 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11236 else 11237 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11238 11239 MIB = BuildMI(*thisMBB, MI, DL, 11240 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11241 .addReg(BaseReg) 11242 .addImm(BPOffset) 11243 .addReg(BufReg) 11244 .cloneMemRefs(MI); 11245 11246 // Setup 11247 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11248 MIB.addRegMask(TRI->getNoPreservedMask()); 11249 11250 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11251 11252 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11253 .addMBB(mainMBB); 11254 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11255 11256 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11257 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11258 11259 // mainMBB: 11260 // mainDstReg = 0 11261 MIB = 11262 BuildMI(mainMBB, DL, 11263 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11264 11265 // Store IP 11266 if (Subtarget.isPPC64()) { 11267 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11268 .addReg(LabelReg) 11269 .addImm(LabelOffset) 11270 .addReg(BufReg); 11271 } else { 11272 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11273 .addReg(LabelReg) 11274 .addImm(LabelOffset) 11275 .addReg(BufReg); 11276 } 11277 MIB.cloneMemRefs(MI); 11278 11279 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11280 mainMBB->addSuccessor(sinkMBB); 11281 11282 // sinkMBB: 11283 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11284 TII->get(PPC::PHI), DstReg) 11285 .addReg(mainDstReg).addMBB(mainMBB) 11286 .addReg(restoreDstReg).addMBB(thisMBB); 11287 11288 MI.eraseFromParent(); 11289 return sinkMBB; 11290 } 11291 11292 MachineBasicBlock * 11293 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11294 MachineBasicBlock *MBB) const { 11295 DebugLoc DL = MI.getDebugLoc(); 11296 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11297 11298 MachineFunction *MF = MBB->getParent(); 11299 MachineRegisterInfo &MRI = MF->getRegInfo(); 11300 11301 MVT PVT = getPointerTy(MF->getDataLayout()); 11302 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11303 "Invalid Pointer Size!"); 11304 11305 const TargetRegisterClass *RC = 11306 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11307 Register Tmp = MRI.createVirtualRegister(RC); 11308 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11309 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11310 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11311 unsigned BP = 11312 (PVT == MVT::i64) 11313 ? PPC::X30 11314 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11315 : PPC::R30); 11316 11317 MachineInstrBuilder MIB; 11318 11319 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11320 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11321 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11322 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11323 11324 Register BufReg = MI.getOperand(0).getReg(); 11325 11326 // Reload FP (the jumped-to function may not have had a 11327 // frame pointer, and if so, then its r31 will be restored 11328 // as necessary). 11329 if (PVT == MVT::i64) { 11330 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11331 .addImm(0) 11332 .addReg(BufReg); 11333 } else { 11334 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11335 .addImm(0) 11336 .addReg(BufReg); 11337 } 11338 MIB.cloneMemRefs(MI); 11339 11340 // Reload IP 11341 if (PVT == MVT::i64) { 11342 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11343 .addImm(LabelOffset) 11344 .addReg(BufReg); 11345 } else { 11346 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11347 .addImm(LabelOffset) 11348 .addReg(BufReg); 11349 } 11350 MIB.cloneMemRefs(MI); 11351 11352 // Reload SP 11353 if (PVT == MVT::i64) { 11354 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11355 .addImm(SPOffset) 11356 .addReg(BufReg); 11357 } else { 11358 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11359 .addImm(SPOffset) 11360 .addReg(BufReg); 11361 } 11362 MIB.cloneMemRefs(MI); 11363 11364 // Reload BP 11365 if (PVT == MVT::i64) { 11366 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11367 .addImm(BPOffset) 11368 .addReg(BufReg); 11369 } else { 11370 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11371 .addImm(BPOffset) 11372 .addReg(BufReg); 11373 } 11374 MIB.cloneMemRefs(MI); 11375 11376 // Reload TOC 11377 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11378 setUsesTOCBasePtr(*MBB->getParent()); 11379 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11380 .addImm(TOCOffset) 11381 .addReg(BufReg) 11382 .cloneMemRefs(MI); 11383 } 11384 11385 // Jump 11386 BuildMI(*MBB, MI, DL, 11387 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11388 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11389 11390 MI.eraseFromParent(); 11391 return MBB; 11392 } 11393 11394 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11395 // If the function specifically requests inline stack probes, emit them. 11396 if (MF.getFunction().hasFnAttribute("probe-stack")) 11397 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11398 "inline-asm"; 11399 return false; 11400 } 11401 11402 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11403 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11404 unsigned StackAlign = TFI->getStackAlignment(); 11405 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11406 "Unexpected stack alignment"); 11407 // The default stack probe size is 4096 if the function has no 11408 // stack-probe-size attribute. 11409 unsigned StackProbeSize = 4096; 11410 const Function &Fn = MF.getFunction(); 11411 if (Fn.hasFnAttribute("stack-probe-size")) 11412 Fn.getFnAttribute("stack-probe-size") 11413 .getValueAsString() 11414 .getAsInteger(0, StackProbeSize); 11415 // Round down to the stack alignment. 11416 StackProbeSize &= ~(StackAlign - 1); 11417 return StackProbeSize ? StackProbeSize : StackAlign; 11418 } 11419 11420 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11421 // into three phases. In the first phase, it uses pseudo instruction 11422 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11423 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11424 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11425 // MaxCallFrameSize so that it can calculate correct data area pointer. 11426 MachineBasicBlock * 11427 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11428 MachineBasicBlock *MBB) const { 11429 const bool isPPC64 = Subtarget.isPPC64(); 11430 MachineFunction *MF = MBB->getParent(); 11431 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11432 DebugLoc DL = MI.getDebugLoc(); 11433 const unsigned ProbeSize = getStackProbeSize(*MF); 11434 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11435 MachineRegisterInfo &MRI = MF->getRegInfo(); 11436 // The CFG of probing stack looks as 11437 // +-----+ 11438 // | MBB | 11439 // +--+--+ 11440 // | 11441 // +----v----+ 11442 // +--->+ TestMBB +---+ 11443 // | +----+----+ | 11444 // | | | 11445 // | +-----v----+ | 11446 // +---+ BlockMBB | | 11447 // +----------+ | 11448 // | 11449 // +---------+ | 11450 // | TailMBB +<--+ 11451 // +---------+ 11452 // In MBB, calculate previous frame pointer and final stack pointer. 11453 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11454 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11455 // TailMBB is spliced via \p MI. 11456 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11457 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11458 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11459 11460 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11461 MF->insert(MBBIter, TestMBB); 11462 MF->insert(MBBIter, BlockMBB); 11463 MF->insert(MBBIter, TailMBB); 11464 11465 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11466 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11467 11468 Register DstReg = MI.getOperand(0).getReg(); 11469 Register NegSizeReg = MI.getOperand(1).getReg(); 11470 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11471 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11472 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11473 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11474 11475 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11476 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11477 // NegSize. 11478 unsigned ProbeOpc; 11479 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11480 ProbeOpc = 11481 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11482 else 11483 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11484 // and NegSizeReg will be allocated in the same phyreg to avoid 11485 // redundant copy when NegSizeReg has only one use which is current MI and 11486 // will be replaced by PREPARE_PROBED_ALLOCA then. 11487 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11488 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11489 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11490 .addDef(ActualNegSizeReg) 11491 .addReg(NegSizeReg) 11492 .add(MI.getOperand(2)) 11493 .add(MI.getOperand(3)); 11494 11495 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11496 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11497 FinalStackPtr) 11498 .addReg(SPReg) 11499 .addReg(ActualNegSizeReg); 11500 11501 // Materialize a scratch register for update. 11502 int64_t NegProbeSize = -(int64_t)ProbeSize; 11503 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11504 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11505 if (!isInt<16>(NegProbeSize)) { 11506 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11507 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11508 .addImm(NegProbeSize >> 16); 11509 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11510 ScratchReg) 11511 .addReg(TempReg) 11512 .addImm(NegProbeSize & 0xFFFF); 11513 } else 11514 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11515 .addImm(NegProbeSize); 11516 11517 { 11518 // Probing leading residual part. 11519 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11520 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11521 .addReg(ActualNegSizeReg) 11522 .addReg(ScratchReg); 11523 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11524 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11525 .addReg(Div) 11526 .addReg(ScratchReg); 11527 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11528 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11529 .addReg(Mul) 11530 .addReg(ActualNegSizeReg); 11531 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11532 .addReg(FramePointer) 11533 .addReg(SPReg) 11534 .addReg(NegMod); 11535 } 11536 11537 { 11538 // Remaining part should be multiple of ProbeSize. 11539 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11540 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11541 .addReg(SPReg) 11542 .addReg(FinalStackPtr); 11543 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11544 .addImm(PPC::PRED_EQ) 11545 .addReg(CmpResult) 11546 .addMBB(TailMBB); 11547 TestMBB->addSuccessor(BlockMBB); 11548 TestMBB->addSuccessor(TailMBB); 11549 } 11550 11551 { 11552 // Touch the block. 11553 // |P...|P...|P... 11554 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11555 .addReg(FramePointer) 11556 .addReg(SPReg) 11557 .addReg(ScratchReg); 11558 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11559 BlockMBB->addSuccessor(TestMBB); 11560 } 11561 11562 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11563 // DYNAREAOFFSET pseudo instruction to get the future result. 11564 Register MaxCallFrameSizeReg = 11565 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11566 BuildMI(TailMBB, DL, 11567 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11568 MaxCallFrameSizeReg) 11569 .add(MI.getOperand(2)) 11570 .add(MI.getOperand(3)); 11571 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11572 .addReg(SPReg) 11573 .addReg(MaxCallFrameSizeReg); 11574 11575 // Splice instructions after MI to TailMBB. 11576 TailMBB->splice(TailMBB->end(), MBB, 11577 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11578 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11579 MBB->addSuccessor(TestMBB); 11580 11581 // Delete the pseudo instruction. 11582 MI.eraseFromParent(); 11583 11584 ++NumDynamicAllocaProbed; 11585 return TailMBB; 11586 } 11587 11588 MachineBasicBlock * 11589 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11590 MachineBasicBlock *BB) const { 11591 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11592 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11593 if (Subtarget.is64BitELFABI() && 11594 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11595 !Subtarget.isUsingPCRelativeCalls()) { 11596 // Call lowering should have added an r2 operand to indicate a dependence 11597 // on the TOC base pointer value. It can't however, because there is no 11598 // way to mark the dependence as implicit there, and so the stackmap code 11599 // will confuse it with a regular operand. Instead, add the dependence 11600 // here. 11601 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11602 } 11603 11604 return emitPatchPoint(MI, BB); 11605 } 11606 11607 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11608 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11609 return emitEHSjLjSetJmp(MI, BB); 11610 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11611 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11612 return emitEHSjLjLongJmp(MI, BB); 11613 } 11614 11615 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11616 11617 // To "insert" these instructions we actually have to insert their 11618 // control-flow patterns. 11619 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11620 MachineFunction::iterator It = ++BB->getIterator(); 11621 11622 MachineFunction *F = BB->getParent(); 11623 11624 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11625 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11626 MI.getOpcode() == PPC::SELECT_I8) { 11627 SmallVector<MachineOperand, 2> Cond; 11628 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11629 MI.getOpcode() == PPC::SELECT_CC_I8) 11630 Cond.push_back(MI.getOperand(4)); 11631 else 11632 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11633 Cond.push_back(MI.getOperand(1)); 11634 11635 DebugLoc dl = MI.getDebugLoc(); 11636 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11637 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11638 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11639 MI.getOpcode() == PPC::SELECT_CC_F8 || 11640 MI.getOpcode() == PPC::SELECT_CC_F16 || 11641 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11642 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11643 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11644 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11645 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11646 MI.getOpcode() == PPC::SELECT_CC_SPE || 11647 MI.getOpcode() == PPC::SELECT_F4 || 11648 MI.getOpcode() == PPC::SELECT_F8 || 11649 MI.getOpcode() == PPC::SELECT_F16 || 11650 MI.getOpcode() == PPC::SELECT_SPE || 11651 MI.getOpcode() == PPC::SELECT_SPE4 || 11652 MI.getOpcode() == PPC::SELECT_VRRC || 11653 MI.getOpcode() == PPC::SELECT_VSFRC || 11654 MI.getOpcode() == PPC::SELECT_VSSRC || 11655 MI.getOpcode() == PPC::SELECT_VSRC) { 11656 // The incoming instruction knows the destination vreg to set, the 11657 // condition code register to branch on, the true/false values to 11658 // select between, and a branch opcode to use. 11659 11660 // thisMBB: 11661 // ... 11662 // TrueVal = ... 11663 // cmpTY ccX, r1, r2 11664 // bCC copy1MBB 11665 // fallthrough --> copy0MBB 11666 MachineBasicBlock *thisMBB = BB; 11667 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11668 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11669 DebugLoc dl = MI.getDebugLoc(); 11670 F->insert(It, copy0MBB); 11671 F->insert(It, sinkMBB); 11672 11673 // Transfer the remainder of BB and its successor edges to sinkMBB. 11674 sinkMBB->splice(sinkMBB->begin(), BB, 11675 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11676 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11677 11678 // Next, add the true and fallthrough blocks as its successors. 11679 BB->addSuccessor(copy0MBB); 11680 BB->addSuccessor(sinkMBB); 11681 11682 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11683 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11684 MI.getOpcode() == PPC::SELECT_F16 || 11685 MI.getOpcode() == PPC::SELECT_SPE4 || 11686 MI.getOpcode() == PPC::SELECT_SPE || 11687 MI.getOpcode() == PPC::SELECT_VRRC || 11688 MI.getOpcode() == PPC::SELECT_VSFRC || 11689 MI.getOpcode() == PPC::SELECT_VSSRC || 11690 MI.getOpcode() == PPC::SELECT_VSRC) { 11691 BuildMI(BB, dl, TII->get(PPC::BC)) 11692 .addReg(MI.getOperand(1).getReg()) 11693 .addMBB(sinkMBB); 11694 } else { 11695 unsigned SelectPred = MI.getOperand(4).getImm(); 11696 BuildMI(BB, dl, TII->get(PPC::BCC)) 11697 .addImm(SelectPred) 11698 .addReg(MI.getOperand(1).getReg()) 11699 .addMBB(sinkMBB); 11700 } 11701 11702 // copy0MBB: 11703 // %FalseValue = ... 11704 // # fallthrough to sinkMBB 11705 BB = copy0MBB; 11706 11707 // Update machine-CFG edges 11708 BB->addSuccessor(sinkMBB); 11709 11710 // sinkMBB: 11711 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11712 // ... 11713 BB = sinkMBB; 11714 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11715 .addReg(MI.getOperand(3).getReg()) 11716 .addMBB(copy0MBB) 11717 .addReg(MI.getOperand(2).getReg()) 11718 .addMBB(thisMBB); 11719 } else if (MI.getOpcode() == PPC::ReadTB) { 11720 // To read the 64-bit time-base register on a 32-bit target, we read the 11721 // two halves. Should the counter have wrapped while it was being read, we 11722 // need to try again. 11723 // ... 11724 // readLoop: 11725 // mfspr Rx,TBU # load from TBU 11726 // mfspr Ry,TB # load from TB 11727 // mfspr Rz,TBU # load from TBU 11728 // cmpw crX,Rx,Rz # check if 'old'='new' 11729 // bne readLoop # branch if they're not equal 11730 // ... 11731 11732 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11733 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11734 DebugLoc dl = MI.getDebugLoc(); 11735 F->insert(It, readMBB); 11736 F->insert(It, sinkMBB); 11737 11738 // Transfer the remainder of BB and its successor edges to sinkMBB. 11739 sinkMBB->splice(sinkMBB->begin(), BB, 11740 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11741 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11742 11743 BB->addSuccessor(readMBB); 11744 BB = readMBB; 11745 11746 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11747 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11748 Register LoReg = MI.getOperand(0).getReg(); 11749 Register HiReg = MI.getOperand(1).getReg(); 11750 11751 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11752 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11753 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11754 11755 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11756 11757 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11758 .addReg(HiReg) 11759 .addReg(ReadAgainReg); 11760 BuildMI(BB, dl, TII->get(PPC::BCC)) 11761 .addImm(PPC::PRED_NE) 11762 .addReg(CmpReg) 11763 .addMBB(readMBB); 11764 11765 BB->addSuccessor(readMBB); 11766 BB->addSuccessor(sinkMBB); 11767 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11768 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11769 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11770 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11771 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11772 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11773 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11774 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11775 11776 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11777 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11778 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11779 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11780 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11781 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11782 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11783 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11784 11785 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11786 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11787 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11788 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11789 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11790 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11791 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11792 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11793 11794 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11795 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11796 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11797 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11798 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11799 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11800 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11801 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11802 11803 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11804 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11805 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11806 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11807 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11808 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11809 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11810 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11811 11812 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11813 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11814 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11815 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11816 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11817 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11818 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11819 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11820 11821 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11822 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11823 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11824 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11825 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11826 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11827 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11828 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11829 11830 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11831 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11832 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11833 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11834 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11835 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11836 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11837 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11838 11839 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11840 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11841 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11842 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11843 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11844 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11845 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11846 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11847 11848 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11849 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11850 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11851 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11852 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11853 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11854 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11855 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11856 11857 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11858 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11859 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11860 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11861 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11862 BB = EmitAtomicBinary(MI, BB, 4, 0); 11863 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11864 BB = EmitAtomicBinary(MI, BB, 8, 0); 11865 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11866 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11867 (Subtarget.hasPartwordAtomics() && 11868 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11869 (Subtarget.hasPartwordAtomics() && 11870 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11871 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11872 11873 auto LoadMnemonic = PPC::LDARX; 11874 auto StoreMnemonic = PPC::STDCX; 11875 switch (MI.getOpcode()) { 11876 default: 11877 llvm_unreachable("Compare and swap of unknown size"); 11878 case PPC::ATOMIC_CMP_SWAP_I8: 11879 LoadMnemonic = PPC::LBARX; 11880 StoreMnemonic = PPC::STBCX; 11881 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11882 break; 11883 case PPC::ATOMIC_CMP_SWAP_I16: 11884 LoadMnemonic = PPC::LHARX; 11885 StoreMnemonic = PPC::STHCX; 11886 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11887 break; 11888 case PPC::ATOMIC_CMP_SWAP_I32: 11889 LoadMnemonic = PPC::LWARX; 11890 StoreMnemonic = PPC::STWCX; 11891 break; 11892 case PPC::ATOMIC_CMP_SWAP_I64: 11893 LoadMnemonic = PPC::LDARX; 11894 StoreMnemonic = PPC::STDCX; 11895 break; 11896 } 11897 Register dest = MI.getOperand(0).getReg(); 11898 Register ptrA = MI.getOperand(1).getReg(); 11899 Register ptrB = MI.getOperand(2).getReg(); 11900 Register oldval = MI.getOperand(3).getReg(); 11901 Register newval = MI.getOperand(4).getReg(); 11902 DebugLoc dl = MI.getDebugLoc(); 11903 11904 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11905 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11906 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11907 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11908 F->insert(It, loop1MBB); 11909 F->insert(It, loop2MBB); 11910 F->insert(It, midMBB); 11911 F->insert(It, exitMBB); 11912 exitMBB->splice(exitMBB->begin(), BB, 11913 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11914 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11915 11916 // thisMBB: 11917 // ... 11918 // fallthrough --> loopMBB 11919 BB->addSuccessor(loop1MBB); 11920 11921 // loop1MBB: 11922 // l[bhwd]arx dest, ptr 11923 // cmp[wd] dest, oldval 11924 // bne- midMBB 11925 // loop2MBB: 11926 // st[bhwd]cx. newval, ptr 11927 // bne- loopMBB 11928 // b exitBB 11929 // midMBB: 11930 // st[bhwd]cx. dest, ptr 11931 // exitBB: 11932 BB = loop1MBB; 11933 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11934 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11935 .addReg(oldval) 11936 .addReg(dest); 11937 BuildMI(BB, dl, TII->get(PPC::BCC)) 11938 .addImm(PPC::PRED_NE) 11939 .addReg(PPC::CR0) 11940 .addMBB(midMBB); 11941 BB->addSuccessor(loop2MBB); 11942 BB->addSuccessor(midMBB); 11943 11944 BB = loop2MBB; 11945 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11946 .addReg(newval) 11947 .addReg(ptrA) 11948 .addReg(ptrB); 11949 BuildMI(BB, dl, TII->get(PPC::BCC)) 11950 .addImm(PPC::PRED_NE) 11951 .addReg(PPC::CR0) 11952 .addMBB(loop1MBB); 11953 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11954 BB->addSuccessor(loop1MBB); 11955 BB->addSuccessor(exitMBB); 11956 11957 BB = midMBB; 11958 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11959 .addReg(dest) 11960 .addReg(ptrA) 11961 .addReg(ptrB); 11962 BB->addSuccessor(exitMBB); 11963 11964 // exitMBB: 11965 // ... 11966 BB = exitMBB; 11967 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11968 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11969 // We must use 64-bit registers for addresses when targeting 64-bit, 11970 // since we're actually doing arithmetic on them. Other registers 11971 // can be 32-bit. 11972 bool is64bit = Subtarget.isPPC64(); 11973 bool isLittleEndian = Subtarget.isLittleEndian(); 11974 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11975 11976 Register dest = MI.getOperand(0).getReg(); 11977 Register ptrA = MI.getOperand(1).getReg(); 11978 Register ptrB = MI.getOperand(2).getReg(); 11979 Register oldval = MI.getOperand(3).getReg(); 11980 Register newval = MI.getOperand(4).getReg(); 11981 DebugLoc dl = MI.getDebugLoc(); 11982 11983 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11984 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11985 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11986 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11987 F->insert(It, loop1MBB); 11988 F->insert(It, loop2MBB); 11989 F->insert(It, midMBB); 11990 F->insert(It, exitMBB); 11991 exitMBB->splice(exitMBB->begin(), BB, 11992 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11993 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11994 11995 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11996 const TargetRegisterClass *RC = 11997 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11998 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11999 12000 Register PtrReg = RegInfo.createVirtualRegister(RC); 12001 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12002 Register ShiftReg = 12003 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12004 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12005 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12006 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12007 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12008 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12009 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12010 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12011 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12012 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12013 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12014 Register Ptr1Reg; 12015 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12016 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12017 // thisMBB: 12018 // ... 12019 // fallthrough --> loopMBB 12020 BB->addSuccessor(loop1MBB); 12021 12022 // The 4-byte load must be aligned, while a char or short may be 12023 // anywhere in the word. Hence all this nasty bookkeeping code. 12024 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12025 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12026 // xori shift, shift1, 24 [16] 12027 // rlwinm ptr, ptr1, 0, 0, 29 12028 // slw newval2, newval, shift 12029 // slw oldval2, oldval,shift 12030 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12031 // slw mask, mask2, shift 12032 // and newval3, newval2, mask 12033 // and oldval3, oldval2, mask 12034 // loop1MBB: 12035 // lwarx tmpDest, ptr 12036 // and tmp, tmpDest, mask 12037 // cmpw tmp, oldval3 12038 // bne- midMBB 12039 // loop2MBB: 12040 // andc tmp2, tmpDest, mask 12041 // or tmp4, tmp2, newval3 12042 // stwcx. tmp4, ptr 12043 // bne- loop1MBB 12044 // b exitBB 12045 // midMBB: 12046 // stwcx. tmpDest, ptr 12047 // exitBB: 12048 // srw dest, tmpDest, shift 12049 if (ptrA != ZeroReg) { 12050 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12051 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12052 .addReg(ptrA) 12053 .addReg(ptrB); 12054 } else { 12055 Ptr1Reg = ptrB; 12056 } 12057 12058 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12059 // mode. 12060 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12061 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12062 .addImm(3) 12063 .addImm(27) 12064 .addImm(is8bit ? 28 : 27); 12065 if (!isLittleEndian) 12066 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12067 .addReg(Shift1Reg) 12068 .addImm(is8bit ? 24 : 16); 12069 if (is64bit) 12070 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12071 .addReg(Ptr1Reg) 12072 .addImm(0) 12073 .addImm(61); 12074 else 12075 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12076 .addReg(Ptr1Reg) 12077 .addImm(0) 12078 .addImm(0) 12079 .addImm(29); 12080 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12081 .addReg(newval) 12082 .addReg(ShiftReg); 12083 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12084 .addReg(oldval) 12085 .addReg(ShiftReg); 12086 if (is8bit) 12087 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12088 else { 12089 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12090 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12091 .addReg(Mask3Reg) 12092 .addImm(65535); 12093 } 12094 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12095 .addReg(Mask2Reg) 12096 .addReg(ShiftReg); 12097 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12098 .addReg(NewVal2Reg) 12099 .addReg(MaskReg); 12100 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12101 .addReg(OldVal2Reg) 12102 .addReg(MaskReg); 12103 12104 BB = loop1MBB; 12105 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12106 .addReg(ZeroReg) 12107 .addReg(PtrReg); 12108 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12109 .addReg(TmpDestReg) 12110 .addReg(MaskReg); 12111 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 12112 .addReg(TmpReg) 12113 .addReg(OldVal3Reg); 12114 BuildMI(BB, dl, TII->get(PPC::BCC)) 12115 .addImm(PPC::PRED_NE) 12116 .addReg(PPC::CR0) 12117 .addMBB(midMBB); 12118 BB->addSuccessor(loop2MBB); 12119 BB->addSuccessor(midMBB); 12120 12121 BB = loop2MBB; 12122 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12123 .addReg(TmpDestReg) 12124 .addReg(MaskReg); 12125 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12126 .addReg(Tmp2Reg) 12127 .addReg(NewVal3Reg); 12128 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12129 .addReg(Tmp4Reg) 12130 .addReg(ZeroReg) 12131 .addReg(PtrReg); 12132 BuildMI(BB, dl, TII->get(PPC::BCC)) 12133 .addImm(PPC::PRED_NE) 12134 .addReg(PPC::CR0) 12135 .addMBB(loop1MBB); 12136 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12137 BB->addSuccessor(loop1MBB); 12138 BB->addSuccessor(exitMBB); 12139 12140 BB = midMBB; 12141 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12142 .addReg(TmpDestReg) 12143 .addReg(ZeroReg) 12144 .addReg(PtrReg); 12145 BB->addSuccessor(exitMBB); 12146 12147 // exitMBB: 12148 // ... 12149 BB = exitMBB; 12150 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12151 .addReg(TmpReg) 12152 .addReg(ShiftReg); 12153 } else if (MI.getOpcode() == PPC::FADDrtz) { 12154 // This pseudo performs an FADD with rounding mode temporarily forced 12155 // to round-to-zero. We emit this via custom inserter since the FPSCR 12156 // is not modeled at the SelectionDAG level. 12157 Register Dest = MI.getOperand(0).getReg(); 12158 Register Src1 = MI.getOperand(1).getReg(); 12159 Register Src2 = MI.getOperand(2).getReg(); 12160 DebugLoc dl = MI.getDebugLoc(); 12161 12162 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12163 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12164 12165 // Save FPSCR value. 12166 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12167 12168 // Set rounding mode to round-to-zero. 12169 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12170 .addImm(31) 12171 .addReg(PPC::RM, RegState::ImplicitDefine); 12172 12173 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12174 .addImm(30) 12175 .addReg(PPC::RM, RegState::ImplicitDefine); 12176 12177 // Perform addition. 12178 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12179 12180 // Restore FPSCR value. 12181 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12182 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12183 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12184 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12185 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12186 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12187 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12188 ? PPC::ANDI8_rec 12189 : PPC::ANDI_rec; 12190 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12191 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12192 12193 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12194 Register Dest = RegInfo.createVirtualRegister( 12195 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12196 12197 DebugLoc Dl = MI.getDebugLoc(); 12198 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12199 .addReg(MI.getOperand(1).getReg()) 12200 .addImm(1); 12201 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12202 MI.getOperand(0).getReg()) 12203 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12204 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12205 DebugLoc Dl = MI.getDebugLoc(); 12206 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12207 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12208 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12209 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12210 MI.getOperand(0).getReg()) 12211 .addReg(CRReg); 12212 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12213 DebugLoc Dl = MI.getDebugLoc(); 12214 unsigned Imm = MI.getOperand(1).getImm(); 12215 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12216 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12217 MI.getOperand(0).getReg()) 12218 .addReg(PPC::CR0EQ); 12219 } else if (MI.getOpcode() == PPC::SETRNDi) { 12220 DebugLoc dl = MI.getDebugLoc(); 12221 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12222 12223 // Save FPSCR value. 12224 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12225 12226 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12227 // the following settings: 12228 // 00 Round to nearest 12229 // 01 Round to 0 12230 // 10 Round to +inf 12231 // 11 Round to -inf 12232 12233 // When the operand is immediate, using the two least significant bits of 12234 // the immediate to set the bits 62:63 of FPSCR. 12235 unsigned Mode = MI.getOperand(1).getImm(); 12236 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12237 .addImm(31) 12238 .addReg(PPC::RM, RegState::ImplicitDefine); 12239 12240 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12241 .addImm(30) 12242 .addReg(PPC::RM, RegState::ImplicitDefine); 12243 } else if (MI.getOpcode() == PPC::SETRND) { 12244 DebugLoc dl = MI.getDebugLoc(); 12245 12246 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12247 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12248 // If the target doesn't have DirectMove, we should use stack to do the 12249 // conversion, because the target doesn't have the instructions like mtvsrd 12250 // or mfvsrd to do this conversion directly. 12251 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12252 if (Subtarget.hasDirectMove()) { 12253 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12254 .addReg(SrcReg); 12255 } else { 12256 // Use stack to do the register copy. 12257 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12258 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12259 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12260 if (RC == &PPC::F8RCRegClass) { 12261 // Copy register from F8RCRegClass to G8RCRegclass. 12262 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12263 "Unsupported RegClass."); 12264 12265 StoreOp = PPC::STFD; 12266 LoadOp = PPC::LD; 12267 } else { 12268 // Copy register from G8RCRegClass to F8RCRegclass. 12269 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12270 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12271 "Unsupported RegClass."); 12272 } 12273 12274 MachineFrameInfo &MFI = F->getFrameInfo(); 12275 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12276 12277 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12278 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12279 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12280 MFI.getObjectAlign(FrameIdx)); 12281 12282 // Store the SrcReg into the stack. 12283 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12284 .addReg(SrcReg) 12285 .addImm(0) 12286 .addFrameIndex(FrameIdx) 12287 .addMemOperand(MMOStore); 12288 12289 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12290 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12291 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12292 MFI.getObjectAlign(FrameIdx)); 12293 12294 // Load from the stack where SrcReg is stored, and save to DestReg, 12295 // so we have done the RegClass conversion from RegClass::SrcReg to 12296 // RegClass::DestReg. 12297 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12298 .addImm(0) 12299 .addFrameIndex(FrameIdx) 12300 .addMemOperand(MMOLoad); 12301 } 12302 }; 12303 12304 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12305 12306 // Save FPSCR value. 12307 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12308 12309 // When the operand is gprc register, use two least significant bits of the 12310 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12311 // 12312 // copy OldFPSCRTmpReg, OldFPSCRReg 12313 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12314 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12315 // copy NewFPSCRReg, NewFPSCRTmpReg 12316 // mtfsf 255, NewFPSCRReg 12317 MachineOperand SrcOp = MI.getOperand(1); 12318 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12319 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12320 12321 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12322 12323 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12324 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12325 12326 // The first operand of INSERT_SUBREG should be a register which has 12327 // subregisters, we only care about its RegClass, so we should use an 12328 // IMPLICIT_DEF register. 12329 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12330 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12331 .addReg(ImDefReg) 12332 .add(SrcOp) 12333 .addImm(1); 12334 12335 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12336 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12337 .addReg(OldFPSCRTmpReg) 12338 .addReg(ExtSrcReg) 12339 .addImm(0) 12340 .addImm(62); 12341 12342 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12343 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12344 12345 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12346 // bits of FPSCR. 12347 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12348 .addImm(255) 12349 .addReg(NewFPSCRReg) 12350 .addImm(0) 12351 .addImm(0); 12352 } else if (MI.getOpcode() == PPC::SETFLM) { 12353 DebugLoc Dl = MI.getDebugLoc(); 12354 12355 // Result of setflm is previous FPSCR content, so we need to save it first. 12356 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12357 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12358 12359 // Put bits in 32:63 to FPSCR. 12360 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12361 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12362 .addImm(255) 12363 .addReg(NewFPSCRReg) 12364 .addImm(0) 12365 .addImm(0); 12366 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12367 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12368 return emitProbedAlloca(MI, BB); 12369 } else { 12370 llvm_unreachable("Unexpected instr type to insert"); 12371 } 12372 12373 MI.eraseFromParent(); // The pseudo instruction is gone now. 12374 return BB; 12375 } 12376 12377 //===----------------------------------------------------------------------===// 12378 // Target Optimization Hooks 12379 //===----------------------------------------------------------------------===// 12380 12381 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12382 // For the estimates, convergence is quadratic, so we essentially double the 12383 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12384 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12385 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12386 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12387 if (VT.getScalarType() == MVT::f64) 12388 RefinementSteps++; 12389 return RefinementSteps; 12390 } 12391 12392 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12393 int Enabled, int &RefinementSteps, 12394 bool &UseOneConstNR, 12395 bool Reciprocal) const { 12396 EVT VT = Operand.getValueType(); 12397 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12398 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12399 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12400 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12401 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12402 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12403 12404 // The Newton-Raphson computation with a single constant does not provide 12405 // enough accuracy on some CPUs. 12406 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12407 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12408 } 12409 return SDValue(); 12410 } 12411 12412 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12413 int Enabled, 12414 int &RefinementSteps) const { 12415 EVT VT = Operand.getValueType(); 12416 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12417 (VT == MVT::f64 && Subtarget.hasFRE()) || 12418 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12419 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12420 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12421 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12422 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12423 } 12424 return SDValue(); 12425 } 12426 12427 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12428 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12429 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12430 // enabled for division), this functionality is redundant with the default 12431 // combiner logic (once the division -> reciprocal/multiply transformation 12432 // has taken place). As a result, this matters more for older cores than for 12433 // newer ones. 12434 12435 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12436 // reciprocal if there are two or more FDIVs (for embedded cores with only 12437 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12438 switch (Subtarget.getCPUDirective()) { 12439 default: 12440 return 3; 12441 case PPC::DIR_440: 12442 case PPC::DIR_A2: 12443 case PPC::DIR_E500: 12444 case PPC::DIR_E500mc: 12445 case PPC::DIR_E5500: 12446 return 2; 12447 } 12448 } 12449 12450 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12451 // collapsed, and so we need to look through chains of them. 12452 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12453 int64_t& Offset, SelectionDAG &DAG) { 12454 if (DAG.isBaseWithConstantOffset(Loc)) { 12455 Base = Loc.getOperand(0); 12456 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12457 12458 // The base might itself be a base plus an offset, and if so, accumulate 12459 // that as well. 12460 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12461 } 12462 } 12463 12464 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12465 unsigned Bytes, int Dist, 12466 SelectionDAG &DAG) { 12467 if (VT.getSizeInBits() / 8 != Bytes) 12468 return false; 12469 12470 SDValue BaseLoc = Base->getBasePtr(); 12471 if (Loc.getOpcode() == ISD::FrameIndex) { 12472 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12473 return false; 12474 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12475 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12476 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12477 int FS = MFI.getObjectSize(FI); 12478 int BFS = MFI.getObjectSize(BFI); 12479 if (FS != BFS || FS != (int)Bytes) return false; 12480 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12481 } 12482 12483 SDValue Base1 = Loc, Base2 = BaseLoc; 12484 int64_t Offset1 = 0, Offset2 = 0; 12485 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12486 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12487 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12488 return true; 12489 12490 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12491 const GlobalValue *GV1 = nullptr; 12492 const GlobalValue *GV2 = nullptr; 12493 Offset1 = 0; 12494 Offset2 = 0; 12495 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12496 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12497 if (isGA1 && isGA2 && GV1 == GV2) 12498 return Offset1 == (Offset2 + Dist*Bytes); 12499 return false; 12500 } 12501 12502 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12503 // not enforce equality of the chain operands. 12504 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12505 unsigned Bytes, int Dist, 12506 SelectionDAG &DAG) { 12507 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12508 EVT VT = LS->getMemoryVT(); 12509 SDValue Loc = LS->getBasePtr(); 12510 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12511 } 12512 12513 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12514 EVT VT; 12515 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12516 default: return false; 12517 case Intrinsic::ppc_altivec_lvx: 12518 case Intrinsic::ppc_altivec_lvxl: 12519 case Intrinsic::ppc_vsx_lxvw4x: 12520 case Intrinsic::ppc_vsx_lxvw4x_be: 12521 VT = MVT::v4i32; 12522 break; 12523 case Intrinsic::ppc_vsx_lxvd2x: 12524 case Intrinsic::ppc_vsx_lxvd2x_be: 12525 VT = MVT::v2f64; 12526 break; 12527 case Intrinsic::ppc_altivec_lvebx: 12528 VT = MVT::i8; 12529 break; 12530 case Intrinsic::ppc_altivec_lvehx: 12531 VT = MVT::i16; 12532 break; 12533 case Intrinsic::ppc_altivec_lvewx: 12534 VT = MVT::i32; 12535 break; 12536 } 12537 12538 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12539 } 12540 12541 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12542 EVT VT; 12543 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12544 default: return false; 12545 case Intrinsic::ppc_altivec_stvx: 12546 case Intrinsic::ppc_altivec_stvxl: 12547 case Intrinsic::ppc_vsx_stxvw4x: 12548 VT = MVT::v4i32; 12549 break; 12550 case Intrinsic::ppc_vsx_stxvd2x: 12551 VT = MVT::v2f64; 12552 break; 12553 case Intrinsic::ppc_vsx_stxvw4x_be: 12554 VT = MVT::v4i32; 12555 break; 12556 case Intrinsic::ppc_vsx_stxvd2x_be: 12557 VT = MVT::v2f64; 12558 break; 12559 case Intrinsic::ppc_altivec_stvebx: 12560 VT = MVT::i8; 12561 break; 12562 case Intrinsic::ppc_altivec_stvehx: 12563 VT = MVT::i16; 12564 break; 12565 case Intrinsic::ppc_altivec_stvewx: 12566 VT = MVT::i32; 12567 break; 12568 } 12569 12570 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12571 } 12572 12573 return false; 12574 } 12575 12576 // Return true is there is a nearyby consecutive load to the one provided 12577 // (regardless of alignment). We search up and down the chain, looking though 12578 // token factors and other loads (but nothing else). As a result, a true result 12579 // indicates that it is safe to create a new consecutive load adjacent to the 12580 // load provided. 12581 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12582 SDValue Chain = LD->getChain(); 12583 EVT VT = LD->getMemoryVT(); 12584 12585 SmallSet<SDNode *, 16> LoadRoots; 12586 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12587 SmallSet<SDNode *, 16> Visited; 12588 12589 // First, search up the chain, branching to follow all token-factor operands. 12590 // If we find a consecutive load, then we're done, otherwise, record all 12591 // nodes just above the top-level loads and token factors. 12592 while (!Queue.empty()) { 12593 SDNode *ChainNext = Queue.pop_back_val(); 12594 if (!Visited.insert(ChainNext).second) 12595 continue; 12596 12597 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12598 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12599 return true; 12600 12601 if (!Visited.count(ChainLD->getChain().getNode())) 12602 Queue.push_back(ChainLD->getChain().getNode()); 12603 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12604 for (const SDUse &O : ChainNext->ops()) 12605 if (!Visited.count(O.getNode())) 12606 Queue.push_back(O.getNode()); 12607 } else 12608 LoadRoots.insert(ChainNext); 12609 } 12610 12611 // Second, search down the chain, starting from the top-level nodes recorded 12612 // in the first phase. These top-level nodes are the nodes just above all 12613 // loads and token factors. Starting with their uses, recursively look though 12614 // all loads (just the chain uses) and token factors to find a consecutive 12615 // load. 12616 Visited.clear(); 12617 Queue.clear(); 12618 12619 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12620 IE = LoadRoots.end(); I != IE; ++I) { 12621 Queue.push_back(*I); 12622 12623 while (!Queue.empty()) { 12624 SDNode *LoadRoot = Queue.pop_back_val(); 12625 if (!Visited.insert(LoadRoot).second) 12626 continue; 12627 12628 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12629 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12630 return true; 12631 12632 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12633 UE = LoadRoot->use_end(); UI != UE; ++UI) 12634 if (((isa<MemSDNode>(*UI) && 12635 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12636 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12637 Queue.push_back(*UI); 12638 } 12639 } 12640 12641 return false; 12642 } 12643 12644 /// This function is called when we have proved that a SETCC node can be replaced 12645 /// by subtraction (and other supporting instructions) so that the result of 12646 /// comparison is kept in a GPR instead of CR. This function is purely for 12647 /// codegen purposes and has some flags to guide the codegen process. 12648 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12649 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12650 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12651 12652 // Zero extend the operands to the largest legal integer. Originally, they 12653 // must be of a strictly smaller size. 12654 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12655 DAG.getConstant(Size, DL, MVT::i32)); 12656 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12657 DAG.getConstant(Size, DL, MVT::i32)); 12658 12659 // Swap if needed. Depends on the condition code. 12660 if (Swap) 12661 std::swap(Op0, Op1); 12662 12663 // Subtract extended integers. 12664 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12665 12666 // Move the sign bit to the least significant position and zero out the rest. 12667 // Now the least significant bit carries the result of original comparison. 12668 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12669 DAG.getConstant(Size - 1, DL, MVT::i32)); 12670 auto Final = Shifted; 12671 12672 // Complement the result if needed. Based on the condition code. 12673 if (Complement) 12674 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12675 DAG.getConstant(1, DL, MVT::i64)); 12676 12677 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12678 } 12679 12680 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12681 DAGCombinerInfo &DCI) const { 12682 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12683 12684 SelectionDAG &DAG = DCI.DAG; 12685 SDLoc DL(N); 12686 12687 // Size of integers being compared has a critical role in the following 12688 // analysis, so we prefer to do this when all types are legal. 12689 if (!DCI.isAfterLegalizeDAG()) 12690 return SDValue(); 12691 12692 // If all users of SETCC extend its value to a legal integer type 12693 // then we replace SETCC with a subtraction 12694 for (SDNode::use_iterator UI = N->use_begin(), 12695 UE = N->use_end(); UI != UE; ++UI) { 12696 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12697 return SDValue(); 12698 } 12699 12700 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12701 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12702 12703 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12704 12705 if (OpSize < Size) { 12706 switch (CC) { 12707 default: break; 12708 case ISD::SETULT: 12709 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12710 case ISD::SETULE: 12711 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12712 case ISD::SETUGT: 12713 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12714 case ISD::SETUGE: 12715 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12716 } 12717 } 12718 12719 return SDValue(); 12720 } 12721 12722 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12723 DAGCombinerInfo &DCI) const { 12724 SelectionDAG &DAG = DCI.DAG; 12725 SDLoc dl(N); 12726 12727 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12728 // If we're tracking CR bits, we need to be careful that we don't have: 12729 // trunc(binary-ops(zext(x), zext(y))) 12730 // or 12731 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12732 // such that we're unnecessarily moving things into GPRs when it would be 12733 // better to keep them in CR bits. 12734 12735 // Note that trunc here can be an actual i1 trunc, or can be the effective 12736 // truncation that comes from a setcc or select_cc. 12737 if (N->getOpcode() == ISD::TRUNCATE && 12738 N->getValueType(0) != MVT::i1) 12739 return SDValue(); 12740 12741 if (N->getOperand(0).getValueType() != MVT::i32 && 12742 N->getOperand(0).getValueType() != MVT::i64) 12743 return SDValue(); 12744 12745 if (N->getOpcode() == ISD::SETCC || 12746 N->getOpcode() == ISD::SELECT_CC) { 12747 // If we're looking at a comparison, then we need to make sure that the 12748 // high bits (all except for the first) don't matter the result. 12749 ISD::CondCode CC = 12750 cast<CondCodeSDNode>(N->getOperand( 12751 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12752 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12753 12754 if (ISD::isSignedIntSetCC(CC)) { 12755 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12756 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12757 return SDValue(); 12758 } else if (ISD::isUnsignedIntSetCC(CC)) { 12759 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12760 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12761 !DAG.MaskedValueIsZero(N->getOperand(1), 12762 APInt::getHighBitsSet(OpBits, OpBits-1))) 12763 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12764 : SDValue()); 12765 } else { 12766 // This is neither a signed nor an unsigned comparison, just make sure 12767 // that the high bits are equal. 12768 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12769 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12770 12771 // We don't really care about what is known about the first bit (if 12772 // anything), so clear it in all masks prior to comparing them. 12773 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12774 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12775 12776 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12777 return SDValue(); 12778 } 12779 } 12780 12781 // We now know that the higher-order bits are irrelevant, we just need to 12782 // make sure that all of the intermediate operations are bit operations, and 12783 // all inputs are extensions. 12784 if (N->getOperand(0).getOpcode() != ISD::AND && 12785 N->getOperand(0).getOpcode() != ISD::OR && 12786 N->getOperand(0).getOpcode() != ISD::XOR && 12787 N->getOperand(0).getOpcode() != ISD::SELECT && 12788 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12789 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12790 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12791 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12792 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12793 return SDValue(); 12794 12795 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12796 N->getOperand(1).getOpcode() != ISD::AND && 12797 N->getOperand(1).getOpcode() != ISD::OR && 12798 N->getOperand(1).getOpcode() != ISD::XOR && 12799 N->getOperand(1).getOpcode() != ISD::SELECT && 12800 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12801 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12802 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12803 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12804 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12805 return SDValue(); 12806 12807 SmallVector<SDValue, 4> Inputs; 12808 SmallVector<SDValue, 8> BinOps, PromOps; 12809 SmallPtrSet<SDNode *, 16> Visited; 12810 12811 for (unsigned i = 0; i < 2; ++i) { 12812 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12813 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12814 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12815 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12816 isa<ConstantSDNode>(N->getOperand(i))) 12817 Inputs.push_back(N->getOperand(i)); 12818 else 12819 BinOps.push_back(N->getOperand(i)); 12820 12821 if (N->getOpcode() == ISD::TRUNCATE) 12822 break; 12823 } 12824 12825 // Visit all inputs, collect all binary operations (and, or, xor and 12826 // select) that are all fed by extensions. 12827 while (!BinOps.empty()) { 12828 SDValue BinOp = BinOps.back(); 12829 BinOps.pop_back(); 12830 12831 if (!Visited.insert(BinOp.getNode()).second) 12832 continue; 12833 12834 PromOps.push_back(BinOp); 12835 12836 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12837 // The condition of the select is not promoted. 12838 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12839 continue; 12840 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12841 continue; 12842 12843 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12844 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12845 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12846 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12847 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12848 Inputs.push_back(BinOp.getOperand(i)); 12849 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12850 BinOp.getOperand(i).getOpcode() == ISD::OR || 12851 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12852 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12853 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12854 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12855 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12856 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12857 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12858 BinOps.push_back(BinOp.getOperand(i)); 12859 } else { 12860 // We have an input that is not an extension or another binary 12861 // operation; we'll abort this transformation. 12862 return SDValue(); 12863 } 12864 } 12865 } 12866 12867 // Make sure that this is a self-contained cluster of operations (which 12868 // is not quite the same thing as saying that everything has only one 12869 // use). 12870 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12871 if (isa<ConstantSDNode>(Inputs[i])) 12872 continue; 12873 12874 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12875 UE = Inputs[i].getNode()->use_end(); 12876 UI != UE; ++UI) { 12877 SDNode *User = *UI; 12878 if (User != N && !Visited.count(User)) 12879 return SDValue(); 12880 12881 // Make sure that we're not going to promote the non-output-value 12882 // operand(s) or SELECT or SELECT_CC. 12883 // FIXME: Although we could sometimes handle this, and it does occur in 12884 // practice that one of the condition inputs to the select is also one of 12885 // the outputs, we currently can't deal with this. 12886 if (User->getOpcode() == ISD::SELECT) { 12887 if (User->getOperand(0) == Inputs[i]) 12888 return SDValue(); 12889 } else if (User->getOpcode() == ISD::SELECT_CC) { 12890 if (User->getOperand(0) == Inputs[i] || 12891 User->getOperand(1) == Inputs[i]) 12892 return SDValue(); 12893 } 12894 } 12895 } 12896 12897 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12898 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12899 UE = PromOps[i].getNode()->use_end(); 12900 UI != UE; ++UI) { 12901 SDNode *User = *UI; 12902 if (User != N && !Visited.count(User)) 12903 return SDValue(); 12904 12905 // Make sure that we're not going to promote the non-output-value 12906 // operand(s) or SELECT or SELECT_CC. 12907 // FIXME: Although we could sometimes handle this, and it does occur in 12908 // practice that one of the condition inputs to the select is also one of 12909 // the outputs, we currently can't deal with this. 12910 if (User->getOpcode() == ISD::SELECT) { 12911 if (User->getOperand(0) == PromOps[i]) 12912 return SDValue(); 12913 } else if (User->getOpcode() == ISD::SELECT_CC) { 12914 if (User->getOperand(0) == PromOps[i] || 12915 User->getOperand(1) == PromOps[i]) 12916 return SDValue(); 12917 } 12918 } 12919 } 12920 12921 // Replace all inputs with the extension operand. 12922 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12923 // Constants may have users outside the cluster of to-be-promoted nodes, 12924 // and so we need to replace those as we do the promotions. 12925 if (isa<ConstantSDNode>(Inputs[i])) 12926 continue; 12927 else 12928 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12929 } 12930 12931 std::list<HandleSDNode> PromOpHandles; 12932 for (auto &PromOp : PromOps) 12933 PromOpHandles.emplace_back(PromOp); 12934 12935 // Replace all operations (these are all the same, but have a different 12936 // (i1) return type). DAG.getNode will validate that the types of 12937 // a binary operator match, so go through the list in reverse so that 12938 // we've likely promoted both operands first. Any intermediate truncations or 12939 // extensions disappear. 12940 while (!PromOpHandles.empty()) { 12941 SDValue PromOp = PromOpHandles.back().getValue(); 12942 PromOpHandles.pop_back(); 12943 12944 if (PromOp.getOpcode() == ISD::TRUNCATE || 12945 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12946 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12947 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12948 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12949 PromOp.getOperand(0).getValueType() != MVT::i1) { 12950 // The operand is not yet ready (see comment below). 12951 PromOpHandles.emplace_front(PromOp); 12952 continue; 12953 } 12954 12955 SDValue RepValue = PromOp.getOperand(0); 12956 if (isa<ConstantSDNode>(RepValue)) 12957 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12958 12959 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12960 continue; 12961 } 12962 12963 unsigned C; 12964 switch (PromOp.getOpcode()) { 12965 default: C = 0; break; 12966 case ISD::SELECT: C = 1; break; 12967 case ISD::SELECT_CC: C = 2; break; 12968 } 12969 12970 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12971 PromOp.getOperand(C).getValueType() != MVT::i1) || 12972 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12973 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12974 // The to-be-promoted operands of this node have not yet been 12975 // promoted (this should be rare because we're going through the 12976 // list backward, but if one of the operands has several users in 12977 // this cluster of to-be-promoted nodes, it is possible). 12978 PromOpHandles.emplace_front(PromOp); 12979 continue; 12980 } 12981 12982 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12983 PromOp.getNode()->op_end()); 12984 12985 // If there are any constant inputs, make sure they're replaced now. 12986 for (unsigned i = 0; i < 2; ++i) 12987 if (isa<ConstantSDNode>(Ops[C+i])) 12988 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12989 12990 DAG.ReplaceAllUsesOfValueWith(PromOp, 12991 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12992 } 12993 12994 // Now we're left with the initial truncation itself. 12995 if (N->getOpcode() == ISD::TRUNCATE) 12996 return N->getOperand(0); 12997 12998 // Otherwise, this is a comparison. The operands to be compared have just 12999 // changed type (to i1), but everything else is the same. 13000 return SDValue(N, 0); 13001 } 13002 13003 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13004 DAGCombinerInfo &DCI) const { 13005 SelectionDAG &DAG = DCI.DAG; 13006 SDLoc dl(N); 13007 13008 // If we're tracking CR bits, we need to be careful that we don't have: 13009 // zext(binary-ops(trunc(x), trunc(y))) 13010 // or 13011 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13012 // such that we're unnecessarily moving things into CR bits that can more 13013 // efficiently stay in GPRs. Note that if we're not certain that the high 13014 // bits are set as required by the final extension, we still may need to do 13015 // some masking to get the proper behavior. 13016 13017 // This same functionality is important on PPC64 when dealing with 13018 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13019 // the return values of functions. Because it is so similar, it is handled 13020 // here as well. 13021 13022 if (N->getValueType(0) != MVT::i32 && 13023 N->getValueType(0) != MVT::i64) 13024 return SDValue(); 13025 13026 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13027 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13028 return SDValue(); 13029 13030 if (N->getOperand(0).getOpcode() != ISD::AND && 13031 N->getOperand(0).getOpcode() != ISD::OR && 13032 N->getOperand(0).getOpcode() != ISD::XOR && 13033 N->getOperand(0).getOpcode() != ISD::SELECT && 13034 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13035 return SDValue(); 13036 13037 SmallVector<SDValue, 4> Inputs; 13038 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13039 SmallPtrSet<SDNode *, 16> Visited; 13040 13041 // Visit all inputs, collect all binary operations (and, or, xor and 13042 // select) that are all fed by truncations. 13043 while (!BinOps.empty()) { 13044 SDValue BinOp = BinOps.back(); 13045 BinOps.pop_back(); 13046 13047 if (!Visited.insert(BinOp.getNode()).second) 13048 continue; 13049 13050 PromOps.push_back(BinOp); 13051 13052 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13053 // The condition of the select is not promoted. 13054 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13055 continue; 13056 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13057 continue; 13058 13059 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13060 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13061 Inputs.push_back(BinOp.getOperand(i)); 13062 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13063 BinOp.getOperand(i).getOpcode() == ISD::OR || 13064 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13065 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13066 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13067 BinOps.push_back(BinOp.getOperand(i)); 13068 } else { 13069 // We have an input that is not a truncation or another binary 13070 // operation; we'll abort this transformation. 13071 return SDValue(); 13072 } 13073 } 13074 } 13075 13076 // The operands of a select that must be truncated when the select is 13077 // promoted because the operand is actually part of the to-be-promoted set. 13078 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13079 13080 // Make sure that this is a self-contained cluster of operations (which 13081 // is not quite the same thing as saying that everything has only one 13082 // use). 13083 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13084 if (isa<ConstantSDNode>(Inputs[i])) 13085 continue; 13086 13087 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 13088 UE = Inputs[i].getNode()->use_end(); 13089 UI != UE; ++UI) { 13090 SDNode *User = *UI; 13091 if (User != N && !Visited.count(User)) 13092 return SDValue(); 13093 13094 // If we're going to promote the non-output-value operand(s) or SELECT or 13095 // SELECT_CC, record them for truncation. 13096 if (User->getOpcode() == ISD::SELECT) { 13097 if (User->getOperand(0) == Inputs[i]) 13098 SelectTruncOp[0].insert(std::make_pair(User, 13099 User->getOperand(0).getValueType())); 13100 } else if (User->getOpcode() == ISD::SELECT_CC) { 13101 if (User->getOperand(0) == Inputs[i]) 13102 SelectTruncOp[0].insert(std::make_pair(User, 13103 User->getOperand(0).getValueType())); 13104 if (User->getOperand(1) == Inputs[i]) 13105 SelectTruncOp[1].insert(std::make_pair(User, 13106 User->getOperand(1).getValueType())); 13107 } 13108 } 13109 } 13110 13111 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13112 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 13113 UE = PromOps[i].getNode()->use_end(); 13114 UI != UE; ++UI) { 13115 SDNode *User = *UI; 13116 if (User != N && !Visited.count(User)) 13117 return SDValue(); 13118 13119 // If we're going to promote the non-output-value operand(s) or SELECT or 13120 // SELECT_CC, record them for truncation. 13121 if (User->getOpcode() == ISD::SELECT) { 13122 if (User->getOperand(0) == PromOps[i]) 13123 SelectTruncOp[0].insert(std::make_pair(User, 13124 User->getOperand(0).getValueType())); 13125 } else if (User->getOpcode() == ISD::SELECT_CC) { 13126 if (User->getOperand(0) == PromOps[i]) 13127 SelectTruncOp[0].insert(std::make_pair(User, 13128 User->getOperand(0).getValueType())); 13129 if (User->getOperand(1) == PromOps[i]) 13130 SelectTruncOp[1].insert(std::make_pair(User, 13131 User->getOperand(1).getValueType())); 13132 } 13133 } 13134 } 13135 13136 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13137 bool ReallyNeedsExt = false; 13138 if (N->getOpcode() != ISD::ANY_EXTEND) { 13139 // If all of the inputs are not already sign/zero extended, then 13140 // we'll still need to do that at the end. 13141 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13142 if (isa<ConstantSDNode>(Inputs[i])) 13143 continue; 13144 13145 unsigned OpBits = 13146 Inputs[i].getOperand(0).getValueSizeInBits(); 13147 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13148 13149 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13150 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13151 APInt::getHighBitsSet(OpBits, 13152 OpBits-PromBits))) || 13153 (N->getOpcode() == ISD::SIGN_EXTEND && 13154 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13155 (OpBits-(PromBits-1)))) { 13156 ReallyNeedsExt = true; 13157 break; 13158 } 13159 } 13160 } 13161 13162 // Replace all inputs, either with the truncation operand, or a 13163 // truncation or extension to the final output type. 13164 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13165 // Constant inputs need to be replaced with the to-be-promoted nodes that 13166 // use them because they might have users outside of the cluster of 13167 // promoted nodes. 13168 if (isa<ConstantSDNode>(Inputs[i])) 13169 continue; 13170 13171 SDValue InSrc = Inputs[i].getOperand(0); 13172 if (Inputs[i].getValueType() == N->getValueType(0)) 13173 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13174 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13175 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13176 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13177 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13178 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13179 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13180 else 13181 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13182 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13183 } 13184 13185 std::list<HandleSDNode> PromOpHandles; 13186 for (auto &PromOp : PromOps) 13187 PromOpHandles.emplace_back(PromOp); 13188 13189 // Replace all operations (these are all the same, but have a different 13190 // (promoted) return type). DAG.getNode will validate that the types of 13191 // a binary operator match, so go through the list in reverse so that 13192 // we've likely promoted both operands first. 13193 while (!PromOpHandles.empty()) { 13194 SDValue PromOp = PromOpHandles.back().getValue(); 13195 PromOpHandles.pop_back(); 13196 13197 unsigned C; 13198 switch (PromOp.getOpcode()) { 13199 default: C = 0; break; 13200 case ISD::SELECT: C = 1; break; 13201 case ISD::SELECT_CC: C = 2; break; 13202 } 13203 13204 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13205 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13206 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13207 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13208 // The to-be-promoted operands of this node have not yet been 13209 // promoted (this should be rare because we're going through the 13210 // list backward, but if one of the operands has several users in 13211 // this cluster of to-be-promoted nodes, it is possible). 13212 PromOpHandles.emplace_front(PromOp); 13213 continue; 13214 } 13215 13216 // For SELECT and SELECT_CC nodes, we do a similar check for any 13217 // to-be-promoted comparison inputs. 13218 if (PromOp.getOpcode() == ISD::SELECT || 13219 PromOp.getOpcode() == ISD::SELECT_CC) { 13220 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13221 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13222 (SelectTruncOp[1].count(PromOp.getNode()) && 13223 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13224 PromOpHandles.emplace_front(PromOp); 13225 continue; 13226 } 13227 } 13228 13229 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13230 PromOp.getNode()->op_end()); 13231 13232 // If this node has constant inputs, then they'll need to be promoted here. 13233 for (unsigned i = 0; i < 2; ++i) { 13234 if (!isa<ConstantSDNode>(Ops[C+i])) 13235 continue; 13236 if (Ops[C+i].getValueType() == N->getValueType(0)) 13237 continue; 13238 13239 if (N->getOpcode() == ISD::SIGN_EXTEND) 13240 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13241 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13242 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13243 else 13244 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13245 } 13246 13247 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13248 // truncate them again to the original value type. 13249 if (PromOp.getOpcode() == ISD::SELECT || 13250 PromOp.getOpcode() == ISD::SELECT_CC) { 13251 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13252 if (SI0 != SelectTruncOp[0].end()) 13253 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13254 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13255 if (SI1 != SelectTruncOp[1].end()) 13256 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13257 } 13258 13259 DAG.ReplaceAllUsesOfValueWith(PromOp, 13260 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13261 } 13262 13263 // Now we're left with the initial extension itself. 13264 if (!ReallyNeedsExt) 13265 return N->getOperand(0); 13266 13267 // To zero extend, just mask off everything except for the first bit (in the 13268 // i1 case). 13269 if (N->getOpcode() == ISD::ZERO_EXTEND) 13270 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13271 DAG.getConstant(APInt::getLowBitsSet( 13272 N->getValueSizeInBits(0), PromBits), 13273 dl, N->getValueType(0))); 13274 13275 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13276 "Invalid extension type"); 13277 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13278 SDValue ShiftCst = 13279 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13280 return DAG.getNode( 13281 ISD::SRA, dl, N->getValueType(0), 13282 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13283 ShiftCst); 13284 } 13285 13286 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13287 DAGCombinerInfo &DCI) const { 13288 assert(N->getOpcode() == ISD::SETCC && 13289 "Should be called with a SETCC node"); 13290 13291 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13292 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13293 SDValue LHS = N->getOperand(0); 13294 SDValue RHS = N->getOperand(1); 13295 13296 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13297 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13298 LHS.hasOneUse()) 13299 std::swap(LHS, RHS); 13300 13301 // x == 0-y --> x+y == 0 13302 // x != 0-y --> x+y != 0 13303 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13304 RHS.hasOneUse()) { 13305 SDLoc DL(N); 13306 SelectionDAG &DAG = DCI.DAG; 13307 EVT VT = N->getValueType(0); 13308 EVT OpVT = LHS.getValueType(); 13309 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13310 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13311 } 13312 } 13313 13314 return DAGCombineTruncBoolExt(N, DCI); 13315 } 13316 13317 // Is this an extending load from an f32 to an f64? 13318 static bool isFPExtLoad(SDValue Op) { 13319 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13320 return LD->getExtensionType() == ISD::EXTLOAD && 13321 Op.getValueType() == MVT::f64; 13322 return false; 13323 } 13324 13325 /// Reduces the number of fp-to-int conversion when building a vector. 13326 /// 13327 /// If this vector is built out of floating to integer conversions, 13328 /// transform it to a vector built out of floating point values followed by a 13329 /// single floating to integer conversion of the vector. 13330 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13331 /// becomes (fptosi (build_vector ($A, $B, ...))) 13332 SDValue PPCTargetLowering:: 13333 combineElementTruncationToVectorTruncation(SDNode *N, 13334 DAGCombinerInfo &DCI) const { 13335 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13336 "Should be called with a BUILD_VECTOR node"); 13337 13338 SelectionDAG &DAG = DCI.DAG; 13339 SDLoc dl(N); 13340 13341 SDValue FirstInput = N->getOperand(0); 13342 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13343 "The input operand must be an fp-to-int conversion."); 13344 13345 // This combine happens after legalization so the fp_to_[su]i nodes are 13346 // already converted to PPCSISD nodes. 13347 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13348 if (FirstConversion == PPCISD::FCTIDZ || 13349 FirstConversion == PPCISD::FCTIDUZ || 13350 FirstConversion == PPCISD::FCTIWZ || 13351 FirstConversion == PPCISD::FCTIWUZ) { 13352 bool IsSplat = true; 13353 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13354 FirstConversion == PPCISD::FCTIWUZ; 13355 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13356 SmallVector<SDValue, 4> Ops; 13357 EVT TargetVT = N->getValueType(0); 13358 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13359 SDValue NextOp = N->getOperand(i); 13360 if (NextOp.getOpcode() != PPCISD::MFVSR) 13361 return SDValue(); 13362 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13363 if (NextConversion != FirstConversion) 13364 return SDValue(); 13365 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13366 // This is not valid if the input was originally double precision. It is 13367 // also not profitable to do unless this is an extending load in which 13368 // case doing this combine will allow us to combine consecutive loads. 13369 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13370 return SDValue(); 13371 if (N->getOperand(i) != FirstInput) 13372 IsSplat = false; 13373 } 13374 13375 // If this is a splat, we leave it as-is since there will be only a single 13376 // fp-to-int conversion followed by a splat of the integer. This is better 13377 // for 32-bit and smaller ints and neutral for 64-bit ints. 13378 if (IsSplat) 13379 return SDValue(); 13380 13381 // Now that we know we have the right type of node, get its operands 13382 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13383 SDValue In = N->getOperand(i).getOperand(0); 13384 if (Is32Bit) { 13385 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13386 // here, we know that all inputs are extending loads so this is safe). 13387 if (In.isUndef()) 13388 Ops.push_back(DAG.getUNDEF(SrcVT)); 13389 else { 13390 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13391 MVT::f32, In.getOperand(0), 13392 DAG.getIntPtrConstant(1, dl)); 13393 Ops.push_back(Trunc); 13394 } 13395 } else 13396 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13397 } 13398 13399 unsigned Opcode; 13400 if (FirstConversion == PPCISD::FCTIDZ || 13401 FirstConversion == PPCISD::FCTIWZ) 13402 Opcode = ISD::FP_TO_SINT; 13403 else 13404 Opcode = ISD::FP_TO_UINT; 13405 13406 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13407 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13408 return DAG.getNode(Opcode, dl, TargetVT, BV); 13409 } 13410 return SDValue(); 13411 } 13412 13413 /// Reduce the number of loads when building a vector. 13414 /// 13415 /// Building a vector out of multiple loads can be converted to a load 13416 /// of the vector type if the loads are consecutive. If the loads are 13417 /// consecutive but in descending order, a shuffle is added at the end 13418 /// to reorder the vector. 13419 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13420 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13421 "Should be called with a BUILD_VECTOR node"); 13422 13423 SDLoc dl(N); 13424 13425 // Return early for non byte-sized type, as they can't be consecutive. 13426 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13427 return SDValue(); 13428 13429 bool InputsAreConsecutiveLoads = true; 13430 bool InputsAreReverseConsecutive = true; 13431 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13432 SDValue FirstInput = N->getOperand(0); 13433 bool IsRoundOfExtLoad = false; 13434 13435 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13436 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13437 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13438 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13439 } 13440 // Not a build vector of (possibly fp_rounded) loads. 13441 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13442 N->getNumOperands() == 1) 13443 return SDValue(); 13444 13445 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13446 // If any inputs are fp_round(extload), they all must be. 13447 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13448 return SDValue(); 13449 13450 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13451 N->getOperand(i); 13452 if (NextInput.getOpcode() != ISD::LOAD) 13453 return SDValue(); 13454 13455 SDValue PreviousInput = 13456 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13457 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13458 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13459 13460 // If any inputs are fp_round(extload), they all must be. 13461 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13462 return SDValue(); 13463 13464 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13465 InputsAreConsecutiveLoads = false; 13466 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13467 InputsAreReverseConsecutive = false; 13468 13469 // Exit early if the loads are neither consecutive nor reverse consecutive. 13470 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13471 return SDValue(); 13472 } 13473 13474 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13475 "The loads cannot be both consecutive and reverse consecutive."); 13476 13477 SDValue FirstLoadOp = 13478 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13479 SDValue LastLoadOp = 13480 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13481 N->getOperand(N->getNumOperands()-1); 13482 13483 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13484 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13485 if (InputsAreConsecutiveLoads) { 13486 assert(LD1 && "Input needs to be a LoadSDNode."); 13487 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13488 LD1->getBasePtr(), LD1->getPointerInfo(), 13489 LD1->getAlignment()); 13490 } 13491 if (InputsAreReverseConsecutive) { 13492 assert(LDL && "Input needs to be a LoadSDNode."); 13493 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13494 LDL->getBasePtr(), LDL->getPointerInfo(), 13495 LDL->getAlignment()); 13496 SmallVector<int, 16> Ops; 13497 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13498 Ops.push_back(i); 13499 13500 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13501 DAG.getUNDEF(N->getValueType(0)), Ops); 13502 } 13503 return SDValue(); 13504 } 13505 13506 // This function adds the required vector_shuffle needed to get 13507 // the elements of the vector extract in the correct position 13508 // as specified by the CorrectElems encoding. 13509 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13510 SDValue Input, uint64_t Elems, 13511 uint64_t CorrectElems) { 13512 SDLoc dl(N); 13513 13514 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13515 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13516 13517 // Knowing the element indices being extracted from the original 13518 // vector and the order in which they're being inserted, just put 13519 // them at element indices required for the instruction. 13520 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13521 if (DAG.getDataLayout().isLittleEndian()) 13522 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13523 else 13524 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13525 CorrectElems = CorrectElems >> 8; 13526 Elems = Elems >> 8; 13527 } 13528 13529 SDValue Shuffle = 13530 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13531 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13532 13533 EVT VT = N->getValueType(0); 13534 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13535 13536 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13537 Input.getValueType().getVectorElementType(), 13538 VT.getVectorNumElements()); 13539 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13540 DAG.getValueType(ExtVT)); 13541 } 13542 13543 // Look for build vector patterns where input operands come from sign 13544 // extended vector_extract elements of specific indices. If the correct indices 13545 // aren't used, add a vector shuffle to fix up the indices and create 13546 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13547 // during instruction selection. 13548 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13549 // This array encodes the indices that the vector sign extend instructions 13550 // extract from when extending from one type to another for both BE and LE. 13551 // The right nibble of each byte corresponds to the LE incides. 13552 // and the left nibble of each byte corresponds to the BE incides. 13553 // For example: 0x3074B8FC byte->word 13554 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13555 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13556 // For example: 0x000070F8 byte->double word 13557 // For LE: the allowed indices are: 0x0,0x8 13558 // For BE: the allowed indices are: 0x7,0xF 13559 uint64_t TargetElems[] = { 13560 0x3074B8FC, // b->w 13561 0x000070F8, // b->d 13562 0x10325476, // h->w 13563 0x00003074, // h->d 13564 0x00001032, // w->d 13565 }; 13566 13567 uint64_t Elems = 0; 13568 int Index; 13569 SDValue Input; 13570 13571 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13572 if (!Op) 13573 return false; 13574 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13575 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13576 return false; 13577 13578 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13579 // of the right width. 13580 SDValue Extract = Op.getOperand(0); 13581 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13582 Extract = Extract.getOperand(0); 13583 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13584 return false; 13585 13586 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13587 if (!ExtOp) 13588 return false; 13589 13590 Index = ExtOp->getZExtValue(); 13591 if (Input && Input != Extract.getOperand(0)) 13592 return false; 13593 13594 if (!Input) 13595 Input = Extract.getOperand(0); 13596 13597 Elems = Elems << 8; 13598 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13599 Elems |= Index; 13600 13601 return true; 13602 }; 13603 13604 // If the build vector operands aren't sign extended vector extracts, 13605 // of the same input vector, then return. 13606 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13607 if (!isSExtOfVecExtract(N->getOperand(i))) { 13608 return SDValue(); 13609 } 13610 } 13611 13612 // If the vector extract indicies are not correct, add the appropriate 13613 // vector_shuffle. 13614 int TgtElemArrayIdx; 13615 int InputSize = Input.getValueType().getScalarSizeInBits(); 13616 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13617 if (InputSize + OutputSize == 40) 13618 TgtElemArrayIdx = 0; 13619 else if (InputSize + OutputSize == 72) 13620 TgtElemArrayIdx = 1; 13621 else if (InputSize + OutputSize == 48) 13622 TgtElemArrayIdx = 2; 13623 else if (InputSize + OutputSize == 80) 13624 TgtElemArrayIdx = 3; 13625 else if (InputSize + OutputSize == 96) 13626 TgtElemArrayIdx = 4; 13627 else 13628 return SDValue(); 13629 13630 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13631 CorrectElems = DAG.getDataLayout().isLittleEndian() 13632 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13633 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13634 if (Elems != CorrectElems) { 13635 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13636 } 13637 13638 // Regular lowering will catch cases where a shuffle is not needed. 13639 return SDValue(); 13640 } 13641 13642 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13643 DAGCombinerInfo &DCI) const { 13644 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13645 "Should be called with a BUILD_VECTOR node"); 13646 13647 SelectionDAG &DAG = DCI.DAG; 13648 SDLoc dl(N); 13649 13650 if (!Subtarget.hasVSX()) 13651 return SDValue(); 13652 13653 // The target independent DAG combiner will leave a build_vector of 13654 // float-to-int conversions intact. We can generate MUCH better code for 13655 // a float-to-int conversion of a vector of floats. 13656 SDValue FirstInput = N->getOperand(0); 13657 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13658 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13659 if (Reduced) 13660 return Reduced; 13661 } 13662 13663 // If we're building a vector out of consecutive loads, just load that 13664 // vector type. 13665 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13666 if (Reduced) 13667 return Reduced; 13668 13669 // If we're building a vector out of extended elements from another vector 13670 // we have P9 vector integer extend instructions. The code assumes legal 13671 // input types (i.e. it can't handle things like v4i16) so do not run before 13672 // legalization. 13673 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13674 Reduced = combineBVOfVecSExt(N, DAG); 13675 if (Reduced) 13676 return Reduced; 13677 } 13678 13679 13680 if (N->getValueType(0) != MVT::v2f64) 13681 return SDValue(); 13682 13683 // Looking for: 13684 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13685 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13686 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13687 return SDValue(); 13688 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13689 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13690 return SDValue(); 13691 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13692 return SDValue(); 13693 13694 SDValue Ext1 = FirstInput.getOperand(0); 13695 SDValue Ext2 = N->getOperand(1).getOperand(0); 13696 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13697 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13698 return SDValue(); 13699 13700 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13701 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13702 if (!Ext1Op || !Ext2Op) 13703 return SDValue(); 13704 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13705 Ext1.getOperand(0) != Ext2.getOperand(0)) 13706 return SDValue(); 13707 13708 int FirstElem = Ext1Op->getZExtValue(); 13709 int SecondElem = Ext2Op->getZExtValue(); 13710 int SubvecIdx; 13711 if (FirstElem == 0 && SecondElem == 1) 13712 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13713 else if (FirstElem == 2 && SecondElem == 3) 13714 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13715 else 13716 return SDValue(); 13717 13718 SDValue SrcVec = Ext1.getOperand(0); 13719 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13720 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13721 return DAG.getNode(NodeType, dl, MVT::v2f64, 13722 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13723 } 13724 13725 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13726 DAGCombinerInfo &DCI) const { 13727 assert((N->getOpcode() == ISD::SINT_TO_FP || 13728 N->getOpcode() == ISD::UINT_TO_FP) && 13729 "Need an int -> FP conversion node here"); 13730 13731 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13732 return SDValue(); 13733 13734 SelectionDAG &DAG = DCI.DAG; 13735 SDLoc dl(N); 13736 SDValue Op(N, 0); 13737 13738 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13739 // from the hardware. 13740 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13741 return SDValue(); 13742 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13743 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13744 return SDValue(); 13745 13746 SDValue FirstOperand(Op.getOperand(0)); 13747 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13748 (FirstOperand.getValueType() == MVT::i8 || 13749 FirstOperand.getValueType() == MVT::i16); 13750 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13751 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13752 bool DstDouble = Op.getValueType() == MVT::f64; 13753 unsigned ConvOp = Signed ? 13754 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13755 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13756 SDValue WidthConst = 13757 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13758 dl, false); 13759 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13760 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13761 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13762 DAG.getVTList(MVT::f64, MVT::Other), 13763 Ops, MVT::i8, LDN->getMemOperand()); 13764 13765 // For signed conversion, we need to sign-extend the value in the VSR 13766 if (Signed) { 13767 SDValue ExtOps[] = { Ld, WidthConst }; 13768 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13769 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13770 } else 13771 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13772 } 13773 13774 13775 // For i32 intermediate values, unfortunately, the conversion functions 13776 // leave the upper 32 bits of the value are undefined. Within the set of 13777 // scalar instructions, we have no method for zero- or sign-extending the 13778 // value. Thus, we cannot handle i32 intermediate values here. 13779 if (Op.getOperand(0).getValueType() == MVT::i32) 13780 return SDValue(); 13781 13782 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13783 "UINT_TO_FP is supported only with FPCVT"); 13784 13785 // If we have FCFIDS, then use it when converting to single-precision. 13786 // Otherwise, convert to double-precision and then round. 13787 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13788 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13789 : PPCISD::FCFIDS) 13790 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13791 : PPCISD::FCFID); 13792 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13793 ? MVT::f32 13794 : MVT::f64; 13795 13796 // If we're converting from a float, to an int, and back to a float again, 13797 // then we don't need the store/load pair at all. 13798 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13799 Subtarget.hasFPCVT()) || 13800 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13801 SDValue Src = Op.getOperand(0).getOperand(0); 13802 if (Src.getValueType() == MVT::f32) { 13803 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13804 DCI.AddToWorklist(Src.getNode()); 13805 } else if (Src.getValueType() != MVT::f64) { 13806 // Make sure that we don't pick up a ppc_fp128 source value. 13807 return SDValue(); 13808 } 13809 13810 unsigned FCTOp = 13811 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13812 PPCISD::FCTIDUZ; 13813 13814 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13815 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13816 13817 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13818 FP = DAG.getNode(ISD::FP_ROUND, dl, 13819 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13820 DCI.AddToWorklist(FP.getNode()); 13821 } 13822 13823 return FP; 13824 } 13825 13826 return SDValue(); 13827 } 13828 13829 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13830 // builtins) into loads with swaps. 13831 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13832 DAGCombinerInfo &DCI) const { 13833 SelectionDAG &DAG = DCI.DAG; 13834 SDLoc dl(N); 13835 SDValue Chain; 13836 SDValue Base; 13837 MachineMemOperand *MMO; 13838 13839 switch (N->getOpcode()) { 13840 default: 13841 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13842 case ISD::LOAD: { 13843 LoadSDNode *LD = cast<LoadSDNode>(N); 13844 Chain = LD->getChain(); 13845 Base = LD->getBasePtr(); 13846 MMO = LD->getMemOperand(); 13847 // If the MMO suggests this isn't a load of a full vector, leave 13848 // things alone. For a built-in, we have to make the change for 13849 // correctness, so if there is a size problem that will be a bug. 13850 if (MMO->getSize() < 16) 13851 return SDValue(); 13852 break; 13853 } 13854 case ISD::INTRINSIC_W_CHAIN: { 13855 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13856 Chain = Intrin->getChain(); 13857 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13858 // us what we want. Get operand 2 instead. 13859 Base = Intrin->getOperand(2); 13860 MMO = Intrin->getMemOperand(); 13861 break; 13862 } 13863 } 13864 13865 MVT VecTy = N->getValueType(0).getSimpleVT(); 13866 13867 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13868 // aligned and the type is a vector with elements up to 4 bytes 13869 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13870 VecTy.getScalarSizeInBits() <= 32) { 13871 return SDValue(); 13872 } 13873 13874 SDValue LoadOps[] = { Chain, Base }; 13875 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13876 DAG.getVTList(MVT::v2f64, MVT::Other), 13877 LoadOps, MVT::v2f64, MMO); 13878 13879 DCI.AddToWorklist(Load.getNode()); 13880 Chain = Load.getValue(1); 13881 SDValue Swap = DAG.getNode( 13882 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13883 DCI.AddToWorklist(Swap.getNode()); 13884 13885 // Add a bitcast if the resulting load type doesn't match v2f64. 13886 if (VecTy != MVT::v2f64) { 13887 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13888 DCI.AddToWorklist(N.getNode()); 13889 // Package {bitcast value, swap's chain} to match Load's shape. 13890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13891 N, Swap.getValue(1)); 13892 } 13893 13894 return Swap; 13895 } 13896 13897 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13898 // builtins) into stores with swaps. 13899 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13900 DAGCombinerInfo &DCI) const { 13901 SelectionDAG &DAG = DCI.DAG; 13902 SDLoc dl(N); 13903 SDValue Chain; 13904 SDValue Base; 13905 unsigned SrcOpnd; 13906 MachineMemOperand *MMO; 13907 13908 switch (N->getOpcode()) { 13909 default: 13910 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13911 case ISD::STORE: { 13912 StoreSDNode *ST = cast<StoreSDNode>(N); 13913 Chain = ST->getChain(); 13914 Base = ST->getBasePtr(); 13915 MMO = ST->getMemOperand(); 13916 SrcOpnd = 1; 13917 // If the MMO suggests this isn't a store of a full vector, leave 13918 // things alone. For a built-in, we have to make the change for 13919 // correctness, so if there is a size problem that will be a bug. 13920 if (MMO->getSize() < 16) 13921 return SDValue(); 13922 break; 13923 } 13924 case ISD::INTRINSIC_VOID: { 13925 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13926 Chain = Intrin->getChain(); 13927 // Intrin->getBasePtr() oddly does not get what we want. 13928 Base = Intrin->getOperand(3); 13929 MMO = Intrin->getMemOperand(); 13930 SrcOpnd = 2; 13931 break; 13932 } 13933 } 13934 13935 SDValue Src = N->getOperand(SrcOpnd); 13936 MVT VecTy = Src.getValueType().getSimpleVT(); 13937 13938 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13939 // aligned and the type is a vector with elements up to 4 bytes 13940 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13941 VecTy.getScalarSizeInBits() <= 32) { 13942 return SDValue(); 13943 } 13944 13945 // All stores are done as v2f64 and possible bit cast. 13946 if (VecTy != MVT::v2f64) { 13947 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13948 DCI.AddToWorklist(Src.getNode()); 13949 } 13950 13951 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13952 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13953 DCI.AddToWorklist(Swap.getNode()); 13954 Chain = Swap.getValue(1); 13955 SDValue StoreOps[] = { Chain, Swap, Base }; 13956 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13957 DAG.getVTList(MVT::Other), 13958 StoreOps, VecTy, MMO); 13959 DCI.AddToWorklist(Store.getNode()); 13960 return Store; 13961 } 13962 13963 // Handle DAG combine for STORE (FP_TO_INT F). 13964 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13965 DAGCombinerInfo &DCI) const { 13966 13967 SelectionDAG &DAG = DCI.DAG; 13968 SDLoc dl(N); 13969 unsigned Opcode = N->getOperand(1).getOpcode(); 13970 13971 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13972 && "Not a FP_TO_INT Instruction!"); 13973 13974 SDValue Val = N->getOperand(1).getOperand(0); 13975 EVT Op1VT = N->getOperand(1).getValueType(); 13976 EVT ResVT = Val.getValueType(); 13977 13978 // Floating point types smaller than 32 bits are not legal on Power. 13979 if (ResVT.getScalarSizeInBits() < 32) 13980 return SDValue(); 13981 13982 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13983 bool ValidTypeForStoreFltAsInt = 13984 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13985 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13986 13987 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13988 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13989 return SDValue(); 13990 13991 // Extend f32 values to f64 13992 if (ResVT.getScalarSizeInBits() == 32) { 13993 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13994 DCI.AddToWorklist(Val.getNode()); 13995 } 13996 13997 // Set signed or unsigned conversion opcode. 13998 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13999 PPCISD::FP_TO_SINT_IN_VSR : 14000 PPCISD::FP_TO_UINT_IN_VSR; 14001 14002 Val = DAG.getNode(ConvOpcode, 14003 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14004 DCI.AddToWorklist(Val.getNode()); 14005 14006 // Set number of bytes being converted. 14007 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14008 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14009 DAG.getIntPtrConstant(ByteSize, dl, false), 14010 DAG.getValueType(Op1VT) }; 14011 14012 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14013 DAG.getVTList(MVT::Other), Ops, 14014 cast<StoreSDNode>(N)->getMemoryVT(), 14015 cast<StoreSDNode>(N)->getMemOperand()); 14016 14017 DCI.AddToWorklist(Val.getNode()); 14018 return Val; 14019 } 14020 14021 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14022 // Check that the source of the element keeps flipping 14023 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14024 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14025 for (int i = 1, e = Mask.size(); i < e; i++) { 14026 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14027 return false; 14028 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14029 return false; 14030 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14031 } 14032 return true; 14033 } 14034 14035 static bool isSplatBV(SDValue Op) { 14036 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14037 return false; 14038 SDValue FirstOp; 14039 14040 // Find first non-undef input. 14041 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14042 FirstOp = Op.getOperand(i); 14043 if (!FirstOp.isUndef()) 14044 break; 14045 } 14046 14047 // All inputs are undef or the same as the first non-undef input. 14048 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14049 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14050 return false; 14051 return true; 14052 } 14053 14054 static SDValue isScalarToVec(SDValue Op) { 14055 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14056 return Op; 14057 if (Op.getOpcode() != ISD::BITCAST) 14058 return SDValue(); 14059 Op = Op.getOperand(0); 14060 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14061 return Op; 14062 return SDValue(); 14063 } 14064 14065 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14066 int LHSMaxIdx, int RHSMinIdx, 14067 int RHSMaxIdx, int HalfVec) { 14068 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14069 int Idx = ShuffV[i]; 14070 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14071 ShuffV[i] += HalfVec; 14072 } 14073 return; 14074 } 14075 14076 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14077 // the original is: 14078 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14079 // In such a case, just change the shuffle mask to extract the element 14080 // from the permuted index. 14081 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 14082 SDLoc dl(OrigSToV); 14083 EVT VT = OrigSToV.getValueType(); 14084 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14085 "Expecting a SCALAR_TO_VECTOR here"); 14086 SDValue Input = OrigSToV.getOperand(0); 14087 14088 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14089 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14090 SDValue OrigVector = Input.getOperand(0); 14091 14092 // Can't handle non-const element indices or different vector types 14093 // for the input to the extract and the output of the scalar_to_vector. 14094 if (Idx && VT == OrigVector.getValueType()) { 14095 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 14096 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 14097 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14098 } 14099 } 14100 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14101 OrigSToV.getOperand(0)); 14102 } 14103 14104 // On little endian subtargets, combine shuffles such as: 14105 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 14106 // into: 14107 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 14108 // because the latter can be matched to a single instruction merge. 14109 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 14110 // to put the value into element zero. Adjust the shuffle mask so that the 14111 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 14112 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 14113 SelectionDAG &DAG) const { 14114 SDValue LHS = SVN->getOperand(0); 14115 SDValue RHS = SVN->getOperand(1); 14116 auto Mask = SVN->getMask(); 14117 int NumElts = LHS.getValueType().getVectorNumElements(); 14118 SDValue Res(SVN, 0); 14119 SDLoc dl(SVN); 14120 14121 // None of these combines are useful on big endian systems since the ISA 14122 // already has a big endian bias. 14123 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14124 return Res; 14125 14126 // If this is not a shuffle of a shuffle and the first element comes from 14127 // the second vector, canonicalize to the commuted form. This will make it 14128 // more likely to match one of the single instruction patterns. 14129 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14130 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 14131 std::swap(LHS, RHS); 14132 Res = DAG.getCommutedVectorShuffle(*SVN); 14133 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14134 } 14135 14136 // Adjust the shuffle mask if either input vector comes from a 14137 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 14138 // form (to prevent the need for a swap). 14139 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 14140 SDValue SToVLHS = isScalarToVec(LHS); 14141 SDValue SToVRHS = isScalarToVec(RHS); 14142 if (SToVLHS || SToVRHS) { 14143 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 14144 : SToVRHS.getValueType().getVectorNumElements(); 14145 int NumEltsOut = ShuffV.size(); 14146 14147 // Initially assume that neither input is permuted. These will be adjusted 14148 // accordingly if either input is. 14149 int LHSMaxIdx = -1; 14150 int RHSMinIdx = -1; 14151 int RHSMaxIdx = -1; 14152 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 14153 14154 // Get the permuted scalar to vector nodes for the source(s) that come from 14155 // ISD::SCALAR_TO_VECTOR. 14156 if (SToVLHS) { 14157 // Set up the values for the shuffle vector fixup. 14158 LHSMaxIdx = NumEltsOut / NumEltsIn; 14159 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14160 if (SToVLHS.getValueType() != LHS.getValueType()) 14161 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14162 LHS = SToVLHS; 14163 } 14164 if (SToVRHS) { 14165 RHSMinIdx = NumEltsOut; 14166 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14167 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14168 if (SToVRHS.getValueType() != RHS.getValueType()) 14169 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14170 RHS = SToVRHS; 14171 } 14172 14173 // Fix up the shuffle mask to reflect where the desired element actually is. 14174 // The minimum and maximum indices that correspond to element zero for both 14175 // the LHS and RHS are computed and will control which shuffle mask entries 14176 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14177 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14178 // HalfVec to refer to the corresponding element in the permuted vector. 14179 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14180 HalfVec); 14181 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14182 14183 // We may have simplified away the shuffle. We won't be able to do anything 14184 // further with it here. 14185 if (!isa<ShuffleVectorSDNode>(Res)) 14186 return Res; 14187 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14188 } 14189 14190 // The common case after we commuted the shuffle is that the RHS is a splat 14191 // and we have elements coming in from the splat at indices that are not 14192 // conducive to using a merge. 14193 // Example: 14194 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14195 if (!isSplatBV(RHS)) 14196 return Res; 14197 14198 // We are looking for a mask such that all even elements are from 14199 // one vector and all odd elements from the other. 14200 if (!isAlternatingShuffMask(Mask, NumElts)) 14201 return Res; 14202 14203 // Adjust the mask so we are pulling in the same index from the splat 14204 // as the index from the interesting vector in consecutive elements. 14205 // Example (even elements from first vector): 14206 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14207 if (Mask[0] < NumElts) 14208 for (int i = 1, e = Mask.size(); i < e; i += 2) 14209 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14210 // Example (odd elements from first vector): 14211 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14212 else 14213 for (int i = 0, e = Mask.size(); i < e; i += 2) 14214 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14215 14216 // If the RHS has undefs, we need to remove them since we may have created 14217 // a shuffle that adds those instead of the splat value. 14218 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14219 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14220 14221 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14222 return Res; 14223 } 14224 14225 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14226 LSBaseSDNode *LSBase, 14227 DAGCombinerInfo &DCI) const { 14228 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14229 "Not a reverse memop pattern!"); 14230 14231 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14232 auto Mask = SVN->getMask(); 14233 int i = 0; 14234 auto I = Mask.rbegin(); 14235 auto E = Mask.rend(); 14236 14237 for (; I != E; ++I) { 14238 if (*I != i) 14239 return false; 14240 i++; 14241 } 14242 return true; 14243 }; 14244 14245 SelectionDAG &DAG = DCI.DAG; 14246 EVT VT = SVN->getValueType(0); 14247 14248 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14249 return SDValue(); 14250 14251 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14252 // See comment in PPCVSXSwapRemoval.cpp. 14253 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14254 if (!Subtarget.hasP9Vector()) 14255 return SDValue(); 14256 14257 if(!IsElementReverse(SVN)) 14258 return SDValue(); 14259 14260 if (LSBase->getOpcode() == ISD::LOAD) { 14261 SDLoc dl(SVN); 14262 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14263 return DAG.getMemIntrinsicNode( 14264 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14265 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14266 } 14267 14268 if (LSBase->getOpcode() == ISD::STORE) { 14269 SDLoc dl(LSBase); 14270 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14271 LSBase->getBasePtr()}; 14272 return DAG.getMemIntrinsicNode( 14273 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14274 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14275 } 14276 14277 llvm_unreachable("Expected a load or store node here"); 14278 } 14279 14280 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14281 DAGCombinerInfo &DCI) const { 14282 SelectionDAG &DAG = DCI.DAG; 14283 SDLoc dl(N); 14284 switch (N->getOpcode()) { 14285 default: break; 14286 case ISD::ADD: 14287 return combineADD(N, DCI); 14288 case ISD::SHL: 14289 return combineSHL(N, DCI); 14290 case ISD::SRA: 14291 return combineSRA(N, DCI); 14292 case ISD::SRL: 14293 return combineSRL(N, DCI); 14294 case ISD::MUL: 14295 return combineMUL(N, DCI); 14296 case ISD::FMA: 14297 case PPCISD::FNMSUB: 14298 return combineFMALike(N, DCI); 14299 case PPCISD::SHL: 14300 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14301 return N->getOperand(0); 14302 break; 14303 case PPCISD::SRL: 14304 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14305 return N->getOperand(0); 14306 break; 14307 case PPCISD::SRA: 14308 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14309 if (C->isNullValue() || // 0 >>s V -> 0. 14310 C->isAllOnesValue()) // -1 >>s V -> -1. 14311 return N->getOperand(0); 14312 } 14313 break; 14314 case ISD::SIGN_EXTEND: 14315 case ISD::ZERO_EXTEND: 14316 case ISD::ANY_EXTEND: 14317 return DAGCombineExtBoolTrunc(N, DCI); 14318 case ISD::TRUNCATE: 14319 return combineTRUNCATE(N, DCI); 14320 case ISD::SETCC: 14321 if (SDValue CSCC = combineSetCC(N, DCI)) 14322 return CSCC; 14323 LLVM_FALLTHROUGH; 14324 case ISD::SELECT_CC: 14325 return DAGCombineTruncBoolExt(N, DCI); 14326 case ISD::SINT_TO_FP: 14327 case ISD::UINT_TO_FP: 14328 return combineFPToIntToFP(N, DCI); 14329 case ISD::VECTOR_SHUFFLE: 14330 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14331 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14332 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14333 } 14334 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14335 case ISD::STORE: { 14336 14337 EVT Op1VT = N->getOperand(1).getValueType(); 14338 unsigned Opcode = N->getOperand(1).getOpcode(); 14339 14340 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14341 SDValue Val= combineStoreFPToInt(N, DCI); 14342 if (Val) 14343 return Val; 14344 } 14345 14346 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14347 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14348 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14349 if (Val) 14350 return Val; 14351 } 14352 14353 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14354 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14355 N->getOperand(1).getNode()->hasOneUse() && 14356 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14357 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14358 14359 // STBRX can only handle simple types and it makes no sense to store less 14360 // two bytes in byte-reversed order. 14361 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14362 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14363 break; 14364 14365 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14366 // Do an any-extend to 32-bits if this is a half-word input. 14367 if (BSwapOp.getValueType() == MVT::i16) 14368 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14369 14370 // If the type of BSWAP operand is wider than stored memory width 14371 // it need to be shifted to the right side before STBRX. 14372 if (Op1VT.bitsGT(mVT)) { 14373 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14374 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14375 DAG.getConstant(Shift, dl, MVT::i32)); 14376 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14377 if (Op1VT == MVT::i64) 14378 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14379 } 14380 14381 SDValue Ops[] = { 14382 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14383 }; 14384 return 14385 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14386 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14387 cast<StoreSDNode>(N)->getMemOperand()); 14388 } 14389 14390 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14391 // So it can increase the chance of CSE constant construction. 14392 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14393 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14394 // Need to sign-extended to 64-bits to handle negative values. 14395 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14396 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14397 MemVT.getSizeInBits()); 14398 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14399 14400 // DAG.getTruncStore() can't be used here because it doesn't accept 14401 // the general (base + offset) addressing mode. 14402 // So we use UpdateNodeOperands and setTruncatingStore instead. 14403 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14404 N->getOperand(3)); 14405 cast<StoreSDNode>(N)->setTruncatingStore(true); 14406 return SDValue(N, 0); 14407 } 14408 14409 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14410 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14411 if (Op1VT.isSimple()) { 14412 MVT StoreVT = Op1VT.getSimpleVT(); 14413 if (Subtarget.needsSwapsForVSXMemOps() && 14414 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14415 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14416 return expandVSXStoreForLE(N, DCI); 14417 } 14418 break; 14419 } 14420 case ISD::LOAD: { 14421 LoadSDNode *LD = cast<LoadSDNode>(N); 14422 EVT VT = LD->getValueType(0); 14423 14424 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14425 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14426 if (VT.isSimple()) { 14427 MVT LoadVT = VT.getSimpleVT(); 14428 if (Subtarget.needsSwapsForVSXMemOps() && 14429 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14430 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14431 return expandVSXLoadForLE(N, DCI); 14432 } 14433 14434 // We sometimes end up with a 64-bit integer load, from which we extract 14435 // two single-precision floating-point numbers. This happens with 14436 // std::complex<float>, and other similar structures, because of the way we 14437 // canonicalize structure copies. However, if we lack direct moves, 14438 // then the final bitcasts from the extracted integer values to the 14439 // floating-point numbers turn into store/load pairs. Even with direct moves, 14440 // just loading the two floating-point numbers is likely better. 14441 auto ReplaceTwoFloatLoad = [&]() { 14442 if (VT != MVT::i64) 14443 return false; 14444 14445 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14446 LD->isVolatile()) 14447 return false; 14448 14449 // We're looking for a sequence like this: 14450 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14451 // t16: i64 = srl t13, Constant:i32<32> 14452 // t17: i32 = truncate t16 14453 // t18: f32 = bitcast t17 14454 // t19: i32 = truncate t13 14455 // t20: f32 = bitcast t19 14456 14457 if (!LD->hasNUsesOfValue(2, 0)) 14458 return false; 14459 14460 auto UI = LD->use_begin(); 14461 while (UI.getUse().getResNo() != 0) ++UI; 14462 SDNode *Trunc = *UI++; 14463 while (UI.getUse().getResNo() != 0) ++UI; 14464 SDNode *RightShift = *UI; 14465 if (Trunc->getOpcode() != ISD::TRUNCATE) 14466 std::swap(Trunc, RightShift); 14467 14468 if (Trunc->getOpcode() != ISD::TRUNCATE || 14469 Trunc->getValueType(0) != MVT::i32 || 14470 !Trunc->hasOneUse()) 14471 return false; 14472 if (RightShift->getOpcode() != ISD::SRL || 14473 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14474 RightShift->getConstantOperandVal(1) != 32 || 14475 !RightShift->hasOneUse()) 14476 return false; 14477 14478 SDNode *Trunc2 = *RightShift->use_begin(); 14479 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14480 Trunc2->getValueType(0) != MVT::i32 || 14481 !Trunc2->hasOneUse()) 14482 return false; 14483 14484 SDNode *Bitcast = *Trunc->use_begin(); 14485 SDNode *Bitcast2 = *Trunc2->use_begin(); 14486 14487 if (Bitcast->getOpcode() != ISD::BITCAST || 14488 Bitcast->getValueType(0) != MVT::f32) 14489 return false; 14490 if (Bitcast2->getOpcode() != ISD::BITCAST || 14491 Bitcast2->getValueType(0) != MVT::f32) 14492 return false; 14493 14494 if (Subtarget.isLittleEndian()) 14495 std::swap(Bitcast, Bitcast2); 14496 14497 // Bitcast has the second float (in memory-layout order) and Bitcast2 14498 // has the first one. 14499 14500 SDValue BasePtr = LD->getBasePtr(); 14501 if (LD->isIndexed()) { 14502 assert(LD->getAddressingMode() == ISD::PRE_INC && 14503 "Non-pre-inc AM on PPC?"); 14504 BasePtr = 14505 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14506 LD->getOffset()); 14507 } 14508 14509 auto MMOFlags = 14510 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14511 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14512 LD->getPointerInfo(), LD->getAlignment(), 14513 MMOFlags, LD->getAAInfo()); 14514 SDValue AddPtr = 14515 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14516 BasePtr, DAG.getIntPtrConstant(4, dl)); 14517 SDValue FloatLoad2 = DAG.getLoad( 14518 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14519 LD->getPointerInfo().getWithOffset(4), 14520 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14521 14522 if (LD->isIndexed()) { 14523 // Note that DAGCombine should re-form any pre-increment load(s) from 14524 // what is produced here if that makes sense. 14525 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14526 } 14527 14528 DCI.CombineTo(Bitcast2, FloatLoad); 14529 DCI.CombineTo(Bitcast, FloatLoad2); 14530 14531 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14532 SDValue(FloatLoad2.getNode(), 1)); 14533 return true; 14534 }; 14535 14536 if (ReplaceTwoFloatLoad()) 14537 return SDValue(N, 0); 14538 14539 EVT MemVT = LD->getMemoryVT(); 14540 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14541 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14542 if (LD->isUnindexed() && VT.isVector() && 14543 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14544 // P8 and later hardware should just use LOAD. 14545 !Subtarget.hasP8Vector() && 14546 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14547 VT == MVT::v4f32))) && 14548 LD->getAlign() < ABIAlignment) { 14549 // This is a type-legal unaligned Altivec load. 14550 SDValue Chain = LD->getChain(); 14551 SDValue Ptr = LD->getBasePtr(); 14552 bool isLittleEndian = Subtarget.isLittleEndian(); 14553 14554 // This implements the loading of unaligned vectors as described in 14555 // the venerable Apple Velocity Engine overview. Specifically: 14556 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14557 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14558 // 14559 // The general idea is to expand a sequence of one or more unaligned 14560 // loads into an alignment-based permutation-control instruction (lvsl 14561 // or lvsr), a series of regular vector loads (which always truncate 14562 // their input address to an aligned address), and a series of 14563 // permutations. The results of these permutations are the requested 14564 // loaded values. The trick is that the last "extra" load is not taken 14565 // from the address you might suspect (sizeof(vector) bytes after the 14566 // last requested load), but rather sizeof(vector) - 1 bytes after the 14567 // last requested vector. The point of this is to avoid a page fault if 14568 // the base address happened to be aligned. This works because if the 14569 // base address is aligned, then adding less than a full vector length 14570 // will cause the last vector in the sequence to be (re)loaded. 14571 // Otherwise, the next vector will be fetched as you might suspect was 14572 // necessary. 14573 14574 // We might be able to reuse the permutation generation from 14575 // a different base address offset from this one by an aligned amount. 14576 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14577 // optimization later. 14578 Intrinsic::ID Intr, IntrLD, IntrPerm; 14579 MVT PermCntlTy, PermTy, LDTy; 14580 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14581 : Intrinsic::ppc_altivec_lvsl; 14582 IntrLD = Intrinsic::ppc_altivec_lvx; 14583 IntrPerm = Intrinsic::ppc_altivec_vperm; 14584 PermCntlTy = MVT::v16i8; 14585 PermTy = MVT::v4i32; 14586 LDTy = MVT::v4i32; 14587 14588 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14589 14590 // Create the new MMO for the new base load. It is like the original MMO, 14591 // but represents an area in memory almost twice the vector size centered 14592 // on the original address. If the address is unaligned, we might start 14593 // reading up to (sizeof(vector)-1) bytes below the address of the 14594 // original unaligned load. 14595 MachineFunction &MF = DAG.getMachineFunction(); 14596 MachineMemOperand *BaseMMO = 14597 MF.getMachineMemOperand(LD->getMemOperand(), 14598 -(long)MemVT.getStoreSize()+1, 14599 2*MemVT.getStoreSize()-1); 14600 14601 // Create the new base load. 14602 SDValue LDXIntID = 14603 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14604 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14605 SDValue BaseLoad = 14606 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14607 DAG.getVTList(PermTy, MVT::Other), 14608 BaseLoadOps, LDTy, BaseMMO); 14609 14610 // Note that the value of IncOffset (which is provided to the next 14611 // load's pointer info offset value, and thus used to calculate the 14612 // alignment), and the value of IncValue (which is actually used to 14613 // increment the pointer value) are different! This is because we 14614 // require the next load to appear to be aligned, even though it 14615 // is actually offset from the base pointer by a lesser amount. 14616 int IncOffset = VT.getSizeInBits() / 8; 14617 int IncValue = IncOffset; 14618 14619 // Walk (both up and down) the chain looking for another load at the real 14620 // (aligned) offset (the alignment of the other load does not matter in 14621 // this case). If found, then do not use the offset reduction trick, as 14622 // that will prevent the loads from being later combined (as they would 14623 // otherwise be duplicates). 14624 if (!findConsecutiveLoad(LD, DAG)) 14625 --IncValue; 14626 14627 SDValue Increment = 14628 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14629 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14630 14631 MachineMemOperand *ExtraMMO = 14632 MF.getMachineMemOperand(LD->getMemOperand(), 14633 1, 2*MemVT.getStoreSize()-1); 14634 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14635 SDValue ExtraLoad = 14636 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14637 DAG.getVTList(PermTy, MVT::Other), 14638 ExtraLoadOps, LDTy, ExtraMMO); 14639 14640 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14641 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14642 14643 // Because vperm has a big-endian bias, we must reverse the order 14644 // of the input vectors and complement the permute control vector 14645 // when generating little endian code. We have already handled the 14646 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14647 // and ExtraLoad here. 14648 SDValue Perm; 14649 if (isLittleEndian) 14650 Perm = BuildIntrinsicOp(IntrPerm, 14651 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14652 else 14653 Perm = BuildIntrinsicOp(IntrPerm, 14654 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14655 14656 if (VT != PermTy) 14657 Perm = Subtarget.hasAltivec() 14658 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14659 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14660 DAG.getTargetConstant(1, dl, MVT::i64)); 14661 // second argument is 1 because this rounding 14662 // is always exact. 14663 14664 // The output of the permutation is our loaded result, the TokenFactor is 14665 // our new chain. 14666 DCI.CombineTo(N, Perm, TF); 14667 return SDValue(N, 0); 14668 } 14669 } 14670 break; 14671 case ISD::INTRINSIC_WO_CHAIN: { 14672 bool isLittleEndian = Subtarget.isLittleEndian(); 14673 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14674 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14675 : Intrinsic::ppc_altivec_lvsl); 14676 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14677 SDValue Add = N->getOperand(1); 14678 14679 int Bits = 4 /* 16 byte alignment */; 14680 14681 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14682 APInt::getAllOnesValue(Bits /* alignment */) 14683 .zext(Add.getScalarValueSizeInBits()))) { 14684 SDNode *BasePtr = Add->getOperand(0).getNode(); 14685 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14686 UE = BasePtr->use_end(); 14687 UI != UE; ++UI) { 14688 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14689 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14690 IID) { 14691 // We've found another LVSL/LVSR, and this address is an aligned 14692 // multiple of that one. The results will be the same, so use the 14693 // one we've just found instead. 14694 14695 return SDValue(*UI, 0); 14696 } 14697 } 14698 } 14699 14700 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14701 SDNode *BasePtr = Add->getOperand(0).getNode(); 14702 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14703 UE = BasePtr->use_end(); UI != UE; ++UI) { 14704 if (UI->getOpcode() == ISD::ADD && 14705 isa<ConstantSDNode>(UI->getOperand(1)) && 14706 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14707 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14708 (1ULL << Bits) == 0) { 14709 SDNode *OtherAdd = *UI; 14710 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14711 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14712 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14713 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14714 return SDValue(*VI, 0); 14715 } 14716 } 14717 } 14718 } 14719 } 14720 } 14721 14722 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14723 // Expose the vabsduw/h/b opportunity for down stream 14724 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14725 (IID == Intrinsic::ppc_altivec_vmaxsw || 14726 IID == Intrinsic::ppc_altivec_vmaxsh || 14727 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14728 SDValue V1 = N->getOperand(1); 14729 SDValue V2 = N->getOperand(2); 14730 if ((V1.getSimpleValueType() == MVT::v4i32 || 14731 V1.getSimpleValueType() == MVT::v8i16 || 14732 V1.getSimpleValueType() == MVT::v16i8) && 14733 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14734 // (0-a, a) 14735 if (V1.getOpcode() == ISD::SUB && 14736 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14737 V1.getOperand(1) == V2) { 14738 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14739 } 14740 // (a, 0-a) 14741 if (V2.getOpcode() == ISD::SUB && 14742 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14743 V2.getOperand(1) == V1) { 14744 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14745 } 14746 // (x-y, y-x) 14747 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14748 V1.getOperand(0) == V2.getOperand(1) && 14749 V1.getOperand(1) == V2.getOperand(0)) { 14750 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14751 } 14752 } 14753 } 14754 } 14755 14756 break; 14757 case ISD::INTRINSIC_W_CHAIN: 14758 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14759 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14760 if (Subtarget.needsSwapsForVSXMemOps()) { 14761 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14762 default: 14763 break; 14764 case Intrinsic::ppc_vsx_lxvw4x: 14765 case Intrinsic::ppc_vsx_lxvd2x: 14766 return expandVSXLoadForLE(N, DCI); 14767 } 14768 } 14769 break; 14770 case ISD::INTRINSIC_VOID: 14771 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14772 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14773 if (Subtarget.needsSwapsForVSXMemOps()) { 14774 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14775 default: 14776 break; 14777 case Intrinsic::ppc_vsx_stxvw4x: 14778 case Intrinsic::ppc_vsx_stxvd2x: 14779 return expandVSXStoreForLE(N, DCI); 14780 } 14781 } 14782 break; 14783 case ISD::BSWAP: 14784 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14785 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14786 N->getOperand(0).hasOneUse() && 14787 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14788 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14789 N->getValueType(0) == MVT::i64))) { 14790 SDValue Load = N->getOperand(0); 14791 LoadSDNode *LD = cast<LoadSDNode>(Load); 14792 // Create the byte-swapping load. 14793 SDValue Ops[] = { 14794 LD->getChain(), // Chain 14795 LD->getBasePtr(), // Ptr 14796 DAG.getValueType(N->getValueType(0)) // VT 14797 }; 14798 SDValue BSLoad = 14799 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14800 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14801 MVT::i64 : MVT::i32, MVT::Other), 14802 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14803 14804 // If this is an i16 load, insert the truncate. 14805 SDValue ResVal = BSLoad; 14806 if (N->getValueType(0) == MVT::i16) 14807 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14808 14809 // First, combine the bswap away. This makes the value produced by the 14810 // load dead. 14811 DCI.CombineTo(N, ResVal); 14812 14813 // Next, combine the load away, we give it a bogus result value but a real 14814 // chain result. The result value is dead because the bswap is dead. 14815 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14816 14817 // Return N so it doesn't get rechecked! 14818 return SDValue(N, 0); 14819 } 14820 break; 14821 case PPCISD::VCMP: 14822 // If a VCMPo node already exists with exactly the same operands as this 14823 // node, use its result instead of this node (VCMPo computes both a CR6 and 14824 // a normal output). 14825 // 14826 if (!N->getOperand(0).hasOneUse() && 14827 !N->getOperand(1).hasOneUse() && 14828 !N->getOperand(2).hasOneUse()) { 14829 14830 // Scan all of the users of the LHS, looking for VCMPo's that match. 14831 SDNode *VCMPoNode = nullptr; 14832 14833 SDNode *LHSN = N->getOperand(0).getNode(); 14834 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14835 UI != E; ++UI) 14836 if (UI->getOpcode() == PPCISD::VCMPo && 14837 UI->getOperand(1) == N->getOperand(1) && 14838 UI->getOperand(2) == N->getOperand(2) && 14839 UI->getOperand(0) == N->getOperand(0)) { 14840 VCMPoNode = *UI; 14841 break; 14842 } 14843 14844 // If there is no VCMPo node, or if the flag value has a single use, don't 14845 // transform this. 14846 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14847 break; 14848 14849 // Look at the (necessarily single) use of the flag value. If it has a 14850 // chain, this transformation is more complex. Note that multiple things 14851 // could use the value result, which we should ignore. 14852 SDNode *FlagUser = nullptr; 14853 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14854 FlagUser == nullptr; ++UI) { 14855 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14856 SDNode *User = *UI; 14857 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14858 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14859 FlagUser = User; 14860 break; 14861 } 14862 } 14863 } 14864 14865 // If the user is a MFOCRF instruction, we know this is safe. 14866 // Otherwise we give up for right now. 14867 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14868 return SDValue(VCMPoNode, 0); 14869 } 14870 break; 14871 case ISD::BRCOND: { 14872 SDValue Cond = N->getOperand(1); 14873 SDValue Target = N->getOperand(2); 14874 14875 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14876 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14877 Intrinsic::loop_decrement) { 14878 14879 // We now need to make the intrinsic dead (it cannot be instruction 14880 // selected). 14881 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14882 assert(Cond.getNode()->hasOneUse() && 14883 "Counter decrement has more than one use"); 14884 14885 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14886 N->getOperand(0), Target); 14887 } 14888 } 14889 break; 14890 case ISD::BR_CC: { 14891 // If this is a branch on an altivec predicate comparison, lower this so 14892 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14893 // lowering is done pre-legalize, because the legalizer lowers the predicate 14894 // compare down to code that is difficult to reassemble. 14895 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14896 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14897 14898 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14899 // value. If so, pass-through the AND to get to the intrinsic. 14900 if (LHS.getOpcode() == ISD::AND && 14901 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14902 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14903 Intrinsic::loop_decrement && 14904 isa<ConstantSDNode>(LHS.getOperand(1)) && 14905 !isNullConstant(LHS.getOperand(1))) 14906 LHS = LHS.getOperand(0); 14907 14908 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14909 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14910 Intrinsic::loop_decrement && 14911 isa<ConstantSDNode>(RHS)) { 14912 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14913 "Counter decrement comparison is not EQ or NE"); 14914 14915 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14916 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14917 (CC == ISD::SETNE && !Val); 14918 14919 // We now need to make the intrinsic dead (it cannot be instruction 14920 // selected). 14921 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14922 assert(LHS.getNode()->hasOneUse() && 14923 "Counter decrement has more than one use"); 14924 14925 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14926 N->getOperand(0), N->getOperand(4)); 14927 } 14928 14929 int CompareOpc; 14930 bool isDot; 14931 14932 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14933 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14934 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14935 assert(isDot && "Can't compare against a vector result!"); 14936 14937 // If this is a comparison against something other than 0/1, then we know 14938 // that the condition is never/always true. 14939 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14940 if (Val != 0 && Val != 1) { 14941 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14942 return N->getOperand(0); 14943 // Always !=, turn it into an unconditional branch. 14944 return DAG.getNode(ISD::BR, dl, MVT::Other, 14945 N->getOperand(0), N->getOperand(4)); 14946 } 14947 14948 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14949 14950 // Create the PPCISD altivec 'dot' comparison node. 14951 SDValue Ops[] = { 14952 LHS.getOperand(2), // LHS of compare 14953 LHS.getOperand(3), // RHS of compare 14954 DAG.getConstant(CompareOpc, dl, MVT::i32) 14955 }; 14956 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14957 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14958 14959 // Unpack the result based on how the target uses it. 14960 PPC::Predicate CompOpc; 14961 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14962 default: // Can't happen, don't crash on invalid number though. 14963 case 0: // Branch on the value of the EQ bit of CR6. 14964 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14965 break; 14966 case 1: // Branch on the inverted value of the EQ bit of CR6. 14967 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14968 break; 14969 case 2: // Branch on the value of the LT bit of CR6. 14970 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14971 break; 14972 case 3: // Branch on the inverted value of the LT bit of CR6. 14973 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14974 break; 14975 } 14976 14977 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14978 DAG.getConstant(CompOpc, dl, MVT::i32), 14979 DAG.getRegister(PPC::CR6, MVT::i32), 14980 N->getOperand(4), CompNode.getValue(1)); 14981 } 14982 break; 14983 } 14984 case ISD::BUILD_VECTOR: 14985 return DAGCombineBuildVector(N, DCI); 14986 case ISD::ABS: 14987 return combineABS(N, DCI); 14988 case ISD::VSELECT: 14989 return combineVSelect(N, DCI); 14990 } 14991 14992 return SDValue(); 14993 } 14994 14995 SDValue 14996 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14997 SelectionDAG &DAG, 14998 SmallVectorImpl<SDNode *> &Created) const { 14999 // fold (sdiv X, pow2) 15000 EVT VT = N->getValueType(0); 15001 if (VT == MVT::i64 && !Subtarget.isPPC64()) 15002 return SDValue(); 15003 if ((VT != MVT::i32 && VT != MVT::i64) || 15004 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 15005 return SDValue(); 15006 15007 SDLoc DL(N); 15008 SDValue N0 = N->getOperand(0); 15009 15010 bool IsNegPow2 = (-Divisor).isPowerOf2(); 15011 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 15012 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 15013 15014 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 15015 Created.push_back(Op.getNode()); 15016 15017 if (IsNegPow2) { 15018 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 15019 Created.push_back(Op.getNode()); 15020 } 15021 15022 return Op; 15023 } 15024 15025 //===----------------------------------------------------------------------===// 15026 // Inline Assembly Support 15027 //===----------------------------------------------------------------------===// 15028 15029 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 15030 KnownBits &Known, 15031 const APInt &DemandedElts, 15032 const SelectionDAG &DAG, 15033 unsigned Depth) const { 15034 Known.resetAll(); 15035 switch (Op.getOpcode()) { 15036 default: break; 15037 case PPCISD::LBRX: { 15038 // lhbrx is known to have the top bits cleared out. 15039 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 15040 Known.Zero = 0xFFFF0000; 15041 break; 15042 } 15043 case ISD::INTRINSIC_WO_CHAIN: { 15044 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 15045 default: break; 15046 case Intrinsic::ppc_altivec_vcmpbfp_p: 15047 case Intrinsic::ppc_altivec_vcmpeqfp_p: 15048 case Intrinsic::ppc_altivec_vcmpequb_p: 15049 case Intrinsic::ppc_altivec_vcmpequh_p: 15050 case Intrinsic::ppc_altivec_vcmpequw_p: 15051 case Intrinsic::ppc_altivec_vcmpequd_p: 15052 case Intrinsic::ppc_altivec_vcmpgefp_p: 15053 case Intrinsic::ppc_altivec_vcmpgtfp_p: 15054 case Intrinsic::ppc_altivec_vcmpgtsb_p: 15055 case Intrinsic::ppc_altivec_vcmpgtsh_p: 15056 case Intrinsic::ppc_altivec_vcmpgtsw_p: 15057 case Intrinsic::ppc_altivec_vcmpgtsd_p: 15058 case Intrinsic::ppc_altivec_vcmpgtub_p: 15059 case Intrinsic::ppc_altivec_vcmpgtuh_p: 15060 case Intrinsic::ppc_altivec_vcmpgtuw_p: 15061 case Intrinsic::ppc_altivec_vcmpgtud_p: 15062 Known.Zero = ~1U; // All bits but the low one are known to be zero. 15063 break; 15064 } 15065 } 15066 } 15067 } 15068 15069 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 15070 switch (Subtarget.getCPUDirective()) { 15071 default: break; 15072 case PPC::DIR_970: 15073 case PPC::DIR_PWR4: 15074 case PPC::DIR_PWR5: 15075 case PPC::DIR_PWR5X: 15076 case PPC::DIR_PWR6: 15077 case PPC::DIR_PWR6X: 15078 case PPC::DIR_PWR7: 15079 case PPC::DIR_PWR8: 15080 case PPC::DIR_PWR9: 15081 case PPC::DIR_PWR10: 15082 case PPC::DIR_PWR_FUTURE: { 15083 if (!ML) 15084 break; 15085 15086 if (!DisableInnermostLoopAlign32) { 15087 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 15088 // so that we can decrease cache misses and branch-prediction misses. 15089 // Actual alignment of the loop will depend on the hotness check and other 15090 // logic in alignBlocks. 15091 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 15092 return Align(32); 15093 } 15094 15095 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 15096 15097 // For small loops (between 5 and 8 instructions), align to a 32-byte 15098 // boundary so that the entire loop fits in one instruction-cache line. 15099 uint64_t LoopSize = 0; 15100 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 15101 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 15102 LoopSize += TII->getInstSizeInBytes(*J); 15103 if (LoopSize > 32) 15104 break; 15105 } 15106 15107 if (LoopSize > 16 && LoopSize <= 32) 15108 return Align(32); 15109 15110 break; 15111 } 15112 } 15113 15114 return TargetLowering::getPrefLoopAlignment(ML); 15115 } 15116 15117 /// getConstraintType - Given a constraint, return the type of 15118 /// constraint it is for this target. 15119 PPCTargetLowering::ConstraintType 15120 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 15121 if (Constraint.size() == 1) { 15122 switch (Constraint[0]) { 15123 default: break; 15124 case 'b': 15125 case 'r': 15126 case 'f': 15127 case 'd': 15128 case 'v': 15129 case 'y': 15130 return C_RegisterClass; 15131 case 'Z': 15132 // FIXME: While Z does indicate a memory constraint, it specifically 15133 // indicates an r+r address (used in conjunction with the 'y' modifier 15134 // in the replacement string). Currently, we're forcing the base 15135 // register to be r0 in the asm printer (which is interpreted as zero) 15136 // and forming the complete address in the second register. This is 15137 // suboptimal. 15138 return C_Memory; 15139 } 15140 } else if (Constraint == "wc") { // individual CR bits. 15141 return C_RegisterClass; 15142 } else if (Constraint == "wa" || Constraint == "wd" || 15143 Constraint == "wf" || Constraint == "ws" || 15144 Constraint == "wi" || Constraint == "ww") { 15145 return C_RegisterClass; // VSX registers. 15146 } 15147 return TargetLowering::getConstraintType(Constraint); 15148 } 15149 15150 /// Examine constraint type and operand type and determine a weight value. 15151 /// This object must already have been set up with the operand type 15152 /// and the current alternative constraint selected. 15153 TargetLowering::ConstraintWeight 15154 PPCTargetLowering::getSingleConstraintMatchWeight( 15155 AsmOperandInfo &info, const char *constraint) const { 15156 ConstraintWeight weight = CW_Invalid; 15157 Value *CallOperandVal = info.CallOperandVal; 15158 // If we don't have a value, we can't do a match, 15159 // but allow it at the lowest weight. 15160 if (!CallOperandVal) 15161 return CW_Default; 15162 Type *type = CallOperandVal->getType(); 15163 15164 // Look at the constraint type. 15165 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15166 return CW_Register; // an individual CR bit. 15167 else if ((StringRef(constraint) == "wa" || 15168 StringRef(constraint) == "wd" || 15169 StringRef(constraint) == "wf") && 15170 type->isVectorTy()) 15171 return CW_Register; 15172 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15173 return CW_Register; // just hold 64-bit integers data. 15174 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15175 return CW_Register; 15176 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15177 return CW_Register; 15178 15179 switch (*constraint) { 15180 default: 15181 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15182 break; 15183 case 'b': 15184 if (type->isIntegerTy()) 15185 weight = CW_Register; 15186 break; 15187 case 'f': 15188 if (type->isFloatTy()) 15189 weight = CW_Register; 15190 break; 15191 case 'd': 15192 if (type->isDoubleTy()) 15193 weight = CW_Register; 15194 break; 15195 case 'v': 15196 if (type->isVectorTy()) 15197 weight = CW_Register; 15198 break; 15199 case 'y': 15200 weight = CW_Register; 15201 break; 15202 case 'Z': 15203 weight = CW_Memory; 15204 break; 15205 } 15206 return weight; 15207 } 15208 15209 std::pair<unsigned, const TargetRegisterClass *> 15210 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15211 StringRef Constraint, 15212 MVT VT) const { 15213 if (Constraint.size() == 1) { 15214 // GCC RS6000 Constraint Letters 15215 switch (Constraint[0]) { 15216 case 'b': // R1-R31 15217 if (VT == MVT::i64 && Subtarget.isPPC64()) 15218 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15219 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15220 case 'r': // R0-R31 15221 if (VT == MVT::i64 && Subtarget.isPPC64()) 15222 return std::make_pair(0U, &PPC::G8RCRegClass); 15223 return std::make_pair(0U, &PPC::GPRCRegClass); 15224 // 'd' and 'f' constraints are both defined to be "the floating point 15225 // registers", where one is for 32-bit and the other for 64-bit. We don't 15226 // really care overly much here so just give them all the same reg classes. 15227 case 'd': 15228 case 'f': 15229 if (Subtarget.hasSPE()) { 15230 if (VT == MVT::f32 || VT == MVT::i32) 15231 return std::make_pair(0U, &PPC::GPRCRegClass); 15232 if (VT == MVT::f64 || VT == MVT::i64) 15233 return std::make_pair(0U, &PPC::SPERCRegClass); 15234 } else { 15235 if (VT == MVT::f32 || VT == MVT::i32) 15236 return std::make_pair(0U, &PPC::F4RCRegClass); 15237 if (VT == MVT::f64 || VT == MVT::i64) 15238 return std::make_pair(0U, &PPC::F8RCRegClass); 15239 } 15240 break; 15241 case 'v': 15242 if (Subtarget.hasAltivec()) 15243 return std::make_pair(0U, &PPC::VRRCRegClass); 15244 break; 15245 case 'y': // crrc 15246 return std::make_pair(0U, &PPC::CRRCRegClass); 15247 } 15248 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15249 // An individual CR bit. 15250 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15251 } else if ((Constraint == "wa" || Constraint == "wd" || 15252 Constraint == "wf" || Constraint == "wi") && 15253 Subtarget.hasVSX()) { 15254 return std::make_pair(0U, &PPC::VSRCRegClass); 15255 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15256 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15257 return std::make_pair(0U, &PPC::VSSRCRegClass); 15258 else 15259 return std::make_pair(0U, &PPC::VSFRCRegClass); 15260 } 15261 15262 // If we name a VSX register, we can't defer to the base class because it 15263 // will not recognize the correct register (their names will be VSL{0-31} 15264 // and V{0-31} so they won't match). So we match them here. 15265 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15266 int VSNum = atoi(Constraint.data() + 3); 15267 assert(VSNum >= 0 && VSNum <= 63 && 15268 "Attempted to access a vsr out of range"); 15269 if (VSNum < 32) 15270 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15271 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15272 } 15273 std::pair<unsigned, const TargetRegisterClass *> R = 15274 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15275 15276 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15277 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15278 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15279 // register. 15280 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15281 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15282 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15283 PPC::GPRCRegClass.contains(R.first)) 15284 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15285 PPC::sub_32, &PPC::G8RCRegClass), 15286 &PPC::G8RCRegClass); 15287 15288 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15289 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15290 R.first = PPC::CR0; 15291 R.second = &PPC::CRRCRegClass; 15292 } 15293 15294 return R; 15295 } 15296 15297 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15298 /// vector. If it is invalid, don't add anything to Ops. 15299 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15300 std::string &Constraint, 15301 std::vector<SDValue>&Ops, 15302 SelectionDAG &DAG) const { 15303 SDValue Result; 15304 15305 // Only support length 1 constraints. 15306 if (Constraint.length() > 1) return; 15307 15308 char Letter = Constraint[0]; 15309 switch (Letter) { 15310 default: break; 15311 case 'I': 15312 case 'J': 15313 case 'K': 15314 case 'L': 15315 case 'M': 15316 case 'N': 15317 case 'O': 15318 case 'P': { 15319 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15320 if (!CST) return; // Must be an immediate to match. 15321 SDLoc dl(Op); 15322 int64_t Value = CST->getSExtValue(); 15323 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15324 // numbers are printed as such. 15325 switch (Letter) { 15326 default: llvm_unreachable("Unknown constraint letter!"); 15327 case 'I': // "I" is a signed 16-bit constant. 15328 if (isInt<16>(Value)) 15329 Result = DAG.getTargetConstant(Value, dl, TCVT); 15330 break; 15331 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15332 if (isShiftedUInt<16, 16>(Value)) 15333 Result = DAG.getTargetConstant(Value, dl, TCVT); 15334 break; 15335 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15336 if (isShiftedInt<16, 16>(Value)) 15337 Result = DAG.getTargetConstant(Value, dl, TCVT); 15338 break; 15339 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15340 if (isUInt<16>(Value)) 15341 Result = DAG.getTargetConstant(Value, dl, TCVT); 15342 break; 15343 case 'M': // "M" is a constant that is greater than 31. 15344 if (Value > 31) 15345 Result = DAG.getTargetConstant(Value, dl, TCVT); 15346 break; 15347 case 'N': // "N" is a positive constant that is an exact power of two. 15348 if (Value > 0 && isPowerOf2_64(Value)) 15349 Result = DAG.getTargetConstant(Value, dl, TCVT); 15350 break; 15351 case 'O': // "O" is the constant zero. 15352 if (Value == 0) 15353 Result = DAG.getTargetConstant(Value, dl, TCVT); 15354 break; 15355 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15356 if (isInt<16>(-Value)) 15357 Result = DAG.getTargetConstant(Value, dl, TCVT); 15358 break; 15359 } 15360 break; 15361 } 15362 } 15363 15364 if (Result.getNode()) { 15365 Ops.push_back(Result); 15366 return; 15367 } 15368 15369 // Handle standard constraint letters. 15370 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15371 } 15372 15373 // isLegalAddressingMode - Return true if the addressing mode represented 15374 // by AM is legal for this target, for a load/store of the specified type. 15375 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15376 const AddrMode &AM, Type *Ty, 15377 unsigned AS, 15378 Instruction *I) const { 15379 // Vector type r+i form is supported since power9 as DQ form. We don't check 15380 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15381 // imm form is preferred and the offset can be adjusted to use imm form later 15382 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15383 // max offset to check legal addressing mode, we should be a little aggressive 15384 // to contain other offsets for that LSRUse. 15385 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15386 return false; 15387 15388 // PPC allows a sign-extended 16-bit immediate field. 15389 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15390 return false; 15391 15392 // No global is ever allowed as a base. 15393 if (AM.BaseGV) 15394 return false; 15395 15396 // PPC only support r+r, 15397 switch (AM.Scale) { 15398 case 0: // "r+i" or just "i", depending on HasBaseReg. 15399 break; 15400 case 1: 15401 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15402 return false; 15403 // Otherwise we have r+r or r+i. 15404 break; 15405 case 2: 15406 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15407 return false; 15408 // Allow 2*r as r+r. 15409 break; 15410 default: 15411 // No other scales are supported. 15412 return false; 15413 } 15414 15415 return true; 15416 } 15417 15418 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15419 SelectionDAG &DAG) const { 15420 MachineFunction &MF = DAG.getMachineFunction(); 15421 MachineFrameInfo &MFI = MF.getFrameInfo(); 15422 MFI.setReturnAddressIsTaken(true); 15423 15424 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15425 return SDValue(); 15426 15427 SDLoc dl(Op); 15428 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15429 15430 // Make sure the function does not optimize away the store of the RA to 15431 // the stack. 15432 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15433 FuncInfo->setLRStoreRequired(); 15434 bool isPPC64 = Subtarget.isPPC64(); 15435 auto PtrVT = getPointerTy(MF.getDataLayout()); 15436 15437 if (Depth > 0) { 15438 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15439 SDValue Offset = 15440 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15441 isPPC64 ? MVT::i64 : MVT::i32); 15442 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15443 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15444 MachinePointerInfo()); 15445 } 15446 15447 // Just load the return address off the stack. 15448 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15449 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15450 MachinePointerInfo()); 15451 } 15452 15453 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15454 SelectionDAG &DAG) const { 15455 SDLoc dl(Op); 15456 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15457 15458 MachineFunction &MF = DAG.getMachineFunction(); 15459 MachineFrameInfo &MFI = MF.getFrameInfo(); 15460 MFI.setFrameAddressIsTaken(true); 15461 15462 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15463 bool isPPC64 = PtrVT == MVT::i64; 15464 15465 // Naked functions never have a frame pointer, and so we use r1. For all 15466 // other functions, this decision must be delayed until during PEI. 15467 unsigned FrameReg; 15468 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15469 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15470 else 15471 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15472 15473 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15474 PtrVT); 15475 while (Depth--) 15476 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15477 FrameAddr, MachinePointerInfo()); 15478 return FrameAddr; 15479 } 15480 15481 // FIXME? Maybe this could be a TableGen attribute on some registers and 15482 // this table could be generated automatically from RegInfo. 15483 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15484 const MachineFunction &MF) const { 15485 bool isPPC64 = Subtarget.isPPC64(); 15486 15487 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15488 if (!is64Bit && VT != LLT::scalar(32)) 15489 report_fatal_error("Invalid register global variable type"); 15490 15491 Register Reg = StringSwitch<Register>(RegName) 15492 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15493 .Case("r2", isPPC64 ? Register() : PPC::R2) 15494 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15495 .Default(Register()); 15496 15497 if (Reg) 15498 return Reg; 15499 report_fatal_error("Invalid register name global variable"); 15500 } 15501 15502 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15503 // 32-bit SVR4 ABI access everything as got-indirect. 15504 if (Subtarget.is32BitELFABI()) 15505 return true; 15506 15507 // AIX accesses everything indirectly through the TOC, which is similar to 15508 // the GOT. 15509 if (Subtarget.isAIXABI()) 15510 return true; 15511 15512 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15513 // If it is small or large code model, module locals are accessed 15514 // indirectly by loading their address from .toc/.got. 15515 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15516 return true; 15517 15518 // JumpTable and BlockAddress are accessed as got-indirect. 15519 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15520 return true; 15521 15522 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15523 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15524 15525 return false; 15526 } 15527 15528 bool 15529 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15530 // The PowerPC target isn't yet aware of offsets. 15531 return false; 15532 } 15533 15534 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15535 const CallInst &I, 15536 MachineFunction &MF, 15537 unsigned Intrinsic) const { 15538 switch (Intrinsic) { 15539 case Intrinsic::ppc_altivec_lvx: 15540 case Intrinsic::ppc_altivec_lvxl: 15541 case Intrinsic::ppc_altivec_lvebx: 15542 case Intrinsic::ppc_altivec_lvehx: 15543 case Intrinsic::ppc_altivec_lvewx: 15544 case Intrinsic::ppc_vsx_lxvd2x: 15545 case Intrinsic::ppc_vsx_lxvw4x: { 15546 EVT VT; 15547 switch (Intrinsic) { 15548 case Intrinsic::ppc_altivec_lvebx: 15549 VT = MVT::i8; 15550 break; 15551 case Intrinsic::ppc_altivec_lvehx: 15552 VT = MVT::i16; 15553 break; 15554 case Intrinsic::ppc_altivec_lvewx: 15555 VT = MVT::i32; 15556 break; 15557 case Intrinsic::ppc_vsx_lxvd2x: 15558 VT = MVT::v2f64; 15559 break; 15560 default: 15561 VT = MVT::v4i32; 15562 break; 15563 } 15564 15565 Info.opc = ISD::INTRINSIC_W_CHAIN; 15566 Info.memVT = VT; 15567 Info.ptrVal = I.getArgOperand(0); 15568 Info.offset = -VT.getStoreSize()+1; 15569 Info.size = 2*VT.getStoreSize()-1; 15570 Info.align = Align(1); 15571 Info.flags = MachineMemOperand::MOLoad; 15572 return true; 15573 } 15574 case Intrinsic::ppc_altivec_stvx: 15575 case Intrinsic::ppc_altivec_stvxl: 15576 case Intrinsic::ppc_altivec_stvebx: 15577 case Intrinsic::ppc_altivec_stvehx: 15578 case Intrinsic::ppc_altivec_stvewx: 15579 case Intrinsic::ppc_vsx_stxvd2x: 15580 case Intrinsic::ppc_vsx_stxvw4x: { 15581 EVT VT; 15582 switch (Intrinsic) { 15583 case Intrinsic::ppc_altivec_stvebx: 15584 VT = MVT::i8; 15585 break; 15586 case Intrinsic::ppc_altivec_stvehx: 15587 VT = MVT::i16; 15588 break; 15589 case Intrinsic::ppc_altivec_stvewx: 15590 VT = MVT::i32; 15591 break; 15592 case Intrinsic::ppc_vsx_stxvd2x: 15593 VT = MVT::v2f64; 15594 break; 15595 default: 15596 VT = MVT::v4i32; 15597 break; 15598 } 15599 15600 Info.opc = ISD::INTRINSIC_VOID; 15601 Info.memVT = VT; 15602 Info.ptrVal = I.getArgOperand(1); 15603 Info.offset = -VT.getStoreSize()+1; 15604 Info.size = 2*VT.getStoreSize()-1; 15605 Info.align = Align(1); 15606 Info.flags = MachineMemOperand::MOStore; 15607 return true; 15608 } 15609 default: 15610 break; 15611 } 15612 15613 return false; 15614 } 15615 15616 /// It returns EVT::Other if the type should be determined using generic 15617 /// target-independent logic. 15618 EVT PPCTargetLowering::getOptimalMemOpType( 15619 const MemOp &Op, const AttributeList &FuncAttributes) const { 15620 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15621 // We should use Altivec/VSX loads and stores when available. For unaligned 15622 // addresses, unaligned VSX loads are only fast starting with the P8. 15623 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15624 (Op.isAligned(Align(16)) || 15625 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15626 return MVT::v4i32; 15627 } 15628 15629 if (Subtarget.isPPC64()) { 15630 return MVT::i64; 15631 } 15632 15633 return MVT::i32; 15634 } 15635 15636 /// Returns true if it is beneficial to convert a load of a constant 15637 /// to just the constant itself. 15638 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15639 Type *Ty) const { 15640 assert(Ty->isIntegerTy()); 15641 15642 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15643 return !(BitSize == 0 || BitSize > 64); 15644 } 15645 15646 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15647 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15648 return false; 15649 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15650 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15651 return NumBits1 == 64 && NumBits2 == 32; 15652 } 15653 15654 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15655 if (!VT1.isInteger() || !VT2.isInteger()) 15656 return false; 15657 unsigned NumBits1 = VT1.getSizeInBits(); 15658 unsigned NumBits2 = VT2.getSizeInBits(); 15659 return NumBits1 == 64 && NumBits2 == 32; 15660 } 15661 15662 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15663 // Generally speaking, zexts are not free, but they are free when they can be 15664 // folded with other operations. 15665 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15666 EVT MemVT = LD->getMemoryVT(); 15667 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15668 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15669 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15670 LD->getExtensionType() == ISD::ZEXTLOAD)) 15671 return true; 15672 } 15673 15674 // FIXME: Add other cases... 15675 // - 32-bit shifts with a zext to i64 15676 // - zext after ctlz, bswap, etc. 15677 // - zext after and by a constant mask 15678 15679 return TargetLowering::isZExtFree(Val, VT2); 15680 } 15681 15682 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15683 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15684 "invalid fpext types"); 15685 // Extending to float128 is not free. 15686 if (DestVT == MVT::f128) 15687 return false; 15688 return true; 15689 } 15690 15691 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15692 return isInt<16>(Imm) || isUInt<16>(Imm); 15693 } 15694 15695 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15696 return isInt<16>(Imm) || isUInt<16>(Imm); 15697 } 15698 15699 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15700 unsigned, 15701 unsigned, 15702 MachineMemOperand::Flags, 15703 bool *Fast) const { 15704 if (DisablePPCUnaligned) 15705 return false; 15706 15707 // PowerPC supports unaligned memory access for simple non-vector types. 15708 // Although accessing unaligned addresses is not as efficient as accessing 15709 // aligned addresses, it is generally more efficient than manual expansion, 15710 // and generally only traps for software emulation when crossing page 15711 // boundaries. 15712 15713 if (!VT.isSimple()) 15714 return false; 15715 15716 if (VT.isFloatingPoint() && !VT.isVector() && 15717 !Subtarget.allowsUnalignedFPAccess()) 15718 return false; 15719 15720 if (VT.getSimpleVT().isVector()) { 15721 if (Subtarget.hasVSX()) { 15722 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15723 VT != MVT::v4f32 && VT != MVT::v4i32) 15724 return false; 15725 } else { 15726 return false; 15727 } 15728 } 15729 15730 if (VT == MVT::ppcf128) 15731 return false; 15732 15733 if (Fast) 15734 *Fast = true; 15735 15736 return true; 15737 } 15738 15739 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15740 EVT VT) const { 15741 return isFMAFasterThanFMulAndFAdd( 15742 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15743 } 15744 15745 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15746 Type *Ty) const { 15747 switch (Ty->getScalarType()->getTypeID()) { 15748 case Type::FloatTyID: 15749 case Type::DoubleTyID: 15750 return true; 15751 case Type::FP128TyID: 15752 return Subtarget.hasP9Vector(); 15753 default: 15754 return false; 15755 } 15756 } 15757 15758 // FIXME: add more patterns which are not profitable to hoist. 15759 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15760 if (!I->hasOneUse()) 15761 return true; 15762 15763 Instruction *User = I->user_back(); 15764 assert(User && "A single use instruction with no uses."); 15765 15766 switch (I->getOpcode()) { 15767 case Instruction::FMul: { 15768 // Don't break FMA, PowerPC prefers FMA. 15769 if (User->getOpcode() != Instruction::FSub && 15770 User->getOpcode() != Instruction::FAdd) 15771 return true; 15772 15773 const TargetOptions &Options = getTargetMachine().Options; 15774 const Function *F = I->getFunction(); 15775 const DataLayout &DL = F->getParent()->getDataLayout(); 15776 Type *Ty = User->getOperand(0)->getType(); 15777 15778 return !( 15779 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15780 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15781 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15782 } 15783 case Instruction::Load: { 15784 // Don't break "store (load float*)" pattern, this pattern will be combined 15785 // to "store (load int32)" in later InstCombine pass. See function 15786 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15787 // cycles than loading a 32 bit integer. 15788 LoadInst *LI = cast<LoadInst>(I); 15789 // For the loads that combineLoadToOperationType does nothing, like 15790 // ordered load, it should be profitable to hoist them. 15791 // For swifterror load, it can only be used for pointer to pointer type, so 15792 // later type check should get rid of this case. 15793 if (!LI->isUnordered()) 15794 return true; 15795 15796 if (User->getOpcode() != Instruction::Store) 15797 return true; 15798 15799 if (I->getType()->getTypeID() != Type::FloatTyID) 15800 return true; 15801 15802 return false; 15803 } 15804 default: 15805 return true; 15806 } 15807 return true; 15808 } 15809 15810 const MCPhysReg * 15811 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15812 // LR is a callee-save register, but we must treat it as clobbered by any call 15813 // site. Hence we include LR in the scratch registers, which are in turn added 15814 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15815 // to CTR, which is used by any indirect call. 15816 static const MCPhysReg ScratchRegs[] = { 15817 PPC::X12, PPC::LR8, PPC::CTR8, 0 15818 }; 15819 15820 return ScratchRegs; 15821 } 15822 15823 Register PPCTargetLowering::getExceptionPointerRegister( 15824 const Constant *PersonalityFn) const { 15825 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15826 } 15827 15828 Register PPCTargetLowering::getExceptionSelectorRegister( 15829 const Constant *PersonalityFn) const { 15830 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15831 } 15832 15833 bool 15834 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15835 EVT VT , unsigned DefinedValues) const { 15836 if (VT == MVT::v2i64) 15837 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15838 15839 if (Subtarget.hasVSX()) 15840 return true; 15841 15842 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15843 } 15844 15845 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15846 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15847 return TargetLowering::getSchedulingPreference(N); 15848 15849 return Sched::ILP; 15850 } 15851 15852 // Create a fast isel object. 15853 FastISel * 15854 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15855 const TargetLibraryInfo *LibInfo) const { 15856 return PPC::createFastISel(FuncInfo, LibInfo); 15857 } 15858 15859 // 'Inverted' means the FMA opcode after negating one multiplicand. 15860 // For example, (fma -a b c) = (fnmsub a b c) 15861 static unsigned invertFMAOpcode(unsigned Opc) { 15862 switch (Opc) { 15863 default: 15864 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15865 case ISD::FMA: 15866 return PPCISD::FNMSUB; 15867 case PPCISD::FNMSUB: 15868 return ISD::FMA; 15869 } 15870 } 15871 15872 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15873 bool LegalOps, bool OptForSize, 15874 NegatibleCost &Cost, 15875 unsigned Depth) const { 15876 if (Depth > SelectionDAG::MaxRecursionDepth) 15877 return SDValue(); 15878 15879 unsigned Opc = Op.getOpcode(); 15880 EVT VT = Op.getValueType(); 15881 SDNodeFlags Flags = Op.getNode()->getFlags(); 15882 15883 switch (Opc) { 15884 case PPCISD::FNMSUB: 15885 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15886 break; 15887 15888 const TargetOptions &Options = getTargetMachine().Options; 15889 SDValue N0 = Op.getOperand(0); 15890 SDValue N1 = Op.getOperand(1); 15891 SDValue N2 = Op.getOperand(2); 15892 SDLoc Loc(Op); 15893 15894 NegatibleCost N2Cost = NegatibleCost::Expensive; 15895 SDValue NegN2 = 15896 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15897 15898 if (!NegN2) 15899 return SDValue(); 15900 15901 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 15902 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 15903 // These transformations may change sign of zeroes. For example, 15904 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 15905 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 15906 // Try and choose the cheaper one to negate. 15907 NegatibleCost N0Cost = NegatibleCost::Expensive; 15908 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 15909 N0Cost, Depth + 1); 15910 15911 NegatibleCost N1Cost = NegatibleCost::Expensive; 15912 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 15913 N1Cost, Depth + 1); 15914 15915 if (NegN0 && N0Cost <= N1Cost) { 15916 Cost = std::min(N0Cost, N2Cost); 15917 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 15918 } else if (NegN1) { 15919 Cost = std::min(N1Cost, N2Cost); 15920 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 15921 } 15922 } 15923 15924 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 15925 if (isOperationLegal(ISD::FMA, VT)) { 15926 Cost = N2Cost; 15927 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 15928 } 15929 15930 break; 15931 } 15932 15933 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 15934 Cost, Depth); 15935 } 15936 15937 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15938 bool PPCTargetLowering::useLoadStackGuardNode() const { 15939 if (!Subtarget.isTargetLinux()) 15940 return TargetLowering::useLoadStackGuardNode(); 15941 return true; 15942 } 15943 15944 // Override to disable global variable loading on Linux. 15945 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15946 if (!Subtarget.isTargetLinux()) 15947 return TargetLowering::insertSSPDeclarations(M); 15948 } 15949 15950 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15951 bool ForCodeSize) const { 15952 if (!VT.isSimple() || !Subtarget.hasVSX()) 15953 return false; 15954 15955 switch(VT.getSimpleVT().SimpleTy) { 15956 default: 15957 // For FP types that are currently not supported by PPC backend, return 15958 // false. Examples: f16, f80. 15959 return false; 15960 case MVT::f32: 15961 case MVT::f64: 15962 if (Subtarget.hasPrefixInstrs()) { 15963 // With prefixed instructions, we can materialize anything that can be 15964 // represented with a 32-bit immediate, not just positive zero. 15965 APFloat APFloatOfImm = Imm; 15966 return convertToNonDenormSingle(APFloatOfImm); 15967 } 15968 LLVM_FALLTHROUGH; 15969 case MVT::ppcf128: 15970 return Imm.isPosZero(); 15971 } 15972 } 15973 15974 // For vector shift operation op, fold 15975 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15976 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15977 SelectionDAG &DAG) { 15978 SDValue N0 = N->getOperand(0); 15979 SDValue N1 = N->getOperand(1); 15980 EVT VT = N0.getValueType(); 15981 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15982 unsigned Opcode = N->getOpcode(); 15983 unsigned TargetOpcode; 15984 15985 switch (Opcode) { 15986 default: 15987 llvm_unreachable("Unexpected shift operation"); 15988 case ISD::SHL: 15989 TargetOpcode = PPCISD::SHL; 15990 break; 15991 case ISD::SRL: 15992 TargetOpcode = PPCISD::SRL; 15993 break; 15994 case ISD::SRA: 15995 TargetOpcode = PPCISD::SRA; 15996 break; 15997 } 15998 15999 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 16000 N1->getOpcode() == ISD::AND) 16001 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 16002 if (Mask->getZExtValue() == OpSizeInBits - 1) 16003 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 16004 16005 return SDValue(); 16006 } 16007 16008 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 16009 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16010 return Value; 16011 16012 SDValue N0 = N->getOperand(0); 16013 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16014 if (!Subtarget.isISA3_0() || 16015 N0.getOpcode() != ISD::SIGN_EXTEND || 16016 N0.getOperand(0).getValueType() != MVT::i32 || 16017 CN1 == nullptr || N->getValueType(0) != MVT::i64) 16018 return SDValue(); 16019 16020 // We can't save an operation here if the value is already extended, and 16021 // the existing shift is easier to combine. 16022 SDValue ExtsSrc = N0.getOperand(0); 16023 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 16024 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 16025 return SDValue(); 16026 16027 SDLoc DL(N0); 16028 SDValue ShiftBy = SDValue(CN1, 0); 16029 // We want the shift amount to be i32 on the extswli, but the shift could 16030 // have an i64. 16031 if (ShiftBy.getValueType() == MVT::i64) 16032 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 16033 16034 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 16035 ShiftBy); 16036 } 16037 16038 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 16039 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16040 return Value; 16041 16042 return SDValue(); 16043 } 16044 16045 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 16046 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 16047 return Value; 16048 16049 return SDValue(); 16050 } 16051 16052 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 16053 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 16054 // When C is zero, the equation (addi Z, -C) can be simplified to Z 16055 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 16056 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 16057 const PPCSubtarget &Subtarget) { 16058 if (!Subtarget.isPPC64()) 16059 return SDValue(); 16060 16061 SDValue LHS = N->getOperand(0); 16062 SDValue RHS = N->getOperand(1); 16063 16064 auto isZextOfCompareWithConstant = [](SDValue Op) { 16065 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 16066 Op.getValueType() != MVT::i64) 16067 return false; 16068 16069 SDValue Cmp = Op.getOperand(0); 16070 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 16071 Cmp.getOperand(0).getValueType() != MVT::i64) 16072 return false; 16073 16074 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 16075 int64_t NegConstant = 0 - Constant->getSExtValue(); 16076 // Due to the limitations of the addi instruction, 16077 // -C is required to be [-32768, 32767]. 16078 return isInt<16>(NegConstant); 16079 } 16080 16081 return false; 16082 }; 16083 16084 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 16085 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 16086 16087 // If there is a pattern, canonicalize a zext operand to the RHS. 16088 if (LHSHasPattern && !RHSHasPattern) 16089 std::swap(LHS, RHS); 16090 else if (!LHSHasPattern && !RHSHasPattern) 16091 return SDValue(); 16092 16093 SDLoc DL(N); 16094 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 16095 SDValue Cmp = RHS.getOperand(0); 16096 SDValue Z = Cmp.getOperand(0); 16097 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 16098 16099 assert(Constant && "Constant Should not be a null pointer."); 16100 int64_t NegConstant = 0 - Constant->getSExtValue(); 16101 16102 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 16103 default: break; 16104 case ISD::SETNE: { 16105 // when C == 0 16106 // --> addze X, (addic Z, -1).carry 16107 // / 16108 // add X, (zext(setne Z, C))-- 16109 // \ when -32768 <= -C <= 32767 && C != 0 16110 // --> addze X, (addic (addi Z, -C), -1).carry 16111 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16112 DAG.getConstant(NegConstant, DL, MVT::i64)); 16113 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16114 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16115 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 16116 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16117 SDValue(Addc.getNode(), 1)); 16118 } 16119 case ISD::SETEQ: { 16120 // when C == 0 16121 // --> addze X, (subfic Z, 0).carry 16122 // / 16123 // add X, (zext(sete Z, C))-- 16124 // \ when -32768 <= -C <= 32767 && C != 0 16125 // --> addze X, (subfic (addi Z, -C), 0).carry 16126 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 16127 DAG.getConstant(NegConstant, DL, MVT::i64)); 16128 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 16129 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 16130 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 16131 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 16132 SDValue(Subc.getNode(), 1)); 16133 } 16134 } 16135 16136 return SDValue(); 16137 } 16138 16139 // Transform 16140 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 16141 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 16142 // In this case both C1 and C2 must be known constants. 16143 // C1+C2 must fit into a 34 bit signed integer. 16144 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 16145 const PPCSubtarget &Subtarget) { 16146 if (!Subtarget.isUsingPCRelativeCalls()) 16147 return SDValue(); 16148 16149 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 16150 // If we find that node try to cast the Global Address and the Constant. 16151 SDValue LHS = N->getOperand(0); 16152 SDValue RHS = N->getOperand(1); 16153 16154 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16155 std::swap(LHS, RHS); 16156 16157 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 16158 return SDValue(); 16159 16160 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16161 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16162 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16163 16164 // Check that both casts succeeded. 16165 if (!GSDN || !ConstNode) 16166 return SDValue(); 16167 16168 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16169 SDLoc DL(GSDN); 16170 16171 // The signed int offset needs to fit in 34 bits. 16172 if (!isInt<34>(NewOffset)) 16173 return SDValue(); 16174 16175 // The new global address is a copy of the old global address except 16176 // that it has the updated Offset. 16177 SDValue GA = 16178 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16179 NewOffset, GSDN->getTargetFlags()); 16180 SDValue MatPCRel = 16181 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16182 return MatPCRel; 16183 } 16184 16185 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16186 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16187 return Value; 16188 16189 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16190 return Value; 16191 16192 return SDValue(); 16193 } 16194 16195 // Detect TRUNCATE operations on bitcasts of float128 values. 16196 // What we are looking for here is the situtation where we extract a subset 16197 // of bits from a 128 bit float. 16198 // This can be of two forms: 16199 // 1) BITCAST of f128 feeding TRUNCATE 16200 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16201 // The reason this is required is because we do not have a legal i128 type 16202 // and so we want to prevent having to store the f128 and then reload part 16203 // of it. 16204 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16205 DAGCombinerInfo &DCI) const { 16206 // If we are using CRBits then try that first. 16207 if (Subtarget.useCRBits()) { 16208 // Check if CRBits did anything and return that if it did. 16209 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16210 return CRTruncValue; 16211 } 16212 16213 SDLoc dl(N); 16214 SDValue Op0 = N->getOperand(0); 16215 16216 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16217 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16218 EVT VT = N->getValueType(0); 16219 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16220 return SDValue(); 16221 SDValue Sub = Op0.getOperand(0); 16222 if (Sub.getOpcode() == ISD::SUB) { 16223 SDValue SubOp0 = Sub.getOperand(0); 16224 SDValue SubOp1 = Sub.getOperand(1); 16225 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16226 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16227 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16228 SubOp1.getOperand(0), 16229 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16230 } 16231 } 16232 } 16233 16234 // Looking for a truncate of i128 to i64. 16235 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16236 return SDValue(); 16237 16238 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16239 16240 // SRL feeding TRUNCATE. 16241 if (Op0.getOpcode() == ISD::SRL) { 16242 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16243 // The right shift has to be by 64 bits. 16244 if (!ConstNode || ConstNode->getZExtValue() != 64) 16245 return SDValue(); 16246 16247 // Switch the element number to extract. 16248 EltToExtract = EltToExtract ? 0 : 1; 16249 // Update Op0 past the SRL. 16250 Op0 = Op0.getOperand(0); 16251 } 16252 16253 // BITCAST feeding a TRUNCATE possibly via SRL. 16254 if (Op0.getOpcode() == ISD::BITCAST && 16255 Op0.getValueType() == MVT::i128 && 16256 Op0.getOperand(0).getValueType() == MVT::f128) { 16257 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16258 return DCI.DAG.getNode( 16259 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16260 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16261 } 16262 return SDValue(); 16263 } 16264 16265 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16266 SelectionDAG &DAG = DCI.DAG; 16267 16268 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16269 if (!ConstOpOrElement) 16270 return SDValue(); 16271 16272 // An imul is usually smaller than the alternative sequence for legal type. 16273 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16274 isOperationLegal(ISD::MUL, N->getValueType(0))) 16275 return SDValue(); 16276 16277 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16278 switch (this->Subtarget.getCPUDirective()) { 16279 default: 16280 // TODO: enhance the condition for subtarget before pwr8 16281 return false; 16282 case PPC::DIR_PWR8: 16283 // type mul add shl 16284 // scalar 4 1 1 16285 // vector 7 2 2 16286 return true; 16287 case PPC::DIR_PWR9: 16288 case PPC::DIR_PWR10: 16289 case PPC::DIR_PWR_FUTURE: 16290 // type mul add shl 16291 // scalar 5 2 2 16292 // vector 7 2 2 16293 16294 // The cycle RATIO of related operations are showed as a table above. 16295 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16296 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16297 // are 4, it is always profitable; but for 3 instrs patterns 16298 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16299 // So we should only do it for vector type. 16300 return IsAddOne && IsNeg ? VT.isVector() : true; 16301 } 16302 }; 16303 16304 EVT VT = N->getValueType(0); 16305 SDLoc DL(N); 16306 16307 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16308 bool IsNeg = MulAmt.isNegative(); 16309 APInt MulAmtAbs = MulAmt.abs(); 16310 16311 if ((MulAmtAbs - 1).isPowerOf2()) { 16312 // (mul x, 2^N + 1) => (add (shl x, N), x) 16313 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16314 16315 if (!IsProfitable(IsNeg, true, VT)) 16316 return SDValue(); 16317 16318 SDValue Op0 = N->getOperand(0); 16319 SDValue Op1 = 16320 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16321 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16322 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16323 16324 if (!IsNeg) 16325 return Res; 16326 16327 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16328 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16329 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16330 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16331 16332 if (!IsProfitable(IsNeg, false, VT)) 16333 return SDValue(); 16334 16335 SDValue Op0 = N->getOperand(0); 16336 SDValue Op1 = 16337 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16338 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16339 16340 if (!IsNeg) 16341 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16342 else 16343 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16344 16345 } else { 16346 return SDValue(); 16347 } 16348 } 16349 16350 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16351 // in combiner since we need to check SD flags and other subtarget features. 16352 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16353 DAGCombinerInfo &DCI) const { 16354 SDValue N0 = N->getOperand(0); 16355 SDValue N1 = N->getOperand(1); 16356 SDValue N2 = N->getOperand(2); 16357 SDNodeFlags Flags = N->getFlags(); 16358 EVT VT = N->getValueType(0); 16359 SelectionDAG &DAG = DCI.DAG; 16360 const TargetOptions &Options = getTargetMachine().Options; 16361 unsigned Opc = N->getOpcode(); 16362 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16363 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16364 SDLoc Loc(N); 16365 16366 if (!isOperationLegal(ISD::FMA, VT)) 16367 return SDValue(); 16368 16369 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16370 // since (fnmsub a b c)=-0 while c-ab=+0. 16371 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16372 return SDValue(); 16373 16374 // (fma (fneg a) b c) => (fnmsub a b c) 16375 // (fnmsub (fneg a) b c) => (fma a b c) 16376 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16377 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16378 16379 // (fma a (fneg b) c) => (fnmsub a b c) 16380 // (fnmsub a (fneg b) c) => (fma a b c) 16381 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16382 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16383 16384 return SDValue(); 16385 } 16386 16387 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16388 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16389 if (!Subtarget.is64BitELFABI()) 16390 return false; 16391 16392 // If not a tail call then no need to proceed. 16393 if (!CI->isTailCall()) 16394 return false; 16395 16396 // If sibling calls have been disabled and tail-calls aren't guaranteed 16397 // there is no reason to duplicate. 16398 auto &TM = getTargetMachine(); 16399 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16400 return false; 16401 16402 // Can't tail call a function called indirectly, or if it has variadic args. 16403 const Function *Callee = CI->getCalledFunction(); 16404 if (!Callee || Callee->isVarArg()) 16405 return false; 16406 16407 // Make sure the callee and caller calling conventions are eligible for tco. 16408 const Function *Caller = CI->getParent()->getParent(); 16409 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16410 CI->getCallingConv())) 16411 return false; 16412 16413 // If the function is local then we have a good chance at tail-calling it 16414 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16415 } 16416 16417 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16418 if (!Subtarget.hasVSX()) 16419 return false; 16420 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16421 return true; 16422 return VT == MVT::f32 || VT == MVT::f64 || 16423 VT == MVT::v4f32 || VT == MVT::v2f64; 16424 } 16425 16426 bool PPCTargetLowering:: 16427 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16428 const Value *Mask = AndI.getOperand(1); 16429 // If the mask is suitable for andi. or andis. we should sink the and. 16430 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16431 // Can't handle constants wider than 64-bits. 16432 if (CI->getBitWidth() > 64) 16433 return false; 16434 int64_t ConstVal = CI->getZExtValue(); 16435 return isUInt<16>(ConstVal) || 16436 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16437 } 16438 16439 // For non-constant masks, we can always use the record-form and. 16440 return true; 16441 } 16442 16443 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16444 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16445 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16446 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16447 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16448 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16449 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16450 assert(Subtarget.hasP9Altivec() && 16451 "Only combine this when P9 altivec supported!"); 16452 EVT VT = N->getValueType(0); 16453 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16454 return SDValue(); 16455 16456 SelectionDAG &DAG = DCI.DAG; 16457 SDLoc dl(N); 16458 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16459 // Even for signed integers, if it's known to be positive (as signed 16460 // integer) due to zero-extended inputs. 16461 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16462 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16463 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16464 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16465 (SubOpcd1 == ISD::ZERO_EXTEND || 16466 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16467 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16468 N->getOperand(0)->getOperand(0), 16469 N->getOperand(0)->getOperand(1), 16470 DAG.getTargetConstant(0, dl, MVT::i32)); 16471 } 16472 16473 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16474 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16475 N->getOperand(0).hasOneUse()) { 16476 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16477 N->getOperand(0)->getOperand(0), 16478 N->getOperand(0)->getOperand(1), 16479 DAG.getTargetConstant(1, dl, MVT::i32)); 16480 } 16481 } 16482 16483 return SDValue(); 16484 } 16485 16486 // For type v4i32/v8ii16/v16i8, transform 16487 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16488 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16489 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16490 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16491 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16492 DAGCombinerInfo &DCI) const { 16493 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16494 assert(Subtarget.hasP9Altivec() && 16495 "Only combine this when P9 altivec supported!"); 16496 16497 SelectionDAG &DAG = DCI.DAG; 16498 SDLoc dl(N); 16499 SDValue Cond = N->getOperand(0); 16500 SDValue TrueOpnd = N->getOperand(1); 16501 SDValue FalseOpnd = N->getOperand(2); 16502 EVT VT = N->getOperand(1).getValueType(); 16503 16504 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16505 FalseOpnd.getOpcode() != ISD::SUB) 16506 return SDValue(); 16507 16508 // ABSD only available for type v4i32/v8i16/v16i8 16509 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16510 return SDValue(); 16511 16512 // At least to save one more dependent computation 16513 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16514 return SDValue(); 16515 16516 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16517 16518 // Can only handle unsigned comparison here 16519 switch (CC) { 16520 default: 16521 return SDValue(); 16522 case ISD::SETUGT: 16523 case ISD::SETUGE: 16524 break; 16525 case ISD::SETULT: 16526 case ISD::SETULE: 16527 std::swap(TrueOpnd, FalseOpnd); 16528 break; 16529 } 16530 16531 SDValue CmpOpnd1 = Cond.getOperand(0); 16532 SDValue CmpOpnd2 = Cond.getOperand(1); 16533 16534 // SETCC CmpOpnd1 CmpOpnd2 cond 16535 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16536 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16537 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16538 TrueOpnd.getOperand(1) == CmpOpnd2 && 16539 FalseOpnd.getOperand(0) == CmpOpnd2 && 16540 FalseOpnd.getOperand(1) == CmpOpnd1) { 16541 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16542 CmpOpnd1, CmpOpnd2, 16543 DAG.getTargetConstant(0, dl, MVT::i32)); 16544 } 16545 16546 return SDValue(); 16547 } 16548