1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/IntrinsicsPowerPC.h" 70 #include "llvm/IR/Module.h" 71 #include "llvm/IR/Type.h" 72 #include "llvm/IR/Use.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/MC/MCContext.h" 75 #include "llvm/MC/MCExpr.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/MC/MCSectionXCOFF.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> EnablePPCPCRelTLS( 125 "enable-ppc-pcrel-tls", 126 cl::desc("enable the use of PC relative memops in TLS instructions on PPC"), 127 cl::Hidden); 128 129 STATISTIC(NumTailCalls, "Number of tail calls"); 130 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM"); 132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 133 134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 135 136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 137 138 // FIXME: Remove this once the bug has been fixed! 139 extern cl::opt<bool> ANDIGlueBug; 140 141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 142 const PPCSubtarget &STI) 143 : TargetLowering(TM), Subtarget(STI) { 144 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 145 // arguments are at least 4/8 bytes aligned. 146 bool isPPC64 = Subtarget.isPPC64(); 147 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 148 149 // Set up the register classes. 150 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 151 if (!useSoftFloat()) { 152 if (hasSPE()) { 153 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 154 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 155 } else { 156 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 157 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 158 } 159 } 160 161 // Match BITREVERSE to customized fast code sequence in the td file. 162 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 163 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 164 165 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 166 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 167 168 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 169 for (MVT VT : MVT::integer_valuetypes()) { 170 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 172 } 173 174 if (Subtarget.isISA3_0()) { 175 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 177 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 178 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 179 } else { 180 // No extending loads from f16 or HW conversions back and forth. 181 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 182 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 183 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 184 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 185 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 186 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 187 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 188 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 189 } 190 191 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 192 193 // PowerPC has pre-inc load and store's. 194 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 195 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 196 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 197 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 198 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 199 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 200 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 201 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 202 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 203 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 204 if (!Subtarget.hasSPE()) { 205 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 206 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 207 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 208 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 209 } 210 211 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 212 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 213 for (MVT VT : ScalarIntVTs) { 214 setOperationAction(ISD::ADDC, VT, Legal); 215 setOperationAction(ISD::ADDE, VT, Legal); 216 setOperationAction(ISD::SUBC, VT, Legal); 217 setOperationAction(ISD::SUBE, VT, Legal); 218 } 219 220 if (Subtarget.useCRBits()) { 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 222 223 if (isPPC64 || Subtarget.hasFPCVT()) { 224 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 225 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 226 isPPC64 ? MVT::i64 : MVT::i32); 227 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 228 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 229 isPPC64 ? MVT::i64 : MVT::i32); 230 } else { 231 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 232 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 233 } 234 235 // PowerPC does not support direct load/store of condition registers. 236 setOperationAction(ISD::LOAD, MVT::i1, Custom); 237 setOperationAction(ISD::STORE, MVT::i1, Custom); 238 239 // FIXME: Remove this once the ANDI glue bug is fixed: 240 if (ANDIGlueBug) 241 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 242 243 for (MVT VT : MVT::integer_valuetypes()) { 244 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 245 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 246 setTruncStoreAction(VT, MVT::i1, Expand); 247 } 248 249 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 250 } 251 252 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 253 // PPC (the libcall is not available). 254 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 255 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 256 257 // We do not currently implement these libm ops for PowerPC. 258 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 259 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 260 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 261 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 262 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 263 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 264 265 // PowerPC has no SREM/UREM instructions unless we are on P9 266 // On P9 we may use a hardware instruction to compute the remainder. 267 // When the result of both the remainder and the division is required it is 268 // more efficient to compute the remainder from the result of the division 269 // rather than use the remainder instruction. The instructions are legalized 270 // directly because the DivRemPairsPass performs the transformation at the IR 271 // level. 272 if (Subtarget.isISA3_0()) { 273 setOperationAction(ISD::SREM, MVT::i32, Legal); 274 setOperationAction(ISD::UREM, MVT::i32, Legal); 275 setOperationAction(ISD::SREM, MVT::i64, Legal); 276 setOperationAction(ISD::UREM, MVT::i64, Legal); 277 } else { 278 setOperationAction(ISD::SREM, MVT::i32, Expand); 279 setOperationAction(ISD::UREM, MVT::i32, Expand); 280 setOperationAction(ISD::SREM, MVT::i64, Expand); 281 setOperationAction(ISD::UREM, MVT::i64, Expand); 282 } 283 284 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 285 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 286 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 287 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 288 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 289 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 290 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 291 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 292 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 293 294 // Handle constrained floating-point operations of scalar. 295 // TODO: Handle SPE specific operation. 296 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 297 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 298 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 299 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 300 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 301 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 302 303 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 304 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 305 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 306 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 307 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 308 if (Subtarget.hasVSX()) 309 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal); 310 311 if (Subtarget.hasFSQRT()) { 312 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 313 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 314 } 315 316 if (Subtarget.hasFPRND()) { 317 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 318 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 319 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 320 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 321 322 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 323 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 324 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 325 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 326 } 327 328 // We don't support sin/cos/sqrt/fmod/pow 329 setOperationAction(ISD::FSIN , MVT::f64, Expand); 330 setOperationAction(ISD::FCOS , MVT::f64, Expand); 331 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 332 setOperationAction(ISD::FREM , MVT::f64, Expand); 333 setOperationAction(ISD::FPOW , MVT::f64, Expand); 334 setOperationAction(ISD::FSIN , MVT::f32, Expand); 335 setOperationAction(ISD::FCOS , MVT::f32, Expand); 336 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 337 setOperationAction(ISD::FREM , MVT::f32, Expand); 338 setOperationAction(ISD::FPOW , MVT::f32, Expand); 339 if (Subtarget.hasSPE()) { 340 setOperationAction(ISD::FMA , MVT::f64, Expand); 341 setOperationAction(ISD::FMA , MVT::f32, Expand); 342 } else { 343 setOperationAction(ISD::FMA , MVT::f64, Legal); 344 setOperationAction(ISD::FMA , MVT::f32, Legal); 345 } 346 347 if (Subtarget.hasSPE()) 348 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 349 350 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 351 352 // If we're enabling GP optimizations, use hardware square root 353 if (!Subtarget.hasFSQRT() && 354 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 355 Subtarget.hasFRE())) 356 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 357 358 if (!Subtarget.hasFSQRT() && 359 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 360 Subtarget.hasFRES())) 361 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 362 363 if (Subtarget.hasFCPSGN()) { 364 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 365 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 366 } else { 367 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 368 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 369 } 370 371 if (Subtarget.hasFPRND()) { 372 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 373 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 374 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 375 setOperationAction(ISD::FROUND, MVT::f64, Legal); 376 377 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 378 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 379 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 380 setOperationAction(ISD::FROUND, MVT::f32, Legal); 381 } 382 383 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 384 // to speed up scalar BSWAP64. 385 // CTPOP or CTTZ were introduced in P8/P9 respectively 386 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 387 if (Subtarget.hasP9Vector()) 388 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 389 else 390 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 391 if (Subtarget.isISA3_0()) { 392 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 393 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 394 } else { 395 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 396 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 397 } 398 399 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 400 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 401 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 402 } else { 403 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 404 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 405 } 406 407 // PowerPC does not have ROTR 408 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 409 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 410 411 if (!Subtarget.useCRBits()) { 412 // PowerPC does not have Select 413 setOperationAction(ISD::SELECT, MVT::i32, Expand); 414 setOperationAction(ISD::SELECT, MVT::i64, Expand); 415 setOperationAction(ISD::SELECT, MVT::f32, Expand); 416 setOperationAction(ISD::SELECT, MVT::f64, Expand); 417 } 418 419 // PowerPC wants to turn select_cc of FP into fsel when possible. 420 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 421 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 422 423 // PowerPC wants to optimize integer setcc a bit 424 if (!Subtarget.useCRBits()) 425 setOperationAction(ISD::SETCC, MVT::i32, Custom); 426 427 if (Subtarget.hasFPU()) { 428 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 429 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 430 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 431 432 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 433 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 434 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 435 } 436 437 // PowerPC does not have BRCOND which requires SetCC 438 if (!Subtarget.useCRBits()) 439 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 440 441 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 442 443 if (Subtarget.hasSPE()) { 444 // SPE has built-in conversions 445 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 446 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 447 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 448 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 449 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 450 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 451 } else { 452 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 453 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 454 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 455 456 // PowerPC does not have [U|S]INT_TO_FP 457 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 458 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 459 } 460 461 if (Subtarget.hasDirectMove() && isPPC64) { 462 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 463 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 464 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 465 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 466 if (TM.Options.UnsafeFPMath) { 467 setOperationAction(ISD::LRINT, MVT::f64, Legal); 468 setOperationAction(ISD::LRINT, MVT::f32, Legal); 469 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 470 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 471 setOperationAction(ISD::LROUND, MVT::f64, Legal); 472 setOperationAction(ISD::LROUND, MVT::f32, Legal); 473 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 474 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 475 } 476 } else { 477 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 478 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 479 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 480 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 481 } 482 483 // We cannot sextinreg(i1). Expand to shifts. 484 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 485 486 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 487 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 488 // support continuation, user-level threading, and etc.. As a result, no 489 // other SjLj exception interfaces are implemented and please don't build 490 // your own exception handling based on them. 491 // LLVM/Clang supports zero-cost DWARF exception handling. 492 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 493 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 494 495 // We want to legalize GlobalAddress and ConstantPool nodes into the 496 // appropriate instructions to materialize the address. 497 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 498 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 499 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 500 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 501 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 502 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 503 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 504 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 505 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 506 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 507 508 // TRAP is legal. 509 setOperationAction(ISD::TRAP, MVT::Other, Legal); 510 511 // TRAMPOLINE is custom lowered. 512 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 513 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 514 515 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 516 setOperationAction(ISD::VASTART , MVT::Other, Custom); 517 518 if (Subtarget.is64BitELFABI()) { 519 // VAARG always uses double-word chunks, so promote anything smaller. 520 setOperationAction(ISD::VAARG, MVT::i1, Promote); 521 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 522 setOperationAction(ISD::VAARG, MVT::i8, Promote); 523 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 524 setOperationAction(ISD::VAARG, MVT::i16, Promote); 525 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 526 setOperationAction(ISD::VAARG, MVT::i32, Promote); 527 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 528 setOperationAction(ISD::VAARG, MVT::Other, Expand); 529 } else if (Subtarget.is32BitELFABI()) { 530 // VAARG is custom lowered with the 32-bit SVR4 ABI. 531 setOperationAction(ISD::VAARG, MVT::Other, Custom); 532 setOperationAction(ISD::VAARG, MVT::i64, Custom); 533 } else 534 setOperationAction(ISD::VAARG, MVT::Other, Expand); 535 536 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 537 if (Subtarget.is32BitELFABI()) 538 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 539 else 540 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 541 542 // Use the default implementation. 543 setOperationAction(ISD::VAEND , MVT::Other, Expand); 544 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 545 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 546 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 547 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 548 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 549 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 550 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 551 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 552 553 // We want to custom lower some of our intrinsics. 554 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 555 556 // To handle counter-based loop conditions. 557 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 558 559 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 560 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 561 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 562 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 563 564 // Comparisons that require checking two conditions. 565 if (Subtarget.hasSPE()) { 566 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 567 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 568 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 569 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 570 } 571 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 572 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 573 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 574 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 575 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 576 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 577 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 578 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 579 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 580 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 581 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 582 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 583 584 if (Subtarget.has64BitSupport()) { 585 // They also have instructions for converting between i64 and fp. 586 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 587 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 588 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 589 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 590 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 591 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 592 // This is just the low 32 bits of a (signed) fp->i64 conversion. 593 // We cannot do this with Promote because i64 is not a legal type. 594 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 595 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 596 597 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 598 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 599 } else { 600 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 601 if (Subtarget.hasSPE()) { 602 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 603 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 604 } else { 605 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 606 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 607 } 608 } 609 610 // With the instructions enabled under FPCVT, we can do everything. 611 if (Subtarget.hasFPCVT()) { 612 if (Subtarget.has64BitSupport()) { 613 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 614 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 615 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 616 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 617 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 618 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 619 } 620 621 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 622 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 623 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 624 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 625 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 626 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 627 } 628 629 if (Subtarget.use64BitRegs()) { 630 // 64-bit PowerPC implementations can support i64 types directly 631 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 632 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 633 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 634 // 64-bit PowerPC wants to expand i128 shifts itself. 635 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 636 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 637 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 638 } else { 639 // 32-bit PowerPC wants to expand i64 shifts itself. 640 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 641 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 642 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 643 } 644 645 // PowerPC has better expansions for funnel shifts than the generic 646 // TargetLowering::expandFunnelShift. 647 if (Subtarget.has64BitSupport()) { 648 setOperationAction(ISD::FSHL, MVT::i64, Custom); 649 setOperationAction(ISD::FSHR, MVT::i64, Custom); 650 } 651 setOperationAction(ISD::FSHL, MVT::i32, Custom); 652 setOperationAction(ISD::FSHR, MVT::i32, Custom); 653 654 if (Subtarget.hasVSX()) { 655 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 656 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 657 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 658 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 659 } 660 661 if (Subtarget.hasAltivec()) { 662 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 663 setOperationAction(ISD::SADDSAT, VT, Legal); 664 setOperationAction(ISD::SSUBSAT, VT, Legal); 665 setOperationAction(ISD::UADDSAT, VT, Legal); 666 setOperationAction(ISD::USUBSAT, VT, Legal); 667 } 668 // First set operation action for all vector types to expand. Then we 669 // will selectively turn on ones that can be effectively codegen'd. 670 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 671 // add/sub are legal for all supported vector VT's. 672 setOperationAction(ISD::ADD, VT, Legal); 673 setOperationAction(ISD::SUB, VT, Legal); 674 675 // For v2i64, these are only valid with P8Vector. This is corrected after 676 // the loop. 677 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 678 setOperationAction(ISD::SMAX, VT, Legal); 679 setOperationAction(ISD::SMIN, VT, Legal); 680 setOperationAction(ISD::UMAX, VT, Legal); 681 setOperationAction(ISD::UMIN, VT, Legal); 682 } 683 else { 684 setOperationAction(ISD::SMAX, VT, Expand); 685 setOperationAction(ISD::SMIN, VT, Expand); 686 setOperationAction(ISD::UMAX, VT, Expand); 687 setOperationAction(ISD::UMIN, VT, Expand); 688 } 689 690 if (Subtarget.hasVSX()) { 691 setOperationAction(ISD::FMAXNUM, VT, Legal); 692 setOperationAction(ISD::FMINNUM, VT, Legal); 693 } 694 695 // Vector instructions introduced in P8 696 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 697 setOperationAction(ISD::CTPOP, VT, Legal); 698 setOperationAction(ISD::CTLZ, VT, Legal); 699 } 700 else { 701 setOperationAction(ISD::CTPOP, VT, Expand); 702 setOperationAction(ISD::CTLZ, VT, Expand); 703 } 704 705 // Vector instructions introduced in P9 706 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 707 setOperationAction(ISD::CTTZ, VT, Legal); 708 else 709 setOperationAction(ISD::CTTZ, VT, Expand); 710 711 // We promote all shuffles to v16i8. 712 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 713 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 714 715 // We promote all non-typed operations to v4i32. 716 setOperationAction(ISD::AND , VT, Promote); 717 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 718 setOperationAction(ISD::OR , VT, Promote); 719 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 720 setOperationAction(ISD::XOR , VT, Promote); 721 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 722 setOperationAction(ISD::LOAD , VT, Promote); 723 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 724 setOperationAction(ISD::SELECT, VT, Promote); 725 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 726 setOperationAction(ISD::VSELECT, VT, Legal); 727 setOperationAction(ISD::SELECT_CC, VT, Promote); 728 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 729 setOperationAction(ISD::STORE, VT, Promote); 730 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 731 732 // No other operations are legal. 733 setOperationAction(ISD::MUL , VT, Expand); 734 setOperationAction(ISD::SDIV, VT, Expand); 735 setOperationAction(ISD::SREM, VT, Expand); 736 setOperationAction(ISD::UDIV, VT, Expand); 737 setOperationAction(ISD::UREM, VT, Expand); 738 setOperationAction(ISD::FDIV, VT, Expand); 739 setOperationAction(ISD::FREM, VT, Expand); 740 setOperationAction(ISD::FNEG, VT, Expand); 741 setOperationAction(ISD::FSQRT, VT, Expand); 742 setOperationAction(ISD::FLOG, VT, Expand); 743 setOperationAction(ISD::FLOG10, VT, Expand); 744 setOperationAction(ISD::FLOG2, VT, Expand); 745 setOperationAction(ISD::FEXP, VT, Expand); 746 setOperationAction(ISD::FEXP2, VT, Expand); 747 setOperationAction(ISD::FSIN, VT, Expand); 748 setOperationAction(ISD::FCOS, VT, Expand); 749 setOperationAction(ISD::FABS, VT, Expand); 750 setOperationAction(ISD::FFLOOR, VT, Expand); 751 setOperationAction(ISD::FCEIL, VT, Expand); 752 setOperationAction(ISD::FTRUNC, VT, Expand); 753 setOperationAction(ISD::FRINT, VT, Expand); 754 setOperationAction(ISD::FNEARBYINT, VT, Expand); 755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 756 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 757 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 758 setOperationAction(ISD::MULHU, VT, Expand); 759 setOperationAction(ISD::MULHS, VT, Expand); 760 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 761 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 762 setOperationAction(ISD::UDIVREM, VT, Expand); 763 setOperationAction(ISD::SDIVREM, VT, Expand); 764 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 765 setOperationAction(ISD::FPOW, VT, Expand); 766 setOperationAction(ISD::BSWAP, VT, Expand); 767 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 768 setOperationAction(ISD::ROTL, VT, Expand); 769 setOperationAction(ISD::ROTR, VT, Expand); 770 771 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 772 setTruncStoreAction(VT, InnerVT, Expand); 773 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 774 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 775 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 776 } 777 } 778 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 779 if (!Subtarget.hasP8Vector()) { 780 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 781 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 782 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 783 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 784 } 785 786 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 787 setOperationAction(ISD::ABS, VT, Custom); 788 789 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 790 // with merges, splats, etc. 791 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 792 793 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 794 // are cheap, so handle them before they get expanded to scalar. 795 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 796 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 797 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 798 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 799 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 800 801 setOperationAction(ISD::AND , MVT::v4i32, Legal); 802 setOperationAction(ISD::OR , MVT::v4i32, Legal); 803 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 804 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 805 setOperationAction(ISD::SELECT, MVT::v4i32, 806 Subtarget.useCRBits() ? Legal : Expand); 807 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 808 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 809 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 810 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 811 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 812 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 813 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 814 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 815 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 816 817 // Without hasP8Altivec set, v2i64 SMAX isn't available. 818 // But ABS custom lowering requires SMAX support. 819 if (!Subtarget.hasP8Altivec()) 820 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 821 822 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 823 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 824 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 825 if (Subtarget.hasAltivec()) 826 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 827 setOperationAction(ISD::ROTL, VT, Legal); 828 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 829 if (Subtarget.hasP8Altivec()) 830 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 831 832 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 833 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 834 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 835 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 836 837 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 838 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 839 840 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 841 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 842 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 843 } 844 845 if (Subtarget.hasP8Altivec()) 846 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 847 else 848 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 849 850 if (Subtarget.isISA3_1()) { 851 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 852 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 853 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 854 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 855 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 856 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 857 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 858 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 859 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 860 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 861 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 862 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 863 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 864 } 865 866 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 867 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 868 869 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 870 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 871 872 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 873 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 874 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 875 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 876 877 // Altivec does not contain unordered floating-point compare instructions 878 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 879 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 880 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 881 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 882 883 if (Subtarget.hasVSX()) { 884 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 885 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 886 if (Subtarget.hasP8Vector()) { 887 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 889 } 890 if (Subtarget.hasDirectMove() && isPPC64) { 891 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 892 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 896 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 897 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 899 } 900 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 901 902 // The nearbyint variants are not allowed to raise the inexact exception 903 // so we can only code-gen them with unsafe math. 904 if (TM.Options.UnsafeFPMath) { 905 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 906 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 907 } 908 909 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 910 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 911 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 912 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 913 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 914 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 915 setOperationAction(ISD::FROUND, MVT::f64, Legal); 916 setOperationAction(ISD::FRINT, MVT::f64, Legal); 917 918 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 919 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 920 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 921 setOperationAction(ISD::FROUND, MVT::f32, Legal); 922 setOperationAction(ISD::FRINT, MVT::f32, Legal); 923 924 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 925 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 926 927 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 928 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 929 930 // Share the Altivec comparison restrictions. 931 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 932 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 933 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 934 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 935 936 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 937 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 938 939 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 940 941 if (Subtarget.hasP8Vector()) 942 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 943 944 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 945 946 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 947 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 948 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 949 950 if (Subtarget.hasP8Altivec()) { 951 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 952 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 953 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 954 955 // 128 bit shifts can be accomplished via 3 instructions for SHL and 956 // SRL, but not for SRA because of the instructions available: 957 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 958 // doing 959 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 960 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 961 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 962 963 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 964 } 965 else { 966 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 967 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 968 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 969 970 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 971 972 // VSX v2i64 only supports non-arithmetic operations. 973 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 974 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 975 } 976 977 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 978 979 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 980 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 981 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 982 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 983 984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 985 986 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 987 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 988 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 989 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 990 991 // Custom handling for partial vectors of integers converted to 992 // floating point. We already have optimal handling for v2i32 through 993 // the DAG combine, so those aren't necessary. 994 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 995 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 996 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 997 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 998 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 999 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1000 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1001 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1002 1003 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1004 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1005 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1006 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1007 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1008 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1009 1010 if (Subtarget.hasDirectMove()) 1011 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1012 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1013 1014 // Handle constrained floating-point operations of vector. 1015 // The predictor is `hasVSX` because altivec instruction has 1016 // no exception but VSX vector instruction has. 1017 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1018 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1019 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1020 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1021 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1022 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1023 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1024 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1025 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal); 1026 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1027 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1028 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1029 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1030 1031 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1032 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1033 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1034 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1035 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1036 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1037 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1038 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1039 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal); 1040 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1041 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1042 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1043 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1044 1045 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1046 } 1047 1048 if (Subtarget.hasP8Altivec()) { 1049 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1050 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1051 } 1052 1053 if (Subtarget.hasP9Vector()) { 1054 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1055 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1056 1057 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1058 // SRL, but not for SRA because of the instructions available: 1059 // VS{RL} and VS{RL}O. 1060 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1061 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1062 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1063 1064 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1065 setOperationAction(ISD::FADD, MVT::f128, Legal); 1066 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1067 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1068 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1069 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1070 // No extending loads to f128 on PPC. 1071 for (MVT FPT : MVT::fp_valuetypes()) 1072 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1073 setOperationAction(ISD::FMA, MVT::f128, Legal); 1074 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1075 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1076 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1077 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1078 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1079 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1080 1081 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1082 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1083 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1084 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1085 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1086 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1087 1088 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1089 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1090 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1091 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1092 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1093 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1094 // No implementation for these ops for PowerPC. 1095 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1096 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1097 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1098 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1099 setOperationAction(ISD::FREM, MVT::f128, Expand); 1100 1101 // Handle constrained floating-point operations of fp128 1102 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1103 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1104 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1105 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1106 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1107 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1108 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1109 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1110 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1111 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1112 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1113 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1114 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1115 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1116 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1117 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1118 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1119 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1120 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1121 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1122 } 1123 1124 if (Subtarget.hasP9Altivec()) { 1125 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1127 1128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1130 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1133 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1134 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1135 } 1136 } 1137 1138 if (Subtarget.has64BitSupport()) 1139 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1140 1141 if (Subtarget.isISA3_1()) 1142 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1143 1144 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1145 1146 if (!isPPC64) { 1147 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1148 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1149 } 1150 1151 setBooleanContents(ZeroOrOneBooleanContent); 1152 1153 if (Subtarget.hasAltivec()) { 1154 // Altivec instructions set fields to all zeros or all ones. 1155 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1156 } 1157 1158 if (!isPPC64) { 1159 // These libcalls are not available in 32-bit. 1160 setLibcallName(RTLIB::SHL_I128, nullptr); 1161 setLibcallName(RTLIB::SRL_I128, nullptr); 1162 setLibcallName(RTLIB::SRA_I128, nullptr); 1163 } 1164 1165 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1166 1167 // We have target-specific dag combine patterns for the following nodes: 1168 setTargetDAGCombine(ISD::ADD); 1169 setTargetDAGCombine(ISD::SHL); 1170 setTargetDAGCombine(ISD::SRA); 1171 setTargetDAGCombine(ISD::SRL); 1172 setTargetDAGCombine(ISD::MUL); 1173 setTargetDAGCombine(ISD::FMA); 1174 setTargetDAGCombine(ISD::SINT_TO_FP); 1175 setTargetDAGCombine(ISD::BUILD_VECTOR); 1176 if (Subtarget.hasFPCVT()) 1177 setTargetDAGCombine(ISD::UINT_TO_FP); 1178 setTargetDAGCombine(ISD::LOAD); 1179 setTargetDAGCombine(ISD::STORE); 1180 setTargetDAGCombine(ISD::BR_CC); 1181 if (Subtarget.useCRBits()) 1182 setTargetDAGCombine(ISD::BRCOND); 1183 setTargetDAGCombine(ISD::BSWAP); 1184 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1185 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1186 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1187 1188 setTargetDAGCombine(ISD::SIGN_EXTEND); 1189 setTargetDAGCombine(ISD::ZERO_EXTEND); 1190 setTargetDAGCombine(ISD::ANY_EXTEND); 1191 1192 setTargetDAGCombine(ISD::TRUNCATE); 1193 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1194 1195 1196 if (Subtarget.useCRBits()) { 1197 setTargetDAGCombine(ISD::TRUNCATE); 1198 setTargetDAGCombine(ISD::SETCC); 1199 setTargetDAGCombine(ISD::SELECT_CC); 1200 } 1201 1202 // Use reciprocal estimates. 1203 if (TM.Options.UnsafeFPMath) { 1204 setTargetDAGCombine(ISD::FDIV); 1205 setTargetDAGCombine(ISD::FSQRT); 1206 } 1207 1208 if (Subtarget.hasP9Altivec()) { 1209 setTargetDAGCombine(ISD::ABS); 1210 setTargetDAGCombine(ISD::VSELECT); 1211 } 1212 1213 setLibcallName(RTLIB::LOG_F128, "logf128"); 1214 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1215 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1216 setLibcallName(RTLIB::EXP_F128, "expf128"); 1217 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1218 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1219 setLibcallName(RTLIB::COS_F128, "cosf128"); 1220 setLibcallName(RTLIB::POW_F128, "powf128"); 1221 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1222 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1223 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1224 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1225 1226 // With 32 condition bits, we don't need to sink (and duplicate) compares 1227 // aggressively in CodeGenPrep. 1228 if (Subtarget.useCRBits()) { 1229 setHasMultipleConditionRegisters(); 1230 setJumpIsExpensive(); 1231 } 1232 1233 setMinFunctionAlignment(Align(4)); 1234 1235 switch (Subtarget.getCPUDirective()) { 1236 default: break; 1237 case PPC::DIR_970: 1238 case PPC::DIR_A2: 1239 case PPC::DIR_E500: 1240 case PPC::DIR_E500mc: 1241 case PPC::DIR_E5500: 1242 case PPC::DIR_PWR4: 1243 case PPC::DIR_PWR5: 1244 case PPC::DIR_PWR5X: 1245 case PPC::DIR_PWR6: 1246 case PPC::DIR_PWR6X: 1247 case PPC::DIR_PWR7: 1248 case PPC::DIR_PWR8: 1249 case PPC::DIR_PWR9: 1250 case PPC::DIR_PWR10: 1251 case PPC::DIR_PWR_FUTURE: 1252 setPrefLoopAlignment(Align(16)); 1253 setPrefFunctionAlignment(Align(16)); 1254 break; 1255 } 1256 1257 if (Subtarget.enableMachineScheduler()) 1258 setSchedulingPreference(Sched::Source); 1259 else 1260 setSchedulingPreference(Sched::Hybrid); 1261 1262 computeRegisterProperties(STI.getRegisterInfo()); 1263 1264 // The Freescale cores do better with aggressive inlining of memcpy and 1265 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1266 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1267 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1268 MaxStoresPerMemset = 32; 1269 MaxStoresPerMemsetOptSize = 16; 1270 MaxStoresPerMemcpy = 32; 1271 MaxStoresPerMemcpyOptSize = 8; 1272 MaxStoresPerMemmove = 32; 1273 MaxStoresPerMemmoveOptSize = 8; 1274 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1275 // The A2 also benefits from (very) aggressive inlining of memcpy and 1276 // friends. The overhead of a the function call, even when warm, can be 1277 // over one hundred cycles. 1278 MaxStoresPerMemset = 128; 1279 MaxStoresPerMemcpy = 128; 1280 MaxStoresPerMemmove = 128; 1281 MaxLoadsPerMemcmp = 128; 1282 } else { 1283 MaxLoadsPerMemcmp = 8; 1284 MaxLoadsPerMemcmpOptSize = 4; 1285 } 1286 1287 // Let the subtarget (CPU) decide if a predictable select is more expensive 1288 // than the corresponding branch. This information is used in CGP to decide 1289 // when to convert selects into branches. 1290 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1291 } 1292 1293 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1294 /// the desired ByVal argument alignment. 1295 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1296 if (MaxAlign == MaxMaxAlign) 1297 return; 1298 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1299 if (MaxMaxAlign >= 32 && 1300 VTy->getPrimitiveSizeInBits().getFixedSize() >= 256) 1301 MaxAlign = Align(32); 1302 else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 && 1303 MaxAlign < 16) 1304 MaxAlign = Align(16); 1305 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1306 Align EltAlign; 1307 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1308 if (EltAlign > MaxAlign) 1309 MaxAlign = EltAlign; 1310 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1311 for (auto *EltTy : STy->elements()) { 1312 Align EltAlign; 1313 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1314 if (EltAlign > MaxAlign) 1315 MaxAlign = EltAlign; 1316 if (MaxAlign == MaxMaxAlign) 1317 break; 1318 } 1319 } 1320 } 1321 1322 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1323 /// function arguments in the caller parameter area. 1324 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1325 const DataLayout &DL) const { 1326 // 16byte and wider vectors are passed on 16byte boundary. 1327 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1328 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1329 if (Subtarget.hasAltivec()) 1330 getMaxByValAlign(Ty, Alignment, Align(16)); 1331 return Alignment.value(); 1332 } 1333 1334 bool PPCTargetLowering::useSoftFloat() const { 1335 return Subtarget.useSoftFloat(); 1336 } 1337 1338 bool PPCTargetLowering::hasSPE() const { 1339 return Subtarget.hasSPE(); 1340 } 1341 1342 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1343 return VT.isScalarInteger(); 1344 } 1345 1346 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific 1347 /// type is cheaper than a multiply followed by a shift. 1348 /// This is true for words and doublewords on 64-bit PowerPC. 1349 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const { 1350 if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) || 1351 isOperationLegal(ISD::MULHU, Type))) 1352 return true; 1353 return TargetLowering::isMulhCheaperThanMulShift(Type); 1354 } 1355 1356 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1357 switch ((PPCISD::NodeType)Opcode) { 1358 case PPCISD::FIRST_NUMBER: break; 1359 case PPCISD::FSEL: return "PPCISD::FSEL"; 1360 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1361 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1362 case PPCISD::FCFID: return "PPCISD::FCFID"; 1363 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1364 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1365 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1366 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1367 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1368 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1369 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1370 case PPCISD::FP_TO_UINT_IN_VSR: 1371 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1372 case PPCISD::FP_TO_SINT_IN_VSR: 1373 return "PPCISD::FP_TO_SINT_IN_VSR"; 1374 case PPCISD::FRE: return "PPCISD::FRE"; 1375 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1376 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1377 case PPCISD::VPERM: return "PPCISD::VPERM"; 1378 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1379 case PPCISD::XXSPLTI_SP_TO_DP: 1380 return "PPCISD::XXSPLTI_SP_TO_DP"; 1381 case PPCISD::XXSPLTI32DX: 1382 return "PPCISD::XXSPLTI32DX"; 1383 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1384 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1385 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1386 case PPCISD::CMPB: return "PPCISD::CMPB"; 1387 case PPCISD::Hi: return "PPCISD::Hi"; 1388 case PPCISD::Lo: return "PPCISD::Lo"; 1389 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1390 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1391 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1392 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1393 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1394 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1395 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1396 case PPCISD::SRL: return "PPCISD::SRL"; 1397 case PPCISD::SRA: return "PPCISD::SRA"; 1398 case PPCISD::SHL: return "PPCISD::SHL"; 1399 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1400 case PPCISD::CALL: return "PPCISD::CALL"; 1401 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1402 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1403 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1404 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1405 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1406 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1407 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1408 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1409 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1410 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1411 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1412 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1413 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1414 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1415 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1416 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1417 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1418 case PPCISD::ANDI_rec_1_EQ_BIT: 1419 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1420 case PPCISD::ANDI_rec_1_GT_BIT: 1421 return "PPCISD::ANDI_rec_1_GT_BIT"; 1422 case PPCISD::VCMP: return "PPCISD::VCMP"; 1423 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1424 case PPCISD::LBRX: return "PPCISD::LBRX"; 1425 case PPCISD::STBRX: return "PPCISD::STBRX"; 1426 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1427 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1428 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1429 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1430 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1431 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1432 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1433 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1434 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1435 case PPCISD::ST_VSR_SCAL_INT: 1436 return "PPCISD::ST_VSR_SCAL_INT"; 1437 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1438 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1439 case PPCISD::BDZ: return "PPCISD::BDZ"; 1440 case PPCISD::MFFS: return "PPCISD::MFFS"; 1441 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1442 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1443 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1444 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1445 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1446 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1447 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1448 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1449 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1450 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1451 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1452 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1453 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1454 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1455 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1456 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1457 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1458 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1459 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1460 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1461 case PPCISD::SC: return "PPCISD::SC"; 1462 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1463 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1464 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1465 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1466 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1467 case PPCISD::VABSD: return "PPCISD::VABSD"; 1468 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1469 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1470 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1471 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1472 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1473 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1474 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1475 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1476 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1477 case PPCISD::STRICT_FCTIDZ: 1478 return "PPCISD::STRICT_FCTIDZ"; 1479 case PPCISD::STRICT_FCTIWZ: 1480 return "PPCISD::STRICT_FCTIWZ"; 1481 case PPCISD::STRICT_FCTIDUZ: 1482 return "PPCISD::STRICT_FCTIDUZ"; 1483 case PPCISD::STRICT_FCTIWUZ: 1484 return "PPCISD::STRICT_FCTIWUZ"; 1485 } 1486 return nullptr; 1487 } 1488 1489 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1490 EVT VT) const { 1491 if (!VT.isVector()) 1492 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1493 1494 return VT.changeVectorElementTypeToInteger(); 1495 } 1496 1497 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1498 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1499 return true; 1500 } 1501 1502 //===----------------------------------------------------------------------===// 1503 // Node matching predicates, for use by the tblgen matching code. 1504 //===----------------------------------------------------------------------===// 1505 1506 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1507 static bool isFloatingPointZero(SDValue Op) { 1508 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1509 return CFP->getValueAPF().isZero(); 1510 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1511 // Maybe this has already been legalized into the constant pool? 1512 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1513 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1514 return CFP->getValueAPF().isZero(); 1515 } 1516 return false; 1517 } 1518 1519 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1520 /// true if Op is undef or if it matches the specified value. 1521 static bool isConstantOrUndef(int Op, int Val) { 1522 return Op < 0 || Op == Val; 1523 } 1524 1525 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1526 /// VPKUHUM instruction. 1527 /// The ShuffleKind distinguishes between big-endian operations with 1528 /// two different inputs (0), either-endian operations with two identical 1529 /// inputs (1), and little-endian operations with two different inputs (2). 1530 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1531 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1532 SelectionDAG &DAG) { 1533 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1534 if (ShuffleKind == 0) { 1535 if (IsLE) 1536 return false; 1537 for (unsigned i = 0; i != 16; ++i) 1538 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1539 return false; 1540 } else if (ShuffleKind == 2) { 1541 if (!IsLE) 1542 return false; 1543 for (unsigned i = 0; i != 16; ++i) 1544 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1545 return false; 1546 } else if (ShuffleKind == 1) { 1547 unsigned j = IsLE ? 0 : 1; 1548 for (unsigned i = 0; i != 8; ++i) 1549 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1550 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1551 return false; 1552 } 1553 return true; 1554 } 1555 1556 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1557 /// VPKUWUM instruction. 1558 /// The ShuffleKind distinguishes between big-endian operations with 1559 /// two different inputs (0), either-endian operations with two identical 1560 /// inputs (1), and little-endian operations with two different inputs (2). 1561 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1562 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1563 SelectionDAG &DAG) { 1564 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1565 if (ShuffleKind == 0) { 1566 if (IsLE) 1567 return false; 1568 for (unsigned i = 0; i != 16; i += 2) 1569 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1570 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1571 return false; 1572 } else if (ShuffleKind == 2) { 1573 if (!IsLE) 1574 return false; 1575 for (unsigned i = 0; i != 16; i += 2) 1576 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1577 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1578 return false; 1579 } else if (ShuffleKind == 1) { 1580 unsigned j = IsLE ? 0 : 2; 1581 for (unsigned i = 0; i != 8; i += 2) 1582 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1583 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1584 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1585 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1586 return false; 1587 } 1588 return true; 1589 } 1590 1591 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1592 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1593 /// current subtarget. 1594 /// 1595 /// The ShuffleKind distinguishes between big-endian operations with 1596 /// two different inputs (0), either-endian operations with two identical 1597 /// inputs (1), and little-endian operations with two different inputs (2). 1598 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1599 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1600 SelectionDAG &DAG) { 1601 const PPCSubtarget& Subtarget = 1602 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1603 if (!Subtarget.hasP8Vector()) 1604 return false; 1605 1606 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1607 if (ShuffleKind == 0) { 1608 if (IsLE) 1609 return false; 1610 for (unsigned i = 0; i != 16; i += 4) 1611 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1612 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1613 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1614 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1615 return false; 1616 } else if (ShuffleKind == 2) { 1617 if (!IsLE) 1618 return false; 1619 for (unsigned i = 0; i != 16; i += 4) 1620 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1621 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1622 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1623 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1624 return false; 1625 } else if (ShuffleKind == 1) { 1626 unsigned j = IsLE ? 0 : 4; 1627 for (unsigned i = 0; i != 8; i += 4) 1628 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1629 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1630 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1631 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1632 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1633 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1634 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1635 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1636 return false; 1637 } 1638 return true; 1639 } 1640 1641 /// isVMerge - Common function, used to match vmrg* shuffles. 1642 /// 1643 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1644 unsigned LHSStart, unsigned RHSStart) { 1645 if (N->getValueType(0) != MVT::v16i8) 1646 return false; 1647 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1648 "Unsupported merge size!"); 1649 1650 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1651 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1652 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1653 LHSStart+j+i*UnitSize) || 1654 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1655 RHSStart+j+i*UnitSize)) 1656 return false; 1657 } 1658 return true; 1659 } 1660 1661 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1662 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1663 /// The ShuffleKind distinguishes between big-endian merges with two 1664 /// different inputs (0), either-endian merges with two identical inputs (1), 1665 /// and little-endian merges with two different inputs (2). For the latter, 1666 /// the input operands are swapped (see PPCInstrAltivec.td). 1667 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1668 unsigned ShuffleKind, SelectionDAG &DAG) { 1669 if (DAG.getDataLayout().isLittleEndian()) { 1670 if (ShuffleKind == 1) // unary 1671 return isVMerge(N, UnitSize, 0, 0); 1672 else if (ShuffleKind == 2) // swapped 1673 return isVMerge(N, UnitSize, 0, 16); 1674 else 1675 return false; 1676 } else { 1677 if (ShuffleKind == 1) // unary 1678 return isVMerge(N, UnitSize, 8, 8); 1679 else if (ShuffleKind == 0) // normal 1680 return isVMerge(N, UnitSize, 8, 24); 1681 else 1682 return false; 1683 } 1684 } 1685 1686 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1687 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1688 /// The ShuffleKind distinguishes between big-endian merges with two 1689 /// different inputs (0), either-endian merges with two identical inputs (1), 1690 /// and little-endian merges with two different inputs (2). For the latter, 1691 /// the input operands are swapped (see PPCInstrAltivec.td). 1692 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1693 unsigned ShuffleKind, SelectionDAG &DAG) { 1694 if (DAG.getDataLayout().isLittleEndian()) { 1695 if (ShuffleKind == 1) // unary 1696 return isVMerge(N, UnitSize, 8, 8); 1697 else if (ShuffleKind == 2) // swapped 1698 return isVMerge(N, UnitSize, 8, 24); 1699 else 1700 return false; 1701 } else { 1702 if (ShuffleKind == 1) // unary 1703 return isVMerge(N, UnitSize, 0, 0); 1704 else if (ShuffleKind == 0) // normal 1705 return isVMerge(N, UnitSize, 0, 16); 1706 else 1707 return false; 1708 } 1709 } 1710 1711 /** 1712 * Common function used to match vmrgew and vmrgow shuffles 1713 * 1714 * The indexOffset determines whether to look for even or odd words in 1715 * the shuffle mask. This is based on the of the endianness of the target 1716 * machine. 1717 * - Little Endian: 1718 * - Use offset of 0 to check for odd elements 1719 * - Use offset of 4 to check for even elements 1720 * - Big Endian: 1721 * - Use offset of 0 to check for even elements 1722 * - Use offset of 4 to check for odd elements 1723 * A detailed description of the vector element ordering for little endian and 1724 * big endian can be found at 1725 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1726 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1727 * compiler differences mean to you 1728 * 1729 * The mask to the shuffle vector instruction specifies the indices of the 1730 * elements from the two input vectors to place in the result. The elements are 1731 * numbered in array-access order, starting with the first vector. These vectors 1732 * are always of type v16i8, thus each vector will contain 16 elements of size 1733 * 8. More info on the shuffle vector can be found in the 1734 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1735 * Language Reference. 1736 * 1737 * The RHSStartValue indicates whether the same input vectors are used (unary) 1738 * or two different input vectors are used, based on the following: 1739 * - If the instruction uses the same vector for both inputs, the range of the 1740 * indices will be 0 to 15. In this case, the RHSStart value passed should 1741 * be 0. 1742 * - If the instruction has two different vectors then the range of the 1743 * indices will be 0 to 31. In this case, the RHSStart value passed should 1744 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1745 * to 31 specify elements in the second vector). 1746 * 1747 * \param[in] N The shuffle vector SD Node to analyze 1748 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1749 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1750 * vector to the shuffle_vector instruction 1751 * \return true iff this shuffle vector represents an even or odd word merge 1752 */ 1753 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1754 unsigned RHSStartValue) { 1755 if (N->getValueType(0) != MVT::v16i8) 1756 return false; 1757 1758 for (unsigned i = 0; i < 2; ++i) 1759 for (unsigned j = 0; j < 4; ++j) 1760 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1761 i*RHSStartValue+j+IndexOffset) || 1762 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1763 i*RHSStartValue+j+IndexOffset+8)) 1764 return false; 1765 return true; 1766 } 1767 1768 /** 1769 * Determine if the specified shuffle mask is suitable for the vmrgew or 1770 * vmrgow instructions. 1771 * 1772 * \param[in] N The shuffle vector SD Node to analyze 1773 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1774 * \param[in] ShuffleKind Identify the type of merge: 1775 * - 0 = big-endian merge with two different inputs; 1776 * - 1 = either-endian merge with two identical inputs; 1777 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1778 * little-endian merges). 1779 * \param[in] DAG The current SelectionDAG 1780 * \return true iff this shuffle mask 1781 */ 1782 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1783 unsigned ShuffleKind, SelectionDAG &DAG) { 1784 if (DAG.getDataLayout().isLittleEndian()) { 1785 unsigned indexOffset = CheckEven ? 4 : 0; 1786 if (ShuffleKind == 1) // Unary 1787 return isVMerge(N, indexOffset, 0); 1788 else if (ShuffleKind == 2) // swapped 1789 return isVMerge(N, indexOffset, 16); 1790 else 1791 return false; 1792 } 1793 else { 1794 unsigned indexOffset = CheckEven ? 0 : 4; 1795 if (ShuffleKind == 1) // Unary 1796 return isVMerge(N, indexOffset, 0); 1797 else if (ShuffleKind == 0) // Normal 1798 return isVMerge(N, indexOffset, 16); 1799 else 1800 return false; 1801 } 1802 return false; 1803 } 1804 1805 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1806 /// amount, otherwise return -1. 1807 /// The ShuffleKind distinguishes between big-endian operations with two 1808 /// different inputs (0), either-endian operations with two identical inputs 1809 /// (1), and little-endian operations with two different inputs (2). For the 1810 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1811 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1812 SelectionDAG &DAG) { 1813 if (N->getValueType(0) != MVT::v16i8) 1814 return -1; 1815 1816 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1817 1818 // Find the first non-undef value in the shuffle mask. 1819 unsigned i; 1820 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1821 /*search*/; 1822 1823 if (i == 16) return -1; // all undef. 1824 1825 // Otherwise, check to see if the rest of the elements are consecutively 1826 // numbered from this value. 1827 unsigned ShiftAmt = SVOp->getMaskElt(i); 1828 if (ShiftAmt < i) return -1; 1829 1830 ShiftAmt -= i; 1831 bool isLE = DAG.getDataLayout().isLittleEndian(); 1832 1833 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1834 // Check the rest of the elements to see if they are consecutive. 1835 for (++i; i != 16; ++i) 1836 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1837 return -1; 1838 } else if (ShuffleKind == 1) { 1839 // Check the rest of the elements to see if they are consecutive. 1840 for (++i; i != 16; ++i) 1841 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1842 return -1; 1843 } else 1844 return -1; 1845 1846 if (isLE) 1847 ShiftAmt = 16 - ShiftAmt; 1848 1849 return ShiftAmt; 1850 } 1851 1852 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1853 /// specifies a splat of a single element that is suitable for input to 1854 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1855 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1856 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1857 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1858 1859 // The consecutive indices need to specify an element, not part of two 1860 // different elements. So abandon ship early if this isn't the case. 1861 if (N->getMaskElt(0) % EltSize != 0) 1862 return false; 1863 1864 // This is a splat operation if each element of the permute is the same, and 1865 // if the value doesn't reference the second vector. 1866 unsigned ElementBase = N->getMaskElt(0); 1867 1868 // FIXME: Handle UNDEF elements too! 1869 if (ElementBase >= 16) 1870 return false; 1871 1872 // Check that the indices are consecutive, in the case of a multi-byte element 1873 // splatted with a v16i8 mask. 1874 for (unsigned i = 1; i != EltSize; ++i) 1875 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1876 return false; 1877 1878 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1879 if (N->getMaskElt(i) < 0) continue; 1880 for (unsigned j = 0; j != EltSize; ++j) 1881 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1882 return false; 1883 } 1884 return true; 1885 } 1886 1887 /// Check that the mask is shuffling N byte elements. Within each N byte 1888 /// element of the mask, the indices could be either in increasing or 1889 /// decreasing order as long as they are consecutive. 1890 /// \param[in] N the shuffle vector SD Node to analyze 1891 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1892 /// Word/DoubleWord/QuadWord). 1893 /// \param[in] StepLen the delta indices number among the N byte element, if 1894 /// the mask is in increasing/decreasing order then it is 1/-1. 1895 /// \return true iff the mask is shuffling N byte elements. 1896 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1897 int StepLen) { 1898 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1899 "Unexpected element width."); 1900 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1901 1902 unsigned NumOfElem = 16 / Width; 1903 unsigned MaskVal[16]; // Width is never greater than 16 1904 for (unsigned i = 0; i < NumOfElem; ++i) { 1905 MaskVal[0] = N->getMaskElt(i * Width); 1906 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1907 return false; 1908 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1909 return false; 1910 } 1911 1912 for (unsigned int j = 1; j < Width; ++j) { 1913 MaskVal[j] = N->getMaskElt(i * Width + j); 1914 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1915 return false; 1916 } 1917 } 1918 } 1919 1920 return true; 1921 } 1922 1923 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1924 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1925 if (!isNByteElemShuffleMask(N, 4, 1)) 1926 return false; 1927 1928 // Now we look at mask elements 0,4,8,12 1929 unsigned M0 = N->getMaskElt(0) / 4; 1930 unsigned M1 = N->getMaskElt(4) / 4; 1931 unsigned M2 = N->getMaskElt(8) / 4; 1932 unsigned M3 = N->getMaskElt(12) / 4; 1933 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1934 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1935 1936 // Below, let H and L be arbitrary elements of the shuffle mask 1937 // where H is in the range [4,7] and L is in the range [0,3]. 1938 // H, 1, 2, 3 or L, 5, 6, 7 1939 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1940 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1941 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1942 InsertAtByte = IsLE ? 12 : 0; 1943 Swap = M0 < 4; 1944 return true; 1945 } 1946 // 0, H, 2, 3 or 4, L, 6, 7 1947 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1948 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1949 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1950 InsertAtByte = IsLE ? 8 : 4; 1951 Swap = M1 < 4; 1952 return true; 1953 } 1954 // 0, 1, H, 3 or 4, 5, L, 7 1955 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1956 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1957 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1958 InsertAtByte = IsLE ? 4 : 8; 1959 Swap = M2 < 4; 1960 return true; 1961 } 1962 // 0, 1, 2, H or 4, 5, 6, L 1963 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1964 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1965 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1966 InsertAtByte = IsLE ? 0 : 12; 1967 Swap = M3 < 4; 1968 return true; 1969 } 1970 1971 // If both vector operands for the shuffle are the same vector, the mask will 1972 // contain only elements from the first one and the second one will be undef. 1973 if (N->getOperand(1).isUndef()) { 1974 ShiftElts = 0; 1975 Swap = true; 1976 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1977 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1978 InsertAtByte = IsLE ? 12 : 0; 1979 return true; 1980 } 1981 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1982 InsertAtByte = IsLE ? 8 : 4; 1983 return true; 1984 } 1985 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1986 InsertAtByte = IsLE ? 4 : 8; 1987 return true; 1988 } 1989 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1990 InsertAtByte = IsLE ? 0 : 12; 1991 return true; 1992 } 1993 } 1994 1995 return false; 1996 } 1997 1998 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1999 bool &Swap, bool IsLE) { 2000 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2001 // Ensure each byte index of the word is consecutive. 2002 if (!isNByteElemShuffleMask(N, 4, 1)) 2003 return false; 2004 2005 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2006 unsigned M0 = N->getMaskElt(0) / 4; 2007 unsigned M1 = N->getMaskElt(4) / 4; 2008 unsigned M2 = N->getMaskElt(8) / 4; 2009 unsigned M3 = N->getMaskElt(12) / 4; 2010 2011 // If both vector operands for the shuffle are the same vector, the mask will 2012 // contain only elements from the first one and the second one will be undef. 2013 if (N->getOperand(1).isUndef()) { 2014 assert(M0 < 4 && "Indexing into an undef vector?"); 2015 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2016 return false; 2017 2018 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2019 Swap = false; 2020 return true; 2021 } 2022 2023 // Ensure each word index of the ShuffleVector Mask is consecutive. 2024 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2025 return false; 2026 2027 if (IsLE) { 2028 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2029 // Input vectors don't need to be swapped if the leading element 2030 // of the result is one of the 3 left elements of the second vector 2031 // (or if there is no shift to be done at all). 2032 Swap = false; 2033 ShiftElts = (8 - M0) % 8; 2034 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2035 // Input vectors need to be swapped if the leading element 2036 // of the result is one of the 3 left elements of the first vector 2037 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2038 Swap = true; 2039 ShiftElts = (4 - M0) % 4; 2040 } 2041 2042 return true; 2043 } else { // BE 2044 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2045 // Input vectors don't need to be swapped if the leading element 2046 // of the result is one of the 4 elements of the first vector. 2047 Swap = false; 2048 ShiftElts = M0; 2049 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2050 // Input vectors need to be swapped if the leading element 2051 // of the result is one of the 4 elements of the right vector. 2052 Swap = true; 2053 ShiftElts = M0 - 4; 2054 } 2055 2056 return true; 2057 } 2058 } 2059 2060 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2061 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2062 2063 if (!isNByteElemShuffleMask(N, Width, -1)) 2064 return false; 2065 2066 for (int i = 0; i < 16; i += Width) 2067 if (N->getMaskElt(i) != i + Width - 1) 2068 return false; 2069 2070 return true; 2071 } 2072 2073 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2074 return isXXBRShuffleMaskHelper(N, 2); 2075 } 2076 2077 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2078 return isXXBRShuffleMaskHelper(N, 4); 2079 } 2080 2081 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2082 return isXXBRShuffleMaskHelper(N, 8); 2083 } 2084 2085 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2086 return isXXBRShuffleMaskHelper(N, 16); 2087 } 2088 2089 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2090 /// if the inputs to the instruction should be swapped and set \p DM to the 2091 /// value for the immediate. 2092 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2093 /// AND element 0 of the result comes from the first input (LE) or second input 2094 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2095 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2096 /// mask. 2097 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2098 bool &Swap, bool IsLE) { 2099 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2100 2101 // Ensure each byte index of the double word is consecutive. 2102 if (!isNByteElemShuffleMask(N, 8, 1)) 2103 return false; 2104 2105 unsigned M0 = N->getMaskElt(0) / 8; 2106 unsigned M1 = N->getMaskElt(8) / 8; 2107 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2108 2109 // If both vector operands for the shuffle are the same vector, the mask will 2110 // contain only elements from the first one and the second one will be undef. 2111 if (N->getOperand(1).isUndef()) { 2112 if ((M0 | M1) < 2) { 2113 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2114 Swap = false; 2115 return true; 2116 } else 2117 return false; 2118 } 2119 2120 if (IsLE) { 2121 if (M0 > 1 && M1 < 2) { 2122 Swap = false; 2123 } else if (M0 < 2 && M1 > 1) { 2124 M0 = (M0 + 2) % 4; 2125 M1 = (M1 + 2) % 4; 2126 Swap = true; 2127 } else 2128 return false; 2129 2130 // Note: if control flow comes here that means Swap is already set above 2131 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2132 return true; 2133 } else { // BE 2134 if (M0 < 2 && M1 > 1) { 2135 Swap = false; 2136 } else if (M0 > 1 && M1 < 2) { 2137 M0 = (M0 + 2) % 4; 2138 M1 = (M1 + 2) % 4; 2139 Swap = true; 2140 } else 2141 return false; 2142 2143 // Note: if control flow comes here that means Swap is already set above 2144 DM = (M0 << 1) + (M1 & 1); 2145 return true; 2146 } 2147 } 2148 2149 2150 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2151 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2152 /// elements are counted from the left of the vector register). 2153 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2154 SelectionDAG &DAG) { 2155 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2156 assert(isSplatShuffleMask(SVOp, EltSize)); 2157 if (DAG.getDataLayout().isLittleEndian()) 2158 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2159 else 2160 return SVOp->getMaskElt(0) / EltSize; 2161 } 2162 2163 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2164 /// by using a vspltis[bhw] instruction of the specified element size, return 2165 /// the constant being splatted. The ByteSize field indicates the number of 2166 /// bytes of each element [124] -> [bhw]. 2167 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2168 SDValue OpVal(nullptr, 0); 2169 2170 // If ByteSize of the splat is bigger than the element size of the 2171 // build_vector, then we have a case where we are checking for a splat where 2172 // multiple elements of the buildvector are folded together into a single 2173 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2174 unsigned EltSize = 16/N->getNumOperands(); 2175 if (EltSize < ByteSize) { 2176 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2177 SDValue UniquedVals[4]; 2178 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2179 2180 // See if all of the elements in the buildvector agree across. 2181 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2182 if (N->getOperand(i).isUndef()) continue; 2183 // If the element isn't a constant, bail fully out. 2184 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2185 2186 if (!UniquedVals[i&(Multiple-1)].getNode()) 2187 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2188 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2189 return SDValue(); // no match. 2190 } 2191 2192 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2193 // either constant or undef values that are identical for each chunk. See 2194 // if these chunks can form into a larger vspltis*. 2195 2196 // Check to see if all of the leading entries are either 0 or -1. If 2197 // neither, then this won't fit into the immediate field. 2198 bool LeadingZero = true; 2199 bool LeadingOnes = true; 2200 for (unsigned i = 0; i != Multiple-1; ++i) { 2201 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2202 2203 LeadingZero &= isNullConstant(UniquedVals[i]); 2204 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2205 } 2206 // Finally, check the least significant entry. 2207 if (LeadingZero) { 2208 if (!UniquedVals[Multiple-1].getNode()) 2209 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2210 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2211 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2212 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2213 } 2214 if (LeadingOnes) { 2215 if (!UniquedVals[Multiple-1].getNode()) 2216 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2217 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2218 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2219 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2220 } 2221 2222 return SDValue(); 2223 } 2224 2225 // Check to see if this buildvec has a single non-undef value in its elements. 2226 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2227 if (N->getOperand(i).isUndef()) continue; 2228 if (!OpVal.getNode()) 2229 OpVal = N->getOperand(i); 2230 else if (OpVal != N->getOperand(i)) 2231 return SDValue(); 2232 } 2233 2234 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2235 2236 unsigned ValSizeInBytes = EltSize; 2237 uint64_t Value = 0; 2238 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2239 Value = CN->getZExtValue(); 2240 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2241 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2242 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2243 } 2244 2245 // If the splat value is larger than the element value, then we can never do 2246 // this splat. The only case that we could fit the replicated bits into our 2247 // immediate field for would be zero, and we prefer to use vxor for it. 2248 if (ValSizeInBytes < ByteSize) return SDValue(); 2249 2250 // If the element value is larger than the splat value, check if it consists 2251 // of a repeated bit pattern of size ByteSize. 2252 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2253 return SDValue(); 2254 2255 // Properly sign extend the value. 2256 int MaskVal = SignExtend32(Value, ByteSize * 8); 2257 2258 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2259 if (MaskVal == 0) return SDValue(); 2260 2261 // Finally, if this value fits in a 5 bit sext field, return it 2262 if (SignExtend32<5>(MaskVal) == MaskVal) 2263 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2264 return SDValue(); 2265 } 2266 2267 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2268 /// amount, otherwise return -1. 2269 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2270 EVT VT = N->getValueType(0); 2271 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2272 return -1; 2273 2274 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2275 2276 // Find the first non-undef value in the shuffle mask. 2277 unsigned i; 2278 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2279 /*search*/; 2280 2281 if (i == 4) return -1; // all undef. 2282 2283 // Otherwise, check to see if the rest of the elements are consecutively 2284 // numbered from this value. 2285 unsigned ShiftAmt = SVOp->getMaskElt(i); 2286 if (ShiftAmt < i) return -1; 2287 ShiftAmt -= i; 2288 2289 // Check the rest of the elements to see if they are consecutive. 2290 for (++i; i != 4; ++i) 2291 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2292 return -1; 2293 2294 return ShiftAmt; 2295 } 2296 2297 //===----------------------------------------------------------------------===// 2298 // Addressing Mode Selection 2299 //===----------------------------------------------------------------------===// 2300 2301 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2302 /// or 64-bit immediate, and if the value can be accurately represented as a 2303 /// sign extension from a 16-bit value. If so, this returns true and the 2304 /// immediate. 2305 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2306 if (!isa<ConstantSDNode>(N)) 2307 return false; 2308 2309 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2310 if (N->getValueType(0) == MVT::i32) 2311 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2312 else 2313 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2314 } 2315 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2316 return isIntS16Immediate(Op.getNode(), Imm); 2317 } 2318 2319 2320 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2321 /// be represented as an indexed [r+r] operation. 2322 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2323 SDValue &Index, 2324 SelectionDAG &DAG) const { 2325 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2326 UI != E; ++UI) { 2327 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2328 if (Memop->getMemoryVT() == MVT::f64) { 2329 Base = N.getOperand(0); 2330 Index = N.getOperand(1); 2331 return true; 2332 } 2333 } 2334 } 2335 return false; 2336 } 2337 2338 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2339 /// can be represented as an indexed [r+r] operation. Returns false if it 2340 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2341 /// non-zero and N can be represented by a base register plus a signed 16-bit 2342 /// displacement, make a more precise judgement by checking (displacement % \p 2343 /// EncodingAlignment). 2344 bool PPCTargetLowering::SelectAddressRegReg( 2345 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2346 MaybeAlign EncodingAlignment) const { 2347 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2348 // a [pc+imm]. 2349 if (SelectAddressPCRel(N, Base)) 2350 return false; 2351 2352 int16_t Imm = 0; 2353 if (N.getOpcode() == ISD::ADD) { 2354 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2355 // SPE load/store can only handle 8-bit offsets. 2356 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2357 return true; 2358 if (isIntS16Immediate(N.getOperand(1), Imm) && 2359 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2360 return false; // r+i 2361 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2362 return false; // r+i 2363 2364 Base = N.getOperand(0); 2365 Index = N.getOperand(1); 2366 return true; 2367 } else if (N.getOpcode() == ISD::OR) { 2368 if (isIntS16Immediate(N.getOperand(1), Imm) && 2369 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2370 return false; // r+i can fold it if we can. 2371 2372 // If this is an or of disjoint bitfields, we can codegen this as an add 2373 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2374 // disjoint. 2375 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2376 2377 if (LHSKnown.Zero.getBoolValue()) { 2378 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2379 // If all of the bits are known zero on the LHS or RHS, the add won't 2380 // carry. 2381 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2382 Base = N.getOperand(0); 2383 Index = N.getOperand(1); 2384 return true; 2385 } 2386 } 2387 } 2388 2389 return false; 2390 } 2391 2392 // If we happen to be doing an i64 load or store into a stack slot that has 2393 // less than a 4-byte alignment, then the frame-index elimination may need to 2394 // use an indexed load or store instruction (because the offset may not be a 2395 // multiple of 4). The extra register needed to hold the offset comes from the 2396 // register scavenger, and it is possible that the scavenger will need to use 2397 // an emergency spill slot. As a result, we need to make sure that a spill slot 2398 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2399 // stack slot. 2400 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2401 // FIXME: This does not handle the LWA case. 2402 if (VT != MVT::i64) 2403 return; 2404 2405 // NOTE: We'll exclude negative FIs here, which come from argument 2406 // lowering, because there are no known test cases triggering this problem 2407 // using packed structures (or similar). We can remove this exclusion if 2408 // we find such a test case. The reason why this is so test-case driven is 2409 // because this entire 'fixup' is only to prevent crashes (from the 2410 // register scavenger) on not-really-valid inputs. For example, if we have: 2411 // %a = alloca i1 2412 // %b = bitcast i1* %a to i64* 2413 // store i64* a, i64 b 2414 // then the store should really be marked as 'align 1', but is not. If it 2415 // were marked as 'align 1' then the indexed form would have been 2416 // instruction-selected initially, and the problem this 'fixup' is preventing 2417 // won't happen regardless. 2418 if (FrameIdx < 0) 2419 return; 2420 2421 MachineFunction &MF = DAG.getMachineFunction(); 2422 MachineFrameInfo &MFI = MF.getFrameInfo(); 2423 2424 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2425 return; 2426 2427 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2428 FuncInfo->setHasNonRISpills(); 2429 } 2430 2431 /// Returns true if the address N can be represented by a base register plus 2432 /// a signed 16-bit displacement [r+imm], and if it is not better 2433 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2434 /// displacements that are multiples of that value. 2435 bool PPCTargetLowering::SelectAddressRegImm( 2436 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2437 MaybeAlign EncodingAlignment) const { 2438 // FIXME dl should come from parent load or store, not from address 2439 SDLoc dl(N); 2440 2441 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2442 // a [pc+imm]. 2443 if (SelectAddressPCRel(N, Base)) 2444 return false; 2445 2446 // If this can be more profitably realized as r+r, fail. 2447 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2448 return false; 2449 2450 if (N.getOpcode() == ISD::ADD) { 2451 int16_t imm = 0; 2452 if (isIntS16Immediate(N.getOperand(1), imm) && 2453 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2454 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2455 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2456 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2457 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2458 } else { 2459 Base = N.getOperand(0); 2460 } 2461 return true; // [r+i] 2462 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2463 // Match LOAD (ADD (X, Lo(G))). 2464 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2465 && "Cannot handle constant offsets yet!"); 2466 Disp = N.getOperand(1).getOperand(0); // The global address. 2467 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2468 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2469 Disp.getOpcode() == ISD::TargetConstantPool || 2470 Disp.getOpcode() == ISD::TargetJumpTable); 2471 Base = N.getOperand(0); 2472 return true; // [&g+r] 2473 } 2474 } else if (N.getOpcode() == ISD::OR) { 2475 int16_t imm = 0; 2476 if (isIntS16Immediate(N.getOperand(1), imm) && 2477 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2478 // If this is an or of disjoint bitfields, we can codegen this as an add 2479 // (for better address arithmetic) if the LHS and RHS of the OR are 2480 // provably disjoint. 2481 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2482 2483 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2484 // If all of the bits are known zero on the LHS or RHS, the add won't 2485 // carry. 2486 if (FrameIndexSDNode *FI = 2487 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2488 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2489 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2490 } else { 2491 Base = N.getOperand(0); 2492 } 2493 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2494 return true; 2495 } 2496 } 2497 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2498 // Loading from a constant address. 2499 2500 // If this address fits entirely in a 16-bit sext immediate field, codegen 2501 // this as "d, 0" 2502 int16_t Imm; 2503 if (isIntS16Immediate(CN, Imm) && 2504 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2505 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2506 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2507 CN->getValueType(0)); 2508 return true; 2509 } 2510 2511 // Handle 32-bit sext immediates with LIS + addr mode. 2512 if ((CN->getValueType(0) == MVT::i32 || 2513 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2514 (!EncodingAlignment || 2515 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2516 int Addr = (int)CN->getZExtValue(); 2517 2518 // Otherwise, break this down into an LIS + disp. 2519 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2520 2521 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2522 MVT::i32); 2523 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2524 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2525 return true; 2526 } 2527 } 2528 2529 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2530 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2531 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2532 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2533 } else 2534 Base = N; 2535 return true; // [r+0] 2536 } 2537 2538 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2539 /// represented as an indexed [r+r] operation. 2540 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2541 SDValue &Index, 2542 SelectionDAG &DAG) const { 2543 // Check to see if we can easily represent this as an [r+r] address. This 2544 // will fail if it thinks that the address is more profitably represented as 2545 // reg+imm, e.g. where imm = 0. 2546 if (SelectAddressRegReg(N, Base, Index, DAG)) 2547 return true; 2548 2549 // If the address is the result of an add, we will utilize the fact that the 2550 // address calculation includes an implicit add. However, we can reduce 2551 // register pressure if we do not materialize a constant just for use as the 2552 // index register. We only get rid of the add if it is not an add of a 2553 // value and a 16-bit signed constant and both have a single use. 2554 int16_t imm = 0; 2555 if (N.getOpcode() == ISD::ADD && 2556 (!isIntS16Immediate(N.getOperand(1), imm) || 2557 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2558 Base = N.getOperand(0); 2559 Index = N.getOperand(1); 2560 return true; 2561 } 2562 2563 // Otherwise, do it the hard way, using R0 as the base register. 2564 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2565 N.getValueType()); 2566 Index = N; 2567 return true; 2568 } 2569 2570 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2571 Ty *PCRelCand = dyn_cast<Ty>(N); 2572 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2573 } 2574 2575 /// Returns true if this address is a PC Relative address. 2576 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2577 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2578 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2579 // This is a materialize PC Relative node. Always select this as PC Relative. 2580 Base = N; 2581 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2582 return true; 2583 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2584 isValidPCRelNode<GlobalAddressSDNode>(N) || 2585 isValidPCRelNode<JumpTableSDNode>(N) || 2586 isValidPCRelNode<BlockAddressSDNode>(N)) 2587 return true; 2588 return false; 2589 } 2590 2591 /// Returns true if we should use a direct load into vector instruction 2592 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2593 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2594 2595 // If there are any other uses other than scalar to vector, then we should 2596 // keep it as a scalar load -> direct move pattern to prevent multiple 2597 // loads. 2598 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2599 if (!LD) 2600 return false; 2601 2602 EVT MemVT = LD->getMemoryVT(); 2603 if (!MemVT.isSimple()) 2604 return false; 2605 switch(MemVT.getSimpleVT().SimpleTy) { 2606 case MVT::i64: 2607 break; 2608 case MVT::i32: 2609 if (!ST.hasP8Vector()) 2610 return false; 2611 break; 2612 case MVT::i16: 2613 case MVT::i8: 2614 if (!ST.hasP9Vector()) 2615 return false; 2616 break; 2617 default: 2618 return false; 2619 } 2620 2621 SDValue LoadedVal(N, 0); 2622 if (!LoadedVal.hasOneUse()) 2623 return false; 2624 2625 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2626 UI != UE; ++UI) 2627 if (UI.getUse().get().getResNo() == 0 && 2628 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2629 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2630 return false; 2631 2632 return true; 2633 } 2634 2635 /// getPreIndexedAddressParts - returns true by value, base pointer and 2636 /// offset pointer and addressing mode by reference if the node's address 2637 /// can be legally represented as pre-indexed load / store address. 2638 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2639 SDValue &Offset, 2640 ISD::MemIndexedMode &AM, 2641 SelectionDAG &DAG) const { 2642 if (DisablePPCPreinc) return false; 2643 2644 bool isLoad = true; 2645 SDValue Ptr; 2646 EVT VT; 2647 unsigned Alignment; 2648 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2649 Ptr = LD->getBasePtr(); 2650 VT = LD->getMemoryVT(); 2651 Alignment = LD->getAlignment(); 2652 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2653 Ptr = ST->getBasePtr(); 2654 VT = ST->getMemoryVT(); 2655 Alignment = ST->getAlignment(); 2656 isLoad = false; 2657 } else 2658 return false; 2659 2660 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2661 // instructions because we can fold these into a more efficient instruction 2662 // instead, (such as LXSD). 2663 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2664 return false; 2665 } 2666 2667 // PowerPC doesn't have preinc load/store instructions for vectors 2668 if (VT.isVector()) 2669 return false; 2670 2671 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2672 // Common code will reject creating a pre-inc form if the base pointer 2673 // is a frame index, or if N is a store and the base pointer is either 2674 // the same as or a predecessor of the value being stored. Check for 2675 // those situations here, and try with swapped Base/Offset instead. 2676 bool Swap = false; 2677 2678 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2679 Swap = true; 2680 else if (!isLoad) { 2681 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2682 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2683 Swap = true; 2684 } 2685 2686 if (Swap) 2687 std::swap(Base, Offset); 2688 2689 AM = ISD::PRE_INC; 2690 return true; 2691 } 2692 2693 // LDU/STU can only handle immediates that are a multiple of 4. 2694 if (VT != MVT::i64) { 2695 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None)) 2696 return false; 2697 } else { 2698 // LDU/STU need an address with at least 4-byte alignment. 2699 if (Alignment < 4) 2700 return false; 2701 2702 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 2703 return false; 2704 } 2705 2706 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2707 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2708 // sext i32 to i64 when addr mode is r+i. 2709 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2710 LD->getExtensionType() == ISD::SEXTLOAD && 2711 isa<ConstantSDNode>(Offset)) 2712 return false; 2713 } 2714 2715 AM = ISD::PRE_INC; 2716 return true; 2717 } 2718 2719 //===----------------------------------------------------------------------===// 2720 // LowerOperation implementation 2721 //===----------------------------------------------------------------------===// 2722 2723 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2724 /// and LoOpFlags to the target MO flags. 2725 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2726 unsigned &HiOpFlags, unsigned &LoOpFlags, 2727 const GlobalValue *GV = nullptr) { 2728 HiOpFlags = PPCII::MO_HA; 2729 LoOpFlags = PPCII::MO_LO; 2730 2731 // Don't use the pic base if not in PIC relocation model. 2732 if (IsPIC) { 2733 HiOpFlags |= PPCII::MO_PIC_FLAG; 2734 LoOpFlags |= PPCII::MO_PIC_FLAG; 2735 } 2736 } 2737 2738 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2739 SelectionDAG &DAG) { 2740 SDLoc DL(HiPart); 2741 EVT PtrVT = HiPart.getValueType(); 2742 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2743 2744 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2745 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2746 2747 // With PIC, the first instruction is actually "GR+hi(&G)". 2748 if (isPIC) 2749 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2750 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2751 2752 // Generate non-pic code that has direct accesses to the constant pool. 2753 // The address of the global is just (hi(&g)+lo(&g)). 2754 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2755 } 2756 2757 static void setUsesTOCBasePtr(MachineFunction &MF) { 2758 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2759 FuncInfo->setUsesTOCBasePtr(); 2760 } 2761 2762 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2763 setUsesTOCBasePtr(DAG.getMachineFunction()); 2764 } 2765 2766 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2767 SDValue GA) const { 2768 const bool Is64Bit = Subtarget.isPPC64(); 2769 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2770 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2771 : Subtarget.isAIXABI() 2772 ? DAG.getRegister(PPC::R2, VT) 2773 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2774 SDValue Ops[] = { GA, Reg }; 2775 return DAG.getMemIntrinsicNode( 2776 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2777 MachinePointerInfo::getGOT(DAG.getMachineFunction()), None, 2778 MachineMemOperand::MOLoad); 2779 } 2780 2781 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2782 SelectionDAG &DAG) const { 2783 EVT PtrVT = Op.getValueType(); 2784 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2785 const Constant *C = CP->getConstVal(); 2786 2787 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2788 // The actual address of the GlobalValue is stored in the TOC. 2789 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2790 if (Subtarget.isUsingPCRelativeCalls()) { 2791 SDLoc DL(CP); 2792 EVT Ty = getPointerTy(DAG.getDataLayout()); 2793 SDValue ConstPool = DAG.getTargetConstantPool( 2794 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 2795 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 2796 } 2797 setUsesTOCBasePtr(DAG); 2798 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 2799 return getTOCEntry(DAG, SDLoc(CP), GA); 2800 } 2801 2802 unsigned MOHiFlag, MOLoFlag; 2803 bool IsPIC = isPositionIndependent(); 2804 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2805 2806 if (IsPIC && Subtarget.isSVR4ABI()) { 2807 SDValue GA = 2808 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 2809 return getTOCEntry(DAG, SDLoc(CP), GA); 2810 } 2811 2812 SDValue CPIHi = 2813 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 2814 SDValue CPILo = 2815 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 2816 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2817 } 2818 2819 // For 64-bit PowerPC, prefer the more compact relative encodings. 2820 // This trades 32 bits per jump table entry for one or two instructions 2821 // on the jump site. 2822 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2823 if (isJumpTableRelative()) 2824 return MachineJumpTableInfo::EK_LabelDifference32; 2825 2826 return TargetLowering::getJumpTableEncoding(); 2827 } 2828 2829 bool PPCTargetLowering::isJumpTableRelative() const { 2830 if (UseAbsoluteJumpTables) 2831 return false; 2832 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2833 return true; 2834 return TargetLowering::isJumpTableRelative(); 2835 } 2836 2837 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2838 SelectionDAG &DAG) const { 2839 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2840 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2841 2842 switch (getTargetMachine().getCodeModel()) { 2843 case CodeModel::Small: 2844 case CodeModel::Medium: 2845 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2846 default: 2847 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2848 getPointerTy(DAG.getDataLayout())); 2849 } 2850 } 2851 2852 const MCExpr * 2853 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2854 unsigned JTI, 2855 MCContext &Ctx) const { 2856 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2857 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2858 2859 switch (getTargetMachine().getCodeModel()) { 2860 case CodeModel::Small: 2861 case CodeModel::Medium: 2862 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2863 default: 2864 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2865 } 2866 } 2867 2868 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2869 EVT PtrVT = Op.getValueType(); 2870 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2871 2872 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2873 if (Subtarget.isUsingPCRelativeCalls()) { 2874 SDLoc DL(JT); 2875 EVT Ty = getPointerTy(DAG.getDataLayout()); 2876 SDValue GA = 2877 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 2878 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2879 return MatAddr; 2880 } 2881 2882 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2883 // The actual address of the GlobalValue is stored in the TOC. 2884 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2885 setUsesTOCBasePtr(DAG); 2886 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2887 return getTOCEntry(DAG, SDLoc(JT), GA); 2888 } 2889 2890 unsigned MOHiFlag, MOLoFlag; 2891 bool IsPIC = isPositionIndependent(); 2892 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2893 2894 if (IsPIC && Subtarget.isSVR4ABI()) { 2895 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2896 PPCII::MO_PIC_FLAG); 2897 return getTOCEntry(DAG, SDLoc(GA), GA); 2898 } 2899 2900 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2901 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2902 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2903 } 2904 2905 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2906 SelectionDAG &DAG) const { 2907 EVT PtrVT = Op.getValueType(); 2908 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2909 const BlockAddress *BA = BASDN->getBlockAddress(); 2910 2911 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 2912 if (Subtarget.isUsingPCRelativeCalls()) { 2913 SDLoc DL(BASDN); 2914 EVT Ty = getPointerTy(DAG.getDataLayout()); 2915 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 2916 PPCII::MO_PCREL_FLAG); 2917 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 2918 return MatAddr; 2919 } 2920 2921 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2922 // The actual BlockAddress is stored in the TOC. 2923 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2924 setUsesTOCBasePtr(DAG); 2925 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2926 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2927 } 2928 2929 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2930 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2931 return getTOCEntry( 2932 DAG, SDLoc(BASDN), 2933 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2934 2935 unsigned MOHiFlag, MOLoFlag; 2936 bool IsPIC = isPositionIndependent(); 2937 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2938 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2939 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2940 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2941 } 2942 2943 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2944 SelectionDAG &DAG) const { 2945 // FIXME: TLS addresses currently use medium model code sequences, 2946 // which is the most useful form. Eventually support for small and 2947 // large models could be added if users need it, at the cost of 2948 // additional complexity. 2949 if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS) 2950 report_fatal_error("Thread local storage is not supported with pc-relative" 2951 " addressing - please compile with -mno-pcrel"); 2952 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2953 if (DAG.getTarget().useEmulatedTLS()) 2954 return LowerToTLSEmulatedModel(GA, DAG); 2955 2956 SDLoc dl(GA); 2957 const GlobalValue *GV = GA->getGlobal(); 2958 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2959 bool is64bit = Subtarget.isPPC64(); 2960 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2961 PICLevel::Level picLevel = M->getPICLevel(); 2962 2963 const TargetMachine &TM = getTargetMachine(); 2964 TLSModel::Model Model = TM.getTLSModel(GV); 2965 2966 if (Model == TLSModel::LocalExec) { 2967 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2968 PPCII::MO_TPREL_HA); 2969 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2970 PPCII::MO_TPREL_LO); 2971 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2972 : DAG.getRegister(PPC::R2, MVT::i32); 2973 2974 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2975 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2976 } 2977 2978 if (Model == TLSModel::InitialExec) { 2979 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2980 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2981 PPCII::MO_TLS); 2982 SDValue GOTPtr; 2983 if (is64bit) { 2984 setUsesTOCBasePtr(DAG); 2985 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2986 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2987 PtrVT, GOTReg, TGA); 2988 } else { 2989 if (!TM.isPositionIndependent()) 2990 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2991 else if (picLevel == PICLevel::SmallPIC) 2992 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2993 else 2994 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2995 } 2996 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2997 PtrVT, TGA, GOTPtr); 2998 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2999 } 3000 3001 if (Model == TLSModel::GeneralDynamic) { 3002 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3003 SDValue GOTPtr; 3004 if (is64bit) { 3005 setUsesTOCBasePtr(DAG); 3006 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3007 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3008 GOTReg, TGA); 3009 } else { 3010 if (picLevel == PICLevel::SmallPIC) 3011 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3012 else 3013 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3014 } 3015 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3016 GOTPtr, TGA, TGA); 3017 } 3018 3019 if (Model == TLSModel::LocalDynamic) { 3020 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3021 SDValue GOTPtr; 3022 if (is64bit) { 3023 setUsesTOCBasePtr(DAG); 3024 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3025 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3026 GOTReg, TGA); 3027 } else { 3028 if (picLevel == PICLevel::SmallPIC) 3029 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3030 else 3031 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3032 } 3033 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3034 PtrVT, GOTPtr, TGA, TGA); 3035 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3036 PtrVT, TLSAddr, TGA); 3037 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3038 } 3039 3040 llvm_unreachable("Unknown TLS model!"); 3041 } 3042 3043 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3044 SelectionDAG &DAG) const { 3045 EVT PtrVT = Op.getValueType(); 3046 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3047 SDLoc DL(GSDN); 3048 const GlobalValue *GV = GSDN->getGlobal(); 3049 3050 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3051 // The actual address of the GlobalValue is stored in the TOC. 3052 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3053 if (Subtarget.isUsingPCRelativeCalls()) { 3054 EVT Ty = getPointerTy(DAG.getDataLayout()); 3055 if (isAccessedAsGotIndirect(Op)) { 3056 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3057 PPCII::MO_PCREL_FLAG | 3058 PPCII::MO_GOT_FLAG); 3059 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3060 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3061 MachinePointerInfo()); 3062 return Load; 3063 } else { 3064 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3065 PPCII::MO_PCREL_FLAG); 3066 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3067 } 3068 } 3069 setUsesTOCBasePtr(DAG); 3070 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3071 return getTOCEntry(DAG, DL, GA); 3072 } 3073 3074 unsigned MOHiFlag, MOLoFlag; 3075 bool IsPIC = isPositionIndependent(); 3076 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3077 3078 if (IsPIC && Subtarget.isSVR4ABI()) { 3079 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3080 GSDN->getOffset(), 3081 PPCII::MO_PIC_FLAG); 3082 return getTOCEntry(DAG, DL, GA); 3083 } 3084 3085 SDValue GAHi = 3086 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3087 SDValue GALo = 3088 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3089 3090 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3091 } 3092 3093 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3094 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3095 SDLoc dl(Op); 3096 3097 if (Op.getValueType() == MVT::v2i64) { 3098 // When the operands themselves are v2i64 values, we need to do something 3099 // special because VSX has no underlying comparison operations for these. 3100 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 3101 // Equality can be handled by casting to the legal type for Altivec 3102 // comparisons, everything else needs to be expanded. 3103 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3104 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3105 DAG.getSetCC(dl, MVT::v4i32, 3106 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3107 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3108 CC)); 3109 } 3110 3111 return SDValue(); 3112 } 3113 3114 // We handle most of these in the usual way. 3115 return Op; 3116 } 3117 3118 // If we're comparing for equality to zero, expose the fact that this is 3119 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3120 // fold the new nodes. 3121 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3122 return V; 3123 3124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3125 // Leave comparisons against 0 and -1 alone for now, since they're usually 3126 // optimized. FIXME: revisit this when we can custom lower all setcc 3127 // optimizations. 3128 if (C->isAllOnesValue() || C->isNullValue()) 3129 return SDValue(); 3130 } 3131 3132 // If we have an integer seteq/setne, turn it into a compare against zero 3133 // by xor'ing the rhs with the lhs, which is faster than setting a 3134 // condition register, reading it back out, and masking the correct bit. The 3135 // normal approach here uses sub to do this instead of xor. Using xor exposes 3136 // the result to other bit-twiddling opportunities. 3137 EVT LHSVT = Op.getOperand(0).getValueType(); 3138 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3139 EVT VT = Op.getValueType(); 3140 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3141 Op.getOperand(1)); 3142 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3143 } 3144 return SDValue(); 3145 } 3146 3147 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3148 SDNode *Node = Op.getNode(); 3149 EVT VT = Node->getValueType(0); 3150 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3151 SDValue InChain = Node->getOperand(0); 3152 SDValue VAListPtr = Node->getOperand(1); 3153 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3154 SDLoc dl(Node); 3155 3156 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3157 3158 // gpr_index 3159 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3160 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3161 InChain = GprIndex.getValue(1); 3162 3163 if (VT == MVT::i64) { 3164 // Check if GprIndex is even 3165 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3166 DAG.getConstant(1, dl, MVT::i32)); 3167 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3168 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3169 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3170 DAG.getConstant(1, dl, MVT::i32)); 3171 // Align GprIndex to be even if it isn't 3172 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3173 GprIndex); 3174 } 3175 3176 // fpr index is 1 byte after gpr 3177 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3178 DAG.getConstant(1, dl, MVT::i32)); 3179 3180 // fpr 3181 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3182 FprPtr, MachinePointerInfo(SV), MVT::i8); 3183 InChain = FprIndex.getValue(1); 3184 3185 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3186 DAG.getConstant(8, dl, MVT::i32)); 3187 3188 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3189 DAG.getConstant(4, dl, MVT::i32)); 3190 3191 // areas 3192 SDValue OverflowArea = 3193 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3194 InChain = OverflowArea.getValue(1); 3195 3196 SDValue RegSaveArea = 3197 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3198 InChain = RegSaveArea.getValue(1); 3199 3200 // select overflow_area if index > 8 3201 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3202 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3203 3204 // adjustment constant gpr_index * 4/8 3205 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3206 VT.isInteger() ? GprIndex : FprIndex, 3207 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3208 MVT::i32)); 3209 3210 // OurReg = RegSaveArea + RegConstant 3211 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3212 RegConstant); 3213 3214 // Floating types are 32 bytes into RegSaveArea 3215 if (VT.isFloatingPoint()) 3216 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3217 DAG.getConstant(32, dl, MVT::i32)); 3218 3219 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3220 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3221 VT.isInteger() ? GprIndex : FprIndex, 3222 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3223 MVT::i32)); 3224 3225 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3226 VT.isInteger() ? VAListPtr : FprPtr, 3227 MachinePointerInfo(SV), MVT::i8); 3228 3229 // determine if we should load from reg_save_area or overflow_area 3230 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3231 3232 // increase overflow_area by 4/8 if gpr/fpr > 8 3233 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3234 DAG.getConstant(VT.isInteger() ? 4 : 8, 3235 dl, MVT::i32)); 3236 3237 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3238 OverflowAreaPlusN); 3239 3240 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3241 MachinePointerInfo(), MVT::i32); 3242 3243 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3244 } 3245 3246 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3247 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3248 3249 // We have to copy the entire va_list struct: 3250 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3251 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3252 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3253 false, true, false, MachinePointerInfo(), 3254 MachinePointerInfo()); 3255 } 3256 3257 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3258 SelectionDAG &DAG) const { 3259 if (Subtarget.isAIXABI()) 3260 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3261 3262 return Op.getOperand(0); 3263 } 3264 3265 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3266 SelectionDAG &DAG) const { 3267 if (Subtarget.isAIXABI()) 3268 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3269 3270 SDValue Chain = Op.getOperand(0); 3271 SDValue Trmp = Op.getOperand(1); // trampoline 3272 SDValue FPtr = Op.getOperand(2); // nested function 3273 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3274 SDLoc dl(Op); 3275 3276 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3277 bool isPPC64 = (PtrVT == MVT::i64); 3278 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3279 3280 TargetLowering::ArgListTy Args; 3281 TargetLowering::ArgListEntry Entry; 3282 3283 Entry.Ty = IntPtrTy; 3284 Entry.Node = Trmp; Args.push_back(Entry); 3285 3286 // TrampSize == (isPPC64 ? 48 : 40); 3287 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3288 isPPC64 ? MVT::i64 : MVT::i32); 3289 Args.push_back(Entry); 3290 3291 Entry.Node = FPtr; Args.push_back(Entry); 3292 Entry.Node = Nest; Args.push_back(Entry); 3293 3294 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3295 TargetLowering::CallLoweringInfo CLI(DAG); 3296 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3297 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3298 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3299 3300 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3301 return CallResult.second; 3302 } 3303 3304 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3305 MachineFunction &MF = DAG.getMachineFunction(); 3306 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3307 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3308 3309 SDLoc dl(Op); 3310 3311 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3312 // vastart just stores the address of the VarArgsFrameIndex slot into the 3313 // memory location argument. 3314 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3315 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3316 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3317 MachinePointerInfo(SV)); 3318 } 3319 3320 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3321 // We suppose the given va_list is already allocated. 3322 // 3323 // typedef struct { 3324 // char gpr; /* index into the array of 8 GPRs 3325 // * stored in the register save area 3326 // * gpr=0 corresponds to r3, 3327 // * gpr=1 to r4, etc. 3328 // */ 3329 // char fpr; /* index into the array of 8 FPRs 3330 // * stored in the register save area 3331 // * fpr=0 corresponds to f1, 3332 // * fpr=1 to f2, etc. 3333 // */ 3334 // char *overflow_arg_area; 3335 // /* location on stack that holds 3336 // * the next overflow argument 3337 // */ 3338 // char *reg_save_area; 3339 // /* where r3:r10 and f1:f8 (if saved) 3340 // * are stored 3341 // */ 3342 // } va_list[1]; 3343 3344 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3345 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3346 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3347 PtrVT); 3348 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3349 PtrVT); 3350 3351 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3352 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3353 3354 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3355 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3356 3357 uint64_t FPROffset = 1; 3358 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3359 3360 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3361 3362 // Store first byte : number of int regs 3363 SDValue firstStore = 3364 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3365 MachinePointerInfo(SV), MVT::i8); 3366 uint64_t nextOffset = FPROffset; 3367 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3368 ConstFPROffset); 3369 3370 // Store second byte : number of float regs 3371 SDValue secondStore = 3372 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3373 MachinePointerInfo(SV, nextOffset), MVT::i8); 3374 nextOffset += StackOffset; 3375 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3376 3377 // Store second word : arguments given on stack 3378 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3379 MachinePointerInfo(SV, nextOffset)); 3380 nextOffset += FrameOffset; 3381 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3382 3383 // Store third word : arguments given in registers 3384 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3385 MachinePointerInfo(SV, nextOffset)); 3386 } 3387 3388 /// FPR - The set of FP registers that should be allocated for arguments 3389 /// on Darwin and AIX. 3390 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3391 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3392 PPC::F11, PPC::F12, PPC::F13}; 3393 3394 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3395 /// the stack. 3396 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3397 unsigned PtrByteSize) { 3398 unsigned ArgSize = ArgVT.getStoreSize(); 3399 if (Flags.isByVal()) 3400 ArgSize = Flags.getByValSize(); 3401 3402 // Round up to multiples of the pointer size, except for array members, 3403 // which are always packed. 3404 if (!Flags.isInConsecutiveRegs()) 3405 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3406 3407 return ArgSize; 3408 } 3409 3410 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3411 /// on the stack. 3412 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3413 ISD::ArgFlagsTy Flags, 3414 unsigned PtrByteSize) { 3415 Align Alignment(PtrByteSize); 3416 3417 // Altivec parameters are padded to a 16 byte boundary. 3418 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3419 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3420 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3421 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3422 Alignment = Align(16); 3423 3424 // ByVal parameters are aligned as requested. 3425 if (Flags.isByVal()) { 3426 auto BVAlign = Flags.getNonZeroByValAlign(); 3427 if (BVAlign > PtrByteSize) { 3428 if (BVAlign.value() % PtrByteSize != 0) 3429 llvm_unreachable( 3430 "ByVal alignment is not a multiple of the pointer size"); 3431 3432 Alignment = BVAlign; 3433 } 3434 } 3435 3436 // Array members are always packed to their original alignment. 3437 if (Flags.isInConsecutiveRegs()) { 3438 // If the array member was split into multiple registers, the first 3439 // needs to be aligned to the size of the full type. (Except for 3440 // ppcf128, which is only aligned as its f64 components.) 3441 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3442 Alignment = Align(OrigVT.getStoreSize()); 3443 else 3444 Alignment = Align(ArgVT.getStoreSize()); 3445 } 3446 3447 return Alignment; 3448 } 3449 3450 /// CalculateStackSlotUsed - Return whether this argument will use its 3451 /// stack slot (instead of being passed in registers). ArgOffset, 3452 /// AvailableFPRs, and AvailableVRs must hold the current argument 3453 /// position, and will be updated to account for this argument. 3454 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3455 unsigned PtrByteSize, unsigned LinkageSize, 3456 unsigned ParamAreaSize, unsigned &ArgOffset, 3457 unsigned &AvailableFPRs, 3458 unsigned &AvailableVRs) { 3459 bool UseMemory = false; 3460 3461 // Respect alignment of argument on the stack. 3462 Align Alignment = 3463 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3464 ArgOffset = alignTo(ArgOffset, Alignment); 3465 // If there's no space left in the argument save area, we must 3466 // use memory (this check also catches zero-sized arguments). 3467 if (ArgOffset >= LinkageSize + ParamAreaSize) 3468 UseMemory = true; 3469 3470 // Allocate argument on the stack. 3471 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3472 if (Flags.isInConsecutiveRegsLast()) 3473 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3474 // If we overran the argument save area, we must use memory 3475 // (this check catches arguments passed partially in memory) 3476 if (ArgOffset > LinkageSize + ParamAreaSize) 3477 UseMemory = true; 3478 3479 // However, if the argument is actually passed in an FPR or a VR, 3480 // we don't use memory after all. 3481 if (!Flags.isByVal()) { 3482 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3483 if (AvailableFPRs > 0) { 3484 --AvailableFPRs; 3485 return false; 3486 } 3487 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3488 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3489 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3490 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3491 if (AvailableVRs > 0) { 3492 --AvailableVRs; 3493 return false; 3494 } 3495 } 3496 3497 return UseMemory; 3498 } 3499 3500 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3501 /// ensure minimum alignment required for target. 3502 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3503 unsigned NumBytes) { 3504 return alignTo(NumBytes, Lowering->getStackAlign()); 3505 } 3506 3507 SDValue PPCTargetLowering::LowerFormalArguments( 3508 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3509 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3510 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3511 if (Subtarget.isAIXABI()) 3512 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3513 InVals); 3514 if (Subtarget.is64BitELFABI()) 3515 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3516 InVals); 3517 if (Subtarget.is32BitELFABI()) 3518 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3519 InVals); 3520 3521 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3522 InVals); 3523 } 3524 3525 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3526 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3527 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3528 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3529 3530 // 32-bit SVR4 ABI Stack Frame Layout: 3531 // +-----------------------------------+ 3532 // +--> | Back chain | 3533 // | +-----------------------------------+ 3534 // | | Floating-point register save area | 3535 // | +-----------------------------------+ 3536 // | | General register save area | 3537 // | +-----------------------------------+ 3538 // | | CR save word | 3539 // | +-----------------------------------+ 3540 // | | VRSAVE save word | 3541 // | +-----------------------------------+ 3542 // | | Alignment padding | 3543 // | +-----------------------------------+ 3544 // | | Vector register save area | 3545 // | +-----------------------------------+ 3546 // | | Local variable space | 3547 // | +-----------------------------------+ 3548 // | | Parameter list area | 3549 // | +-----------------------------------+ 3550 // | | LR save word | 3551 // | +-----------------------------------+ 3552 // SP--> +--- | Back chain | 3553 // +-----------------------------------+ 3554 // 3555 // Specifications: 3556 // System V Application Binary Interface PowerPC Processor Supplement 3557 // AltiVec Technology Programming Interface Manual 3558 3559 MachineFunction &MF = DAG.getMachineFunction(); 3560 MachineFrameInfo &MFI = MF.getFrameInfo(); 3561 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3562 3563 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3564 // Potential tail calls could cause overwriting of argument stack slots. 3565 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3566 (CallConv == CallingConv::Fast)); 3567 const Align PtrAlign(4); 3568 3569 // Assign locations to all of the incoming arguments. 3570 SmallVector<CCValAssign, 16> ArgLocs; 3571 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3572 *DAG.getContext()); 3573 3574 // Reserve space for the linkage area on the stack. 3575 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3576 CCInfo.AllocateStack(LinkageSize, PtrAlign); 3577 if (useSoftFloat()) 3578 CCInfo.PreAnalyzeFormalArguments(Ins); 3579 3580 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3581 CCInfo.clearWasPPCF128(); 3582 3583 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3584 CCValAssign &VA = ArgLocs[i]; 3585 3586 // Arguments stored in registers. 3587 if (VA.isRegLoc()) { 3588 const TargetRegisterClass *RC; 3589 EVT ValVT = VA.getValVT(); 3590 3591 switch (ValVT.getSimpleVT().SimpleTy) { 3592 default: 3593 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3594 case MVT::i1: 3595 case MVT::i32: 3596 RC = &PPC::GPRCRegClass; 3597 break; 3598 case MVT::f32: 3599 if (Subtarget.hasP8Vector()) 3600 RC = &PPC::VSSRCRegClass; 3601 else if (Subtarget.hasSPE()) 3602 RC = &PPC::GPRCRegClass; 3603 else 3604 RC = &PPC::F4RCRegClass; 3605 break; 3606 case MVT::f64: 3607 if (Subtarget.hasVSX()) 3608 RC = &PPC::VSFRCRegClass; 3609 else if (Subtarget.hasSPE()) 3610 // SPE passes doubles in GPR pairs. 3611 RC = &PPC::GPRCRegClass; 3612 else 3613 RC = &PPC::F8RCRegClass; 3614 break; 3615 case MVT::v16i8: 3616 case MVT::v8i16: 3617 case MVT::v4i32: 3618 RC = &PPC::VRRCRegClass; 3619 break; 3620 case MVT::v4f32: 3621 RC = &PPC::VRRCRegClass; 3622 break; 3623 case MVT::v2f64: 3624 case MVT::v2i64: 3625 RC = &PPC::VRRCRegClass; 3626 break; 3627 } 3628 3629 SDValue ArgValue; 3630 // Transform the arguments stored in physical registers into 3631 // virtual ones. 3632 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3633 assert(i + 1 < e && "No second half of double precision argument"); 3634 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3635 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3636 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3637 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3638 if (!Subtarget.isLittleEndian()) 3639 std::swap (ArgValueLo, ArgValueHi); 3640 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3641 ArgValueHi); 3642 } else { 3643 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3644 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3645 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3646 if (ValVT == MVT::i1) 3647 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3648 } 3649 3650 InVals.push_back(ArgValue); 3651 } else { 3652 // Argument stored in memory. 3653 assert(VA.isMemLoc()); 3654 3655 // Get the extended size of the argument type in stack 3656 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3657 // Get the actual size of the argument type 3658 unsigned ObjSize = VA.getValVT().getStoreSize(); 3659 unsigned ArgOffset = VA.getLocMemOffset(); 3660 // Stack objects in PPC32 are right justified. 3661 ArgOffset += ArgSize - ObjSize; 3662 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3663 3664 // Create load nodes to retrieve arguments from the stack. 3665 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3666 InVals.push_back( 3667 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3668 } 3669 } 3670 3671 // Assign locations to all of the incoming aggregate by value arguments. 3672 // Aggregates passed by value are stored in the local variable space of the 3673 // caller's stack frame, right above the parameter list area. 3674 SmallVector<CCValAssign, 16> ByValArgLocs; 3675 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3676 ByValArgLocs, *DAG.getContext()); 3677 3678 // Reserve stack space for the allocations in CCInfo. 3679 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 3680 3681 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3682 3683 // Area that is at least reserved in the caller of this function. 3684 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3685 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3686 3687 // Set the size that is at least reserved in caller of this function. Tail 3688 // call optimized function's reserved stack space needs to be aligned so that 3689 // taking the difference between two stack areas will result in an aligned 3690 // stack. 3691 MinReservedArea = 3692 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3693 FuncInfo->setMinReservedArea(MinReservedArea); 3694 3695 SmallVector<SDValue, 8> MemOps; 3696 3697 // If the function takes variable number of arguments, make a frame index for 3698 // the start of the first vararg value... for expansion of llvm.va_start. 3699 if (isVarArg) { 3700 static const MCPhysReg GPArgRegs[] = { 3701 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3702 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3703 }; 3704 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3705 3706 static const MCPhysReg FPArgRegs[] = { 3707 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3708 PPC::F8 3709 }; 3710 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3711 3712 if (useSoftFloat() || hasSPE()) 3713 NumFPArgRegs = 0; 3714 3715 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3716 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3717 3718 // Make room for NumGPArgRegs and NumFPArgRegs. 3719 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3720 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3721 3722 FuncInfo->setVarArgsStackOffset( 3723 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3724 CCInfo.getNextStackOffset(), true)); 3725 3726 FuncInfo->setVarArgsFrameIndex( 3727 MFI.CreateStackObject(Depth, Align(8), false)); 3728 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3729 3730 // The fixed integer arguments of a variadic function are stored to the 3731 // VarArgsFrameIndex on the stack so that they may be loaded by 3732 // dereferencing the result of va_next. 3733 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3734 // Get an existing live-in vreg, or add a new one. 3735 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3736 if (!VReg) 3737 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3738 3739 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3740 SDValue Store = 3741 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3742 MemOps.push_back(Store); 3743 // Increment the address by four for the next argument to store 3744 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3745 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3746 } 3747 3748 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3749 // is set. 3750 // The double arguments are stored to the VarArgsFrameIndex 3751 // on the stack. 3752 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3753 // Get an existing live-in vreg, or add a new one. 3754 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3755 if (!VReg) 3756 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3757 3758 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3759 SDValue Store = 3760 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3761 MemOps.push_back(Store); 3762 // Increment the address by eight for the next argument to store 3763 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3764 PtrVT); 3765 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3766 } 3767 } 3768 3769 if (!MemOps.empty()) 3770 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3771 3772 return Chain; 3773 } 3774 3775 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3776 // value to MVT::i64 and then truncate to the correct register size. 3777 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3778 EVT ObjectVT, SelectionDAG &DAG, 3779 SDValue ArgVal, 3780 const SDLoc &dl) const { 3781 if (Flags.isSExt()) 3782 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3783 DAG.getValueType(ObjectVT)); 3784 else if (Flags.isZExt()) 3785 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3786 DAG.getValueType(ObjectVT)); 3787 3788 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3789 } 3790 3791 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3792 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3793 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3794 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3795 // TODO: add description of PPC stack frame format, or at least some docs. 3796 // 3797 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3798 bool isLittleEndian = Subtarget.isLittleEndian(); 3799 MachineFunction &MF = DAG.getMachineFunction(); 3800 MachineFrameInfo &MFI = MF.getFrameInfo(); 3801 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3802 3803 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3804 "fastcc not supported on varargs functions"); 3805 3806 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3807 // Potential tail calls could cause overwriting of argument stack slots. 3808 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3809 (CallConv == CallingConv::Fast)); 3810 unsigned PtrByteSize = 8; 3811 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3812 3813 static const MCPhysReg GPR[] = { 3814 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3815 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3816 }; 3817 static const MCPhysReg VR[] = { 3818 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3819 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3820 }; 3821 3822 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3823 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3824 const unsigned Num_VR_Regs = array_lengthof(VR); 3825 3826 // Do a first pass over the arguments to determine whether the ABI 3827 // guarantees that our caller has allocated the parameter save area 3828 // on its stack frame. In the ELFv1 ABI, this is always the case; 3829 // in the ELFv2 ABI, it is true if this is a vararg function or if 3830 // any parameter is located in a stack slot. 3831 3832 bool HasParameterArea = !isELFv2ABI || isVarArg; 3833 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3834 unsigned NumBytes = LinkageSize; 3835 unsigned AvailableFPRs = Num_FPR_Regs; 3836 unsigned AvailableVRs = Num_VR_Regs; 3837 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3838 if (Ins[i].Flags.isNest()) 3839 continue; 3840 3841 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3842 PtrByteSize, LinkageSize, ParamAreaSize, 3843 NumBytes, AvailableFPRs, AvailableVRs)) 3844 HasParameterArea = true; 3845 } 3846 3847 // Add DAG nodes to load the arguments or copy them out of registers. On 3848 // entry to a function on PPC, the arguments start after the linkage area, 3849 // although the first ones are often in registers. 3850 3851 unsigned ArgOffset = LinkageSize; 3852 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3853 SmallVector<SDValue, 8> MemOps; 3854 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3855 unsigned CurArgIdx = 0; 3856 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3857 SDValue ArgVal; 3858 bool needsLoad = false; 3859 EVT ObjectVT = Ins[ArgNo].VT; 3860 EVT OrigVT = Ins[ArgNo].ArgVT; 3861 unsigned ObjSize = ObjectVT.getStoreSize(); 3862 unsigned ArgSize = ObjSize; 3863 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3864 if (Ins[ArgNo].isOrigArg()) { 3865 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3866 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3867 } 3868 // We re-align the argument offset for each argument, except when using the 3869 // fast calling convention, when we need to make sure we do that only when 3870 // we'll actually use a stack slot. 3871 unsigned CurArgOffset; 3872 Align Alignment; 3873 auto ComputeArgOffset = [&]() { 3874 /* Respect alignment of argument on the stack. */ 3875 Alignment = 3876 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3877 ArgOffset = alignTo(ArgOffset, Alignment); 3878 CurArgOffset = ArgOffset; 3879 }; 3880 3881 if (CallConv != CallingConv::Fast) { 3882 ComputeArgOffset(); 3883 3884 /* Compute GPR index associated with argument offset. */ 3885 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3886 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3887 } 3888 3889 // FIXME the codegen can be much improved in some cases. 3890 // We do not have to keep everything in memory. 3891 if (Flags.isByVal()) { 3892 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3893 3894 if (CallConv == CallingConv::Fast) 3895 ComputeArgOffset(); 3896 3897 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3898 ObjSize = Flags.getByValSize(); 3899 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3900 // Empty aggregate parameters do not take up registers. Examples: 3901 // struct { } a; 3902 // union { } b; 3903 // int c[0]; 3904 // etc. However, we have to provide a place-holder in InVals, so 3905 // pretend we have an 8-byte item at the current address for that 3906 // purpose. 3907 if (!ObjSize) { 3908 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3909 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3910 InVals.push_back(FIN); 3911 continue; 3912 } 3913 3914 // Create a stack object covering all stack doublewords occupied 3915 // by the argument. If the argument is (fully or partially) on 3916 // the stack, or if the argument is fully in registers but the 3917 // caller has allocated the parameter save anyway, we can refer 3918 // directly to the caller's stack frame. Otherwise, create a 3919 // local copy in our own frame. 3920 int FI; 3921 if (HasParameterArea || 3922 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3923 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3924 else 3925 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3926 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3927 3928 // Handle aggregates smaller than 8 bytes. 3929 if (ObjSize < PtrByteSize) { 3930 // The value of the object is its address, which differs from the 3931 // address of the enclosing doubleword on big-endian systems. 3932 SDValue Arg = FIN; 3933 if (!isLittleEndian) { 3934 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3935 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3936 } 3937 InVals.push_back(Arg); 3938 3939 if (GPR_idx != Num_GPR_Regs) { 3940 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3941 FuncInfo->addLiveInAttr(VReg, Flags); 3942 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3943 SDValue Store; 3944 3945 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3946 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3947 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3948 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3949 MachinePointerInfo(&*FuncArg), ObjType); 3950 } else { 3951 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3952 // store the whole register as-is to the parameter save area 3953 // slot. 3954 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3955 MachinePointerInfo(&*FuncArg)); 3956 } 3957 3958 MemOps.push_back(Store); 3959 } 3960 // Whether we copied from a register or not, advance the offset 3961 // into the parameter save area by a full doubleword. 3962 ArgOffset += PtrByteSize; 3963 continue; 3964 } 3965 3966 // The value of the object is its address, which is the address of 3967 // its first stack doubleword. 3968 InVals.push_back(FIN); 3969 3970 // Store whatever pieces of the object are in registers to memory. 3971 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3972 if (GPR_idx == Num_GPR_Regs) 3973 break; 3974 3975 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3976 FuncInfo->addLiveInAttr(VReg, Flags); 3977 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3978 SDValue Addr = FIN; 3979 if (j) { 3980 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3981 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3982 } 3983 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3984 MachinePointerInfo(&*FuncArg, j)); 3985 MemOps.push_back(Store); 3986 ++GPR_idx; 3987 } 3988 ArgOffset += ArgSize; 3989 continue; 3990 } 3991 3992 switch (ObjectVT.getSimpleVT().SimpleTy) { 3993 default: llvm_unreachable("Unhandled argument type!"); 3994 case MVT::i1: 3995 case MVT::i32: 3996 case MVT::i64: 3997 if (Flags.isNest()) { 3998 // The 'nest' parameter, if any, is passed in R11. 3999 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4000 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4001 4002 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4003 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4004 4005 break; 4006 } 4007 4008 // These can be scalar arguments or elements of an integer array type 4009 // passed directly. Clang may use those instead of "byval" aggregate 4010 // types to avoid forcing arguments to memory unnecessarily. 4011 if (GPR_idx != Num_GPR_Regs) { 4012 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4013 FuncInfo->addLiveInAttr(VReg, Flags); 4014 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4015 4016 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4017 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4018 // value to MVT::i64 and then truncate to the correct register size. 4019 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4020 } else { 4021 if (CallConv == CallingConv::Fast) 4022 ComputeArgOffset(); 4023 4024 needsLoad = true; 4025 ArgSize = PtrByteSize; 4026 } 4027 if (CallConv != CallingConv::Fast || needsLoad) 4028 ArgOffset += 8; 4029 break; 4030 4031 case MVT::f32: 4032 case MVT::f64: 4033 // These can be scalar arguments or elements of a float array type 4034 // passed directly. The latter are used to implement ELFv2 homogenous 4035 // float aggregates. 4036 if (FPR_idx != Num_FPR_Regs) { 4037 unsigned VReg; 4038 4039 if (ObjectVT == MVT::f32) 4040 VReg = MF.addLiveIn(FPR[FPR_idx], 4041 Subtarget.hasP8Vector() 4042 ? &PPC::VSSRCRegClass 4043 : &PPC::F4RCRegClass); 4044 else 4045 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4046 ? &PPC::VSFRCRegClass 4047 : &PPC::F8RCRegClass); 4048 4049 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4050 ++FPR_idx; 4051 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4052 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4053 // once we support fp <-> gpr moves. 4054 4055 // This can only ever happen in the presence of f32 array types, 4056 // since otherwise we never run out of FPRs before running out 4057 // of GPRs. 4058 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4059 FuncInfo->addLiveInAttr(VReg, Flags); 4060 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4061 4062 if (ObjectVT == MVT::f32) { 4063 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4064 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4065 DAG.getConstant(32, dl, MVT::i32)); 4066 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4067 } 4068 4069 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4070 } else { 4071 if (CallConv == CallingConv::Fast) 4072 ComputeArgOffset(); 4073 4074 needsLoad = true; 4075 } 4076 4077 // When passing an array of floats, the array occupies consecutive 4078 // space in the argument area; only round up to the next doubleword 4079 // at the end of the array. Otherwise, each float takes 8 bytes. 4080 if (CallConv != CallingConv::Fast || needsLoad) { 4081 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4082 ArgOffset += ArgSize; 4083 if (Flags.isInConsecutiveRegsLast()) 4084 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4085 } 4086 break; 4087 case MVT::v4f32: 4088 case MVT::v4i32: 4089 case MVT::v8i16: 4090 case MVT::v16i8: 4091 case MVT::v2f64: 4092 case MVT::v2i64: 4093 case MVT::v1i128: 4094 case MVT::f128: 4095 // These can be scalar arguments or elements of a vector array type 4096 // passed directly. The latter are used to implement ELFv2 homogenous 4097 // vector aggregates. 4098 if (VR_idx != Num_VR_Regs) { 4099 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4100 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4101 ++VR_idx; 4102 } else { 4103 if (CallConv == CallingConv::Fast) 4104 ComputeArgOffset(); 4105 needsLoad = true; 4106 } 4107 if (CallConv != CallingConv::Fast || needsLoad) 4108 ArgOffset += 16; 4109 break; 4110 } 4111 4112 // We need to load the argument to a virtual register if we determined 4113 // above that we ran out of physical registers of the appropriate type. 4114 if (needsLoad) { 4115 if (ObjSize < ArgSize && !isLittleEndian) 4116 CurArgOffset += ArgSize - ObjSize; 4117 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4118 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4119 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4120 } 4121 4122 InVals.push_back(ArgVal); 4123 } 4124 4125 // Area that is at least reserved in the caller of this function. 4126 unsigned MinReservedArea; 4127 if (HasParameterArea) 4128 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4129 else 4130 MinReservedArea = LinkageSize; 4131 4132 // Set the size that is at least reserved in caller of this function. Tail 4133 // call optimized functions' reserved stack space needs to be aligned so that 4134 // taking the difference between two stack areas will result in an aligned 4135 // stack. 4136 MinReservedArea = 4137 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4138 FuncInfo->setMinReservedArea(MinReservedArea); 4139 4140 // If the function takes variable number of arguments, make a frame index for 4141 // the start of the first vararg value... for expansion of llvm.va_start. 4142 // On ELFv2ABI spec, it writes: 4143 // C programs that are intended to be *portable* across different compilers 4144 // and architectures must use the header file <stdarg.h> to deal with variable 4145 // argument lists. 4146 if (isVarArg && MFI.hasVAStart()) { 4147 int Depth = ArgOffset; 4148 4149 FuncInfo->setVarArgsFrameIndex( 4150 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4151 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4152 4153 // If this function is vararg, store any remaining integer argument regs 4154 // to their spots on the stack so that they may be loaded by dereferencing 4155 // the result of va_next. 4156 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4157 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4158 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4159 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4160 SDValue Store = 4161 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4162 MemOps.push_back(Store); 4163 // Increment the address by four for the next argument to store 4164 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4165 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4166 } 4167 } 4168 4169 if (!MemOps.empty()) 4170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4171 4172 return Chain; 4173 } 4174 4175 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4176 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4177 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4178 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4179 // TODO: add description of PPC stack frame format, or at least some docs. 4180 // 4181 MachineFunction &MF = DAG.getMachineFunction(); 4182 MachineFrameInfo &MFI = MF.getFrameInfo(); 4183 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4184 4185 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4186 bool isPPC64 = PtrVT == MVT::i64; 4187 // Potential tail calls could cause overwriting of argument stack slots. 4188 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4189 (CallConv == CallingConv::Fast)); 4190 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4191 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4192 unsigned ArgOffset = LinkageSize; 4193 // Area that is at least reserved in caller of this function. 4194 unsigned MinReservedArea = ArgOffset; 4195 4196 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4197 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4198 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4199 }; 4200 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4201 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4202 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4203 }; 4204 static const MCPhysReg VR[] = { 4205 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4206 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4207 }; 4208 4209 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4210 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4211 const unsigned Num_VR_Regs = array_lengthof( VR); 4212 4213 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4214 4215 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4216 4217 // In 32-bit non-varargs functions, the stack space for vectors is after the 4218 // stack space for non-vectors. We do not use this space unless we have 4219 // too many vectors to fit in registers, something that only occurs in 4220 // constructed examples:), but we have to walk the arglist to figure 4221 // that out...for the pathological case, compute VecArgOffset as the 4222 // start of the vector parameter area. Computing VecArgOffset is the 4223 // entire point of the following loop. 4224 unsigned VecArgOffset = ArgOffset; 4225 if (!isVarArg && !isPPC64) { 4226 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4227 ++ArgNo) { 4228 EVT ObjectVT = Ins[ArgNo].VT; 4229 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4230 4231 if (Flags.isByVal()) { 4232 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4233 unsigned ObjSize = Flags.getByValSize(); 4234 unsigned ArgSize = 4235 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4236 VecArgOffset += ArgSize; 4237 continue; 4238 } 4239 4240 switch(ObjectVT.getSimpleVT().SimpleTy) { 4241 default: llvm_unreachable("Unhandled argument type!"); 4242 case MVT::i1: 4243 case MVT::i32: 4244 case MVT::f32: 4245 VecArgOffset += 4; 4246 break; 4247 case MVT::i64: // PPC64 4248 case MVT::f64: 4249 // FIXME: We are guaranteed to be !isPPC64 at this point. 4250 // Does MVT::i64 apply? 4251 VecArgOffset += 8; 4252 break; 4253 case MVT::v4f32: 4254 case MVT::v4i32: 4255 case MVT::v8i16: 4256 case MVT::v16i8: 4257 // Nothing to do, we're only looking at Nonvector args here. 4258 break; 4259 } 4260 } 4261 } 4262 // We've found where the vector parameter area in memory is. Skip the 4263 // first 12 parameters; these don't use that memory. 4264 VecArgOffset = ((VecArgOffset+15)/16)*16; 4265 VecArgOffset += 12*16; 4266 4267 // Add DAG nodes to load the arguments or copy them out of registers. On 4268 // entry to a function on PPC, the arguments start after the linkage area, 4269 // although the first ones are often in registers. 4270 4271 SmallVector<SDValue, 8> MemOps; 4272 unsigned nAltivecParamsAtEnd = 0; 4273 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4274 unsigned CurArgIdx = 0; 4275 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4276 SDValue ArgVal; 4277 bool needsLoad = false; 4278 EVT ObjectVT = Ins[ArgNo].VT; 4279 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4280 unsigned ArgSize = ObjSize; 4281 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4282 if (Ins[ArgNo].isOrigArg()) { 4283 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4284 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4285 } 4286 unsigned CurArgOffset = ArgOffset; 4287 4288 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4289 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4290 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4291 if (isVarArg || isPPC64) { 4292 MinReservedArea = ((MinReservedArea+15)/16)*16; 4293 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4294 Flags, 4295 PtrByteSize); 4296 } else nAltivecParamsAtEnd++; 4297 } else 4298 // Calculate min reserved area. 4299 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4300 Flags, 4301 PtrByteSize); 4302 4303 // FIXME the codegen can be much improved in some cases. 4304 // We do not have to keep everything in memory. 4305 if (Flags.isByVal()) { 4306 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4307 4308 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4309 ObjSize = Flags.getByValSize(); 4310 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4311 // Objects of size 1 and 2 are right justified, everything else is 4312 // left justified. This means the memory address is adjusted forwards. 4313 if (ObjSize==1 || ObjSize==2) { 4314 CurArgOffset = CurArgOffset + (4 - ObjSize); 4315 } 4316 // The value of the object is its address. 4317 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4318 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4319 InVals.push_back(FIN); 4320 if (ObjSize==1 || ObjSize==2) { 4321 if (GPR_idx != Num_GPR_Regs) { 4322 unsigned VReg; 4323 if (isPPC64) 4324 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4325 else 4326 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4327 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4328 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4329 SDValue Store = 4330 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4331 MachinePointerInfo(&*FuncArg), ObjType); 4332 MemOps.push_back(Store); 4333 ++GPR_idx; 4334 } 4335 4336 ArgOffset += PtrByteSize; 4337 4338 continue; 4339 } 4340 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4341 // Store whatever pieces of the object are in registers 4342 // to memory. ArgOffset will be the address of the beginning 4343 // of the object. 4344 if (GPR_idx != Num_GPR_Regs) { 4345 unsigned VReg; 4346 if (isPPC64) 4347 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4348 else 4349 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4350 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4351 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4352 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4353 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4354 MachinePointerInfo(&*FuncArg, j)); 4355 MemOps.push_back(Store); 4356 ++GPR_idx; 4357 ArgOffset += PtrByteSize; 4358 } else { 4359 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4360 break; 4361 } 4362 } 4363 continue; 4364 } 4365 4366 switch (ObjectVT.getSimpleVT().SimpleTy) { 4367 default: llvm_unreachable("Unhandled argument type!"); 4368 case MVT::i1: 4369 case MVT::i32: 4370 if (!isPPC64) { 4371 if (GPR_idx != Num_GPR_Regs) { 4372 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4373 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4374 4375 if (ObjectVT == MVT::i1) 4376 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4377 4378 ++GPR_idx; 4379 } else { 4380 needsLoad = true; 4381 ArgSize = PtrByteSize; 4382 } 4383 // All int arguments reserve stack space in the Darwin ABI. 4384 ArgOffset += PtrByteSize; 4385 break; 4386 } 4387 LLVM_FALLTHROUGH; 4388 case MVT::i64: // PPC64 4389 if (GPR_idx != Num_GPR_Regs) { 4390 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4391 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4392 4393 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4394 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4395 // value to MVT::i64 and then truncate to the correct register size. 4396 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4397 4398 ++GPR_idx; 4399 } else { 4400 needsLoad = true; 4401 ArgSize = PtrByteSize; 4402 } 4403 // All int arguments reserve stack space in the Darwin ABI. 4404 ArgOffset += 8; 4405 break; 4406 4407 case MVT::f32: 4408 case MVT::f64: 4409 // Every 4 bytes of argument space consumes one of the GPRs available for 4410 // argument passing. 4411 if (GPR_idx != Num_GPR_Regs) { 4412 ++GPR_idx; 4413 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4414 ++GPR_idx; 4415 } 4416 if (FPR_idx != Num_FPR_Regs) { 4417 unsigned VReg; 4418 4419 if (ObjectVT == MVT::f32) 4420 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4421 else 4422 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4423 4424 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4425 ++FPR_idx; 4426 } else { 4427 needsLoad = true; 4428 } 4429 4430 // All FP arguments reserve stack space in the Darwin ABI. 4431 ArgOffset += isPPC64 ? 8 : ObjSize; 4432 break; 4433 case MVT::v4f32: 4434 case MVT::v4i32: 4435 case MVT::v8i16: 4436 case MVT::v16i8: 4437 // Note that vector arguments in registers don't reserve stack space, 4438 // except in varargs functions. 4439 if (VR_idx != Num_VR_Regs) { 4440 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4441 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4442 if (isVarArg) { 4443 while ((ArgOffset % 16) != 0) { 4444 ArgOffset += PtrByteSize; 4445 if (GPR_idx != Num_GPR_Regs) 4446 GPR_idx++; 4447 } 4448 ArgOffset += 16; 4449 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4450 } 4451 ++VR_idx; 4452 } else { 4453 if (!isVarArg && !isPPC64) { 4454 // Vectors go after all the nonvectors. 4455 CurArgOffset = VecArgOffset; 4456 VecArgOffset += 16; 4457 } else { 4458 // Vectors are aligned. 4459 ArgOffset = ((ArgOffset+15)/16)*16; 4460 CurArgOffset = ArgOffset; 4461 ArgOffset += 16; 4462 } 4463 needsLoad = true; 4464 } 4465 break; 4466 } 4467 4468 // We need to load the argument to a virtual register if we determined above 4469 // that we ran out of physical registers of the appropriate type. 4470 if (needsLoad) { 4471 int FI = MFI.CreateFixedObject(ObjSize, 4472 CurArgOffset + (ArgSize - ObjSize), 4473 isImmutable); 4474 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4475 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4476 } 4477 4478 InVals.push_back(ArgVal); 4479 } 4480 4481 // Allow for Altivec parameters at the end, if needed. 4482 if (nAltivecParamsAtEnd) { 4483 MinReservedArea = ((MinReservedArea+15)/16)*16; 4484 MinReservedArea += 16*nAltivecParamsAtEnd; 4485 } 4486 4487 // Area that is at least reserved in the caller of this function. 4488 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4489 4490 // Set the size that is at least reserved in caller of this function. Tail 4491 // call optimized functions' reserved stack space needs to be aligned so that 4492 // taking the difference between two stack areas will result in an aligned 4493 // stack. 4494 MinReservedArea = 4495 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4496 FuncInfo->setMinReservedArea(MinReservedArea); 4497 4498 // If the function takes variable number of arguments, make a frame index for 4499 // the start of the first vararg value... for expansion of llvm.va_start. 4500 if (isVarArg) { 4501 int Depth = ArgOffset; 4502 4503 FuncInfo->setVarArgsFrameIndex( 4504 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4505 Depth, true)); 4506 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4507 4508 // If this function is vararg, store any remaining integer argument regs 4509 // to their spots on the stack so that they may be loaded by dereferencing 4510 // the result of va_next. 4511 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4512 unsigned VReg; 4513 4514 if (isPPC64) 4515 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4516 else 4517 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4518 4519 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4520 SDValue Store = 4521 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4522 MemOps.push_back(Store); 4523 // Increment the address by four for the next argument to store 4524 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4525 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4526 } 4527 } 4528 4529 if (!MemOps.empty()) 4530 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4531 4532 return Chain; 4533 } 4534 4535 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4536 /// adjusted to accommodate the arguments for the tailcall. 4537 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4538 unsigned ParamSize) { 4539 4540 if (!isTailCall) return 0; 4541 4542 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4543 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4544 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4545 // Remember only if the new adjustment is bigger. 4546 if (SPDiff < FI->getTailCallSPDelta()) 4547 FI->setTailCallSPDelta(SPDiff); 4548 4549 return SPDiff; 4550 } 4551 4552 static bool isFunctionGlobalAddress(SDValue Callee); 4553 4554 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4555 const TargetMachine &TM) { 4556 // It does not make sense to call callsShareTOCBase() with a caller that 4557 // is PC Relative since PC Relative callers do not have a TOC. 4558 #ifndef NDEBUG 4559 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4560 assert(!STICaller->isUsingPCRelativeCalls() && 4561 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4562 #endif 4563 4564 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4565 // don't have enough information to determine if the caller and callee share 4566 // the same TOC base, so we have to pessimistically assume they don't for 4567 // correctness. 4568 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4569 if (!G) 4570 return false; 4571 4572 const GlobalValue *GV = G->getGlobal(); 4573 4574 // If the callee is preemptable, then the static linker will use a plt-stub 4575 // which saves the toc to the stack, and needs a nop after the call 4576 // instruction to convert to a toc-restore. 4577 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4578 return false; 4579 4580 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4581 // We may need a TOC restore in the situation where the caller requires a 4582 // valid TOC but the callee is PC Relative and does not. 4583 const Function *F = dyn_cast<Function>(GV); 4584 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4585 4586 // If we have an Alias we can try to get the function from there. 4587 if (Alias) { 4588 const GlobalObject *GlobalObj = Alias->getBaseObject(); 4589 F = dyn_cast<Function>(GlobalObj); 4590 } 4591 4592 // If we still have no valid function pointer we do not have enough 4593 // information to determine if the callee uses PC Relative calls so we must 4594 // assume that it does. 4595 if (!F) 4596 return false; 4597 4598 // If the callee uses PC Relative we cannot guarantee that the callee won't 4599 // clobber the TOC of the caller and so we must assume that the two 4600 // functions do not share a TOC base. 4601 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4602 if (STICallee->isUsingPCRelativeCalls()) 4603 return false; 4604 4605 // The medium and large code models are expected to provide a sufficiently 4606 // large TOC to provide all data addressing needs of a module with a 4607 // single TOC. 4608 if (CodeModel::Medium == TM.getCodeModel() || 4609 CodeModel::Large == TM.getCodeModel()) 4610 return true; 4611 4612 // Otherwise we need to ensure callee and caller are in the same section, 4613 // since the linker may allocate multiple TOCs, and we don't know which 4614 // sections will belong to the same TOC base. 4615 if (!GV->isStrongDefinitionForLinker()) 4616 return false; 4617 4618 // Any explicitly-specified sections and section prefixes must also match. 4619 // Also, if we're using -ffunction-sections, then each function is always in 4620 // a different section (the same is true for COMDAT functions). 4621 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4622 GV->getSection() != Caller->getSection()) 4623 return false; 4624 if (const auto *F = dyn_cast<Function>(GV)) { 4625 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4626 return false; 4627 } 4628 4629 return true; 4630 } 4631 4632 static bool 4633 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4634 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4635 assert(Subtarget.is64BitELFABI()); 4636 4637 const unsigned PtrByteSize = 8; 4638 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4639 4640 static const MCPhysReg GPR[] = { 4641 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4642 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4643 }; 4644 static const MCPhysReg VR[] = { 4645 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4646 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4647 }; 4648 4649 const unsigned NumGPRs = array_lengthof(GPR); 4650 const unsigned NumFPRs = 13; 4651 const unsigned NumVRs = array_lengthof(VR); 4652 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4653 4654 unsigned NumBytes = LinkageSize; 4655 unsigned AvailableFPRs = NumFPRs; 4656 unsigned AvailableVRs = NumVRs; 4657 4658 for (const ISD::OutputArg& Param : Outs) { 4659 if (Param.Flags.isNest()) continue; 4660 4661 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4662 LinkageSize, ParamAreaSize, NumBytes, 4663 AvailableFPRs, AvailableVRs)) 4664 return true; 4665 } 4666 return false; 4667 } 4668 4669 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4670 if (CB.arg_size() != CallerFn->arg_size()) 4671 return false; 4672 4673 auto CalleeArgIter = CB.arg_begin(); 4674 auto CalleeArgEnd = CB.arg_end(); 4675 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4676 4677 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4678 const Value* CalleeArg = *CalleeArgIter; 4679 const Value* CallerArg = &(*CallerArgIter); 4680 if (CalleeArg == CallerArg) 4681 continue; 4682 4683 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4684 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4685 // } 4686 // 1st argument of callee is undef and has the same type as caller. 4687 if (CalleeArg->getType() == CallerArg->getType() && 4688 isa<UndefValue>(CalleeArg)) 4689 continue; 4690 4691 return false; 4692 } 4693 4694 return true; 4695 } 4696 4697 // Returns true if TCO is possible between the callers and callees 4698 // calling conventions. 4699 static bool 4700 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4701 CallingConv::ID CalleeCC) { 4702 // Tail calls are possible with fastcc and ccc. 4703 auto isTailCallableCC = [] (CallingConv::ID CC){ 4704 return CC == CallingConv::C || CC == CallingConv::Fast; 4705 }; 4706 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4707 return false; 4708 4709 // We can safely tail call both fastcc and ccc callees from a c calling 4710 // convention caller. If the caller is fastcc, we may have less stack space 4711 // than a non-fastcc caller with the same signature so disable tail-calls in 4712 // that case. 4713 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4714 } 4715 4716 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4717 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4718 const SmallVectorImpl<ISD::OutputArg> &Outs, 4719 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4720 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4721 4722 if (DisableSCO && !TailCallOpt) return false; 4723 4724 // Variadic argument functions are not supported. 4725 if (isVarArg) return false; 4726 4727 auto &Caller = DAG.getMachineFunction().getFunction(); 4728 // Check that the calling conventions are compatible for tco. 4729 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4730 return false; 4731 4732 // Caller contains any byval parameter is not supported. 4733 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4734 return false; 4735 4736 // Callee contains any byval parameter is not supported, too. 4737 // Note: This is a quick work around, because in some cases, e.g. 4738 // caller's stack size > callee's stack size, we are still able to apply 4739 // sibling call optimization. For example, gcc is able to do SCO for caller1 4740 // in the following example, but not for caller2. 4741 // struct test { 4742 // long int a; 4743 // char ary[56]; 4744 // } gTest; 4745 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4746 // b->a = v.a; 4747 // return 0; 4748 // } 4749 // void caller1(struct test a, struct test c, struct test *b) { 4750 // callee(gTest, b); } 4751 // void caller2(struct test *b) { callee(gTest, b); } 4752 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4753 return false; 4754 4755 // If callee and caller use different calling conventions, we cannot pass 4756 // parameters on stack since offsets for the parameter area may be different. 4757 if (Caller.getCallingConv() != CalleeCC && 4758 needStackSlotPassParameters(Subtarget, Outs)) 4759 return false; 4760 4761 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4762 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4763 // callee potentially have different TOC bases then we cannot tail call since 4764 // we need to restore the TOC pointer after the call. 4765 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4766 // We cannot guarantee this for indirect calls or calls to external functions. 4767 // When PC-Relative addressing is used, the concept of the TOC is no longer 4768 // applicable so this check is not required. 4769 // Check first for indirect calls. 4770 if (!Subtarget.isUsingPCRelativeCalls() && 4771 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4772 return false; 4773 4774 // Check if we share the TOC base. 4775 if (!Subtarget.isUsingPCRelativeCalls() && 4776 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4777 return false; 4778 4779 // TCO allows altering callee ABI, so we don't have to check further. 4780 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4781 return true; 4782 4783 if (DisableSCO) return false; 4784 4785 // If callee use the same argument list that caller is using, then we can 4786 // apply SCO on this case. If it is not, then we need to check if callee needs 4787 // stack for passing arguments. 4788 // PC Relative tail calls may not have a CallBase. 4789 // If there is no CallBase we cannot verify if we have the same argument 4790 // list so assume that we don't have the same argument list. 4791 if (CB && !hasSameArgumentList(&Caller, *CB) && 4792 needStackSlotPassParameters(Subtarget, Outs)) 4793 return false; 4794 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4795 return false; 4796 4797 return true; 4798 } 4799 4800 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4801 /// for tail call optimization. Targets which want to do tail call 4802 /// optimization should implement this function. 4803 bool 4804 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4805 CallingConv::ID CalleeCC, 4806 bool isVarArg, 4807 const SmallVectorImpl<ISD::InputArg> &Ins, 4808 SelectionDAG& DAG) const { 4809 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4810 return false; 4811 4812 // Variable argument functions are not supported. 4813 if (isVarArg) 4814 return false; 4815 4816 MachineFunction &MF = DAG.getMachineFunction(); 4817 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4818 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4819 // Functions containing by val parameters are not supported. 4820 for (unsigned i = 0; i != Ins.size(); i++) { 4821 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4822 if (Flags.isByVal()) return false; 4823 } 4824 4825 // Non-PIC/GOT tail calls are supported. 4826 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4827 return true; 4828 4829 // At the moment we can only do local tail calls (in same module, hidden 4830 // or protected) if we are generating PIC. 4831 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4832 return G->getGlobal()->hasHiddenVisibility() 4833 || G->getGlobal()->hasProtectedVisibility(); 4834 } 4835 4836 return false; 4837 } 4838 4839 /// isCallCompatibleAddress - Return the immediate to use if the specified 4840 /// 32-bit value is representable in the immediate field of a BxA instruction. 4841 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4842 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4843 if (!C) return nullptr; 4844 4845 int Addr = C->getZExtValue(); 4846 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4847 SignExtend32<26>(Addr) != Addr) 4848 return nullptr; // Top 6 bits have to be sext of immediate. 4849 4850 return DAG 4851 .getConstant( 4852 (int)C->getZExtValue() >> 2, SDLoc(Op), 4853 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4854 .getNode(); 4855 } 4856 4857 namespace { 4858 4859 struct TailCallArgumentInfo { 4860 SDValue Arg; 4861 SDValue FrameIdxOp; 4862 int FrameIdx = 0; 4863 4864 TailCallArgumentInfo() = default; 4865 }; 4866 4867 } // end anonymous namespace 4868 4869 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4870 static void StoreTailCallArgumentsToStackSlot( 4871 SelectionDAG &DAG, SDValue Chain, 4872 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4873 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4874 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4875 SDValue Arg = TailCallArgs[i].Arg; 4876 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4877 int FI = TailCallArgs[i].FrameIdx; 4878 // Store relative to framepointer. 4879 MemOpChains.push_back(DAG.getStore( 4880 Chain, dl, Arg, FIN, 4881 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4882 } 4883 } 4884 4885 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4886 /// the appropriate stack slot for the tail call optimized function call. 4887 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4888 SDValue OldRetAddr, SDValue OldFP, 4889 int SPDiff, const SDLoc &dl) { 4890 if (SPDiff) { 4891 // Calculate the new stack slot for the return address. 4892 MachineFunction &MF = DAG.getMachineFunction(); 4893 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4894 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4895 bool isPPC64 = Subtarget.isPPC64(); 4896 int SlotSize = isPPC64 ? 8 : 4; 4897 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4898 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4899 NewRetAddrLoc, true); 4900 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4901 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4902 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4903 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4904 } 4905 return Chain; 4906 } 4907 4908 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4909 /// the position of the argument. 4910 static void 4911 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4912 SDValue Arg, int SPDiff, unsigned ArgOffset, 4913 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4914 int Offset = ArgOffset + SPDiff; 4915 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4916 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4917 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4918 SDValue FIN = DAG.getFrameIndex(FI, VT); 4919 TailCallArgumentInfo Info; 4920 Info.Arg = Arg; 4921 Info.FrameIdxOp = FIN; 4922 Info.FrameIdx = FI; 4923 TailCallArguments.push_back(Info); 4924 } 4925 4926 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4927 /// stack slot. Returns the chain as result and the loaded frame pointers in 4928 /// LROpOut/FPOpout. Used when tail calling. 4929 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4930 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4931 SDValue &FPOpOut, const SDLoc &dl) const { 4932 if (SPDiff) { 4933 // Load the LR and FP stack slot for later adjusting. 4934 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4935 LROpOut = getReturnAddrFrameIndex(DAG); 4936 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4937 Chain = SDValue(LROpOut.getNode(), 1); 4938 } 4939 return Chain; 4940 } 4941 4942 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4943 /// by "Src" to address "Dst" of size "Size". Alignment information is 4944 /// specified by the specific parameter attribute. The copy will be passed as 4945 /// a byval function parameter. 4946 /// Sometimes what we are copying is the end of a larger object, the part that 4947 /// does not fit in registers. 4948 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4949 SDValue Chain, ISD::ArgFlagsTy Flags, 4950 SelectionDAG &DAG, const SDLoc &dl) { 4951 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4952 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4953 Flags.getNonZeroByValAlign(), false, false, false, 4954 MachinePointerInfo(), MachinePointerInfo()); 4955 } 4956 4957 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4958 /// tail calls. 4959 static void LowerMemOpCallTo( 4960 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4961 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4962 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4963 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4964 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4965 if (!isTailCall) { 4966 if (isVector) { 4967 SDValue StackPtr; 4968 if (isPPC64) 4969 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4970 else 4971 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4972 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4973 DAG.getConstant(ArgOffset, dl, PtrVT)); 4974 } 4975 MemOpChains.push_back( 4976 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4977 // Calculate and remember argument location. 4978 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4979 TailCallArguments); 4980 } 4981 4982 static void 4983 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4984 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4985 SDValue FPOp, 4986 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4987 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4988 // might overwrite each other in case of tail call optimization. 4989 SmallVector<SDValue, 8> MemOpChains2; 4990 // Do not flag preceding copytoreg stuff together with the following stuff. 4991 InFlag = SDValue(); 4992 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4993 MemOpChains2, dl); 4994 if (!MemOpChains2.empty()) 4995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4996 4997 // Store the return address to the appropriate stack slot. 4998 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4999 5000 // Emit callseq_end just before tailcall node. 5001 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5002 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 5003 InFlag = Chain.getValue(1); 5004 } 5005 5006 // Is this global address that of a function that can be called by name? (as 5007 // opposed to something that must hold a descriptor for an indirect call). 5008 static bool isFunctionGlobalAddress(SDValue Callee) { 5009 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5010 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5011 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5012 return false; 5013 5014 return G->getGlobal()->getValueType()->isFunctionTy(); 5015 } 5016 5017 return false; 5018 } 5019 5020 SDValue PPCTargetLowering::LowerCallResult( 5021 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5022 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5023 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5024 SmallVector<CCValAssign, 16> RVLocs; 5025 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5026 *DAG.getContext()); 5027 5028 CCRetInfo.AnalyzeCallResult( 5029 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5030 ? RetCC_PPC_Cold 5031 : RetCC_PPC); 5032 5033 // Copy all of the result registers out of their specified physreg. 5034 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5035 CCValAssign &VA = RVLocs[i]; 5036 assert(VA.isRegLoc() && "Can only return in registers!"); 5037 5038 SDValue Val; 5039 5040 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5041 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5042 InFlag); 5043 Chain = Lo.getValue(1); 5044 InFlag = Lo.getValue(2); 5045 VA = RVLocs[++i]; // skip ahead to next loc 5046 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5047 InFlag); 5048 Chain = Hi.getValue(1); 5049 InFlag = Hi.getValue(2); 5050 if (!Subtarget.isLittleEndian()) 5051 std::swap (Lo, Hi); 5052 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5053 } else { 5054 Val = DAG.getCopyFromReg(Chain, dl, 5055 VA.getLocReg(), VA.getLocVT(), InFlag); 5056 Chain = Val.getValue(1); 5057 InFlag = Val.getValue(2); 5058 } 5059 5060 switch (VA.getLocInfo()) { 5061 default: llvm_unreachable("Unknown loc info!"); 5062 case CCValAssign::Full: break; 5063 case CCValAssign::AExt: 5064 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5065 break; 5066 case CCValAssign::ZExt: 5067 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5068 DAG.getValueType(VA.getValVT())); 5069 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5070 break; 5071 case CCValAssign::SExt: 5072 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5073 DAG.getValueType(VA.getValVT())); 5074 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5075 break; 5076 } 5077 5078 InVals.push_back(Val); 5079 } 5080 5081 return Chain; 5082 } 5083 5084 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5085 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5086 // PatchPoint calls are not indirect. 5087 if (isPatchPoint) 5088 return false; 5089 5090 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5091 return false; 5092 5093 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5094 // becuase the immediate function pointer points to a descriptor instead of 5095 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5096 // pointer immediate points to the global entry point, while the BLA would 5097 // need to jump to the local entry point (see rL211174). 5098 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5099 isBLACompatibleAddress(Callee, DAG)) 5100 return false; 5101 5102 return true; 5103 } 5104 5105 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5106 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5107 return Subtarget.isAIXABI() || 5108 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5109 } 5110 5111 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5112 const Function &Caller, 5113 const SDValue &Callee, 5114 const PPCSubtarget &Subtarget, 5115 const TargetMachine &TM) { 5116 if (CFlags.IsTailCall) 5117 return PPCISD::TC_RETURN; 5118 5119 // This is a call through a function pointer. 5120 if (CFlags.IsIndirect) { 5121 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5122 // indirect calls. The save of the caller's TOC pointer to the stack will be 5123 // inserted into the DAG as part of call lowering. The restore of the TOC 5124 // pointer is modeled by using a pseudo instruction for the call opcode that 5125 // represents the 2 instruction sequence of an indirect branch and link, 5126 // immediately followed by a load of the TOC pointer from the the stack save 5127 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5128 // as it is not saved or used. 5129 return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5130 : PPCISD::BCTRL; 5131 } 5132 5133 if (Subtarget.isUsingPCRelativeCalls()) { 5134 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5135 return PPCISD::CALL_NOTOC; 5136 } 5137 5138 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5139 // immediately following the call instruction if the caller and callee may 5140 // have different TOC bases. At link time if the linker determines the calls 5141 // may not share a TOC base, the call is redirected to a trampoline inserted 5142 // by the linker. The trampoline will (among other things) save the callers 5143 // TOC pointer at an ABI designated offset in the linkage area and the linker 5144 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5145 // into gpr2. 5146 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5147 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5148 : PPCISD::CALL_NOP; 5149 5150 return PPCISD::CALL; 5151 } 5152 5153 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5154 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5155 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5156 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5157 return SDValue(Dest, 0); 5158 5159 // Returns true if the callee is local, and false otherwise. 5160 auto isLocalCallee = [&]() { 5161 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5162 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5163 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5164 5165 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5166 !dyn_cast_or_null<GlobalIFunc>(GV); 5167 }; 5168 5169 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5170 // a static relocation model causes some versions of GNU LD (2.17.50, at 5171 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5172 // built with secure-PLT. 5173 bool UsePlt = 5174 Subtarget.is32BitELFABI() && !isLocalCallee() && 5175 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5176 5177 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5178 const TargetMachine &TM = Subtarget.getTargetMachine(); 5179 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5180 MCSymbolXCOFF *S = 5181 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5182 5183 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5184 return DAG.getMCSymbol(S, PtrVT); 5185 }; 5186 5187 if (isFunctionGlobalAddress(Callee)) { 5188 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5189 5190 if (Subtarget.isAIXABI()) { 5191 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5192 return getAIXFuncEntryPointSymbolSDNode(GV); 5193 } 5194 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5195 UsePlt ? PPCII::MO_PLT : 0); 5196 } 5197 5198 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5199 const char *SymName = S->getSymbol(); 5200 if (Subtarget.isAIXABI()) { 5201 // If there exists a user-declared function whose name is the same as the 5202 // ExternalSymbol's, then we pick up the user-declared version. 5203 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5204 if (const Function *F = 5205 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5206 return getAIXFuncEntryPointSymbolSDNode(F); 5207 5208 // On AIX, direct function calls reference the symbol for the function's 5209 // entry point, which is named by prepending a "." before the function's 5210 // C-linkage name. A Qualname is returned here because an external 5211 // function entry point is a csect with XTY_ER property. 5212 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5213 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5214 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5215 (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER, 5216 SectionKind::getMetadata()); 5217 return Sec->getQualNameSymbol(); 5218 }; 5219 5220 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5221 } 5222 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5223 UsePlt ? PPCII::MO_PLT : 0); 5224 } 5225 5226 // No transformation needed. 5227 assert(Callee.getNode() && "What no callee?"); 5228 return Callee; 5229 } 5230 5231 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5232 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5233 "Expected a CALLSEQ_STARTSDNode."); 5234 5235 // The last operand is the chain, except when the node has glue. If the node 5236 // has glue, then the last operand is the glue, and the chain is the second 5237 // last operand. 5238 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5239 if (LastValue.getValueType() != MVT::Glue) 5240 return LastValue; 5241 5242 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5243 } 5244 5245 // Creates the node that moves a functions address into the count register 5246 // to prepare for an indirect call instruction. 5247 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5248 SDValue &Glue, SDValue &Chain, 5249 const SDLoc &dl) { 5250 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5251 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5252 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5253 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5254 // The glue is the second value produced. 5255 Glue = Chain.getValue(1); 5256 } 5257 5258 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5259 SDValue &Glue, SDValue &Chain, 5260 SDValue CallSeqStart, 5261 const CallBase *CB, const SDLoc &dl, 5262 bool hasNest, 5263 const PPCSubtarget &Subtarget) { 5264 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5265 // entry point, but to the function descriptor (the function entry point 5266 // address is part of the function descriptor though). 5267 // The function descriptor is a three doubleword structure with the 5268 // following fields: function entry point, TOC base address and 5269 // environment pointer. 5270 // Thus for a call through a function pointer, the following actions need 5271 // to be performed: 5272 // 1. Save the TOC of the caller in the TOC save area of its stack 5273 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5274 // 2. Load the address of the function entry point from the function 5275 // descriptor. 5276 // 3. Load the TOC of the callee from the function descriptor into r2. 5277 // 4. Load the environment pointer from the function descriptor into 5278 // r11. 5279 // 5. Branch to the function entry point address. 5280 // 6. On return of the callee, the TOC of the caller needs to be 5281 // restored (this is done in FinishCall()). 5282 // 5283 // The loads are scheduled at the beginning of the call sequence, and the 5284 // register copies are flagged together to ensure that no other 5285 // operations can be scheduled in between. E.g. without flagging the 5286 // copies together, a TOC access in the caller could be scheduled between 5287 // the assignment of the callee TOC and the branch to the callee, which leads 5288 // to incorrect code. 5289 5290 // Start by loading the function address from the descriptor. 5291 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5292 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5293 ? (MachineMemOperand::MODereferenceable | 5294 MachineMemOperand::MOInvariant) 5295 : MachineMemOperand::MONone; 5296 5297 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5298 5299 // Registers used in building the DAG. 5300 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5301 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5302 5303 // Offsets of descriptor members. 5304 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5305 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5306 5307 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5308 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5309 5310 // One load for the functions entry point address. 5311 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5312 Alignment, MMOFlags); 5313 5314 // One for loading the TOC anchor for the module that contains the called 5315 // function. 5316 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5317 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5318 SDValue TOCPtr = 5319 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5320 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5321 5322 // One for loading the environment pointer. 5323 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5324 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5325 SDValue LoadEnvPtr = 5326 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5327 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5328 5329 5330 // Then copy the newly loaded TOC anchor to the TOC pointer. 5331 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5332 Chain = TOCVal.getValue(0); 5333 Glue = TOCVal.getValue(1); 5334 5335 // If the function call has an explicit 'nest' parameter, it takes the 5336 // place of the environment pointer. 5337 assert((!hasNest || !Subtarget.isAIXABI()) && 5338 "Nest parameter is not supported on AIX."); 5339 if (!hasNest) { 5340 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5341 Chain = EnvVal.getValue(0); 5342 Glue = EnvVal.getValue(1); 5343 } 5344 5345 // The rest of the indirect call sequence is the same as the non-descriptor 5346 // DAG. 5347 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5348 } 5349 5350 static void 5351 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5352 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5353 SelectionDAG &DAG, 5354 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5355 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5356 const PPCSubtarget &Subtarget) { 5357 const bool IsPPC64 = Subtarget.isPPC64(); 5358 // MVT for a general purpose register. 5359 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5360 5361 // First operand is always the chain. 5362 Ops.push_back(Chain); 5363 5364 // If it's a direct call pass the callee as the second operand. 5365 if (!CFlags.IsIndirect) 5366 Ops.push_back(Callee); 5367 else { 5368 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5369 5370 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5371 // on the stack (this would have been done in `LowerCall_64SVR4` or 5372 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5373 // represents both the indirect branch and a load that restores the TOC 5374 // pointer from the linkage area. The operand for the TOC restore is an add 5375 // of the TOC save offset to the stack pointer. This must be the second 5376 // operand: after the chain input but before any other variadic arguments. 5377 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5378 // saved or used. 5379 if (isTOCSaveRestoreRequired(Subtarget)) { 5380 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5381 5382 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5383 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5384 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5385 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5386 Ops.push_back(AddTOC); 5387 } 5388 5389 // Add the register used for the environment pointer. 5390 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5391 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5392 RegVT)); 5393 5394 5395 // Add CTR register as callee so a bctr can be emitted later. 5396 if (CFlags.IsTailCall) 5397 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5398 } 5399 5400 // If this is a tail call add stack pointer delta. 5401 if (CFlags.IsTailCall) 5402 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5403 5404 // Add argument registers to the end of the list so that they are known live 5405 // into the call. 5406 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5407 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5408 RegsToPass[i].second.getValueType())); 5409 5410 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5411 // no way to mark dependencies as implicit here. 5412 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5413 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5414 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5415 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5416 5417 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5418 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5419 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5420 5421 // Add a register mask operand representing the call-preserved registers. 5422 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5423 const uint32_t *Mask = 5424 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5425 assert(Mask && "Missing call preserved mask for calling convention"); 5426 Ops.push_back(DAG.getRegisterMask(Mask)); 5427 5428 // If the glue is valid, it is the last operand. 5429 if (Glue.getNode()) 5430 Ops.push_back(Glue); 5431 } 5432 5433 SDValue PPCTargetLowering::FinishCall( 5434 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5435 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5436 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5437 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5438 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5439 5440 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5441 Subtarget.isAIXABI()) 5442 setUsesTOCBasePtr(DAG); 5443 5444 unsigned CallOpc = 5445 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5446 Subtarget, DAG.getTarget()); 5447 5448 if (!CFlags.IsIndirect) 5449 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5450 else if (Subtarget.usesFunctionDescriptors()) 5451 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5452 dl, CFlags.HasNest, Subtarget); 5453 else 5454 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5455 5456 // Build the operand list for the call instruction. 5457 SmallVector<SDValue, 8> Ops; 5458 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5459 SPDiff, Subtarget); 5460 5461 // Emit tail call. 5462 if (CFlags.IsTailCall) { 5463 // Indirect tail call when using PC Relative calls do not have the same 5464 // constraints. 5465 assert(((Callee.getOpcode() == ISD::Register && 5466 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5467 Callee.getOpcode() == ISD::TargetExternalSymbol || 5468 Callee.getOpcode() == ISD::TargetGlobalAddress || 5469 isa<ConstantSDNode>(Callee) || 5470 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5471 "Expecting a global address, external symbol, absolute value, " 5472 "register or an indirect tail call when PC Relative calls are " 5473 "used."); 5474 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5475 assert(CallOpc == PPCISD::TC_RETURN && 5476 "Unexpected call opcode for a tail call."); 5477 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5478 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5479 } 5480 5481 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5482 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5483 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5484 Glue = Chain.getValue(1); 5485 5486 // When performing tail call optimization the callee pops its arguments off 5487 // the stack. Account for this here so these bytes can be pushed back on in 5488 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5489 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5490 getTargetMachine().Options.GuaranteedTailCallOpt) 5491 ? NumBytes 5492 : 0; 5493 5494 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5495 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5496 Glue, dl); 5497 Glue = Chain.getValue(1); 5498 5499 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5500 DAG, InVals); 5501 } 5502 5503 SDValue 5504 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5505 SmallVectorImpl<SDValue> &InVals) const { 5506 SelectionDAG &DAG = CLI.DAG; 5507 SDLoc &dl = CLI.DL; 5508 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5509 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5510 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5511 SDValue Chain = CLI.Chain; 5512 SDValue Callee = CLI.Callee; 5513 bool &isTailCall = CLI.IsTailCall; 5514 CallingConv::ID CallConv = CLI.CallConv; 5515 bool isVarArg = CLI.IsVarArg; 5516 bool isPatchPoint = CLI.IsPatchPoint; 5517 const CallBase *CB = CLI.CB; 5518 5519 if (isTailCall) { 5520 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5521 isTailCall = false; 5522 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5523 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5524 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5525 else 5526 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5527 Ins, DAG); 5528 if (isTailCall) { 5529 ++NumTailCalls; 5530 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5531 ++NumSiblingCalls; 5532 5533 // PC Relative calls no longer guarantee that the callee is a Global 5534 // Address Node. The callee could be an indirect tail call in which 5535 // case the SDValue for the callee could be a load (to load the address 5536 // of a function pointer) or it may be a register copy (to move the 5537 // address of the callee from a function parameter into a virtual 5538 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5539 assert((Subtarget.isUsingPCRelativeCalls() || 5540 isa<GlobalAddressSDNode>(Callee)) && 5541 "Callee should be an llvm::Function object."); 5542 5543 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5544 << "\nTCO callee: "); 5545 LLVM_DEBUG(Callee.dump()); 5546 } 5547 } 5548 5549 if (!isTailCall && CB && CB->isMustTailCall()) 5550 report_fatal_error("failed to perform tail call elimination on a call " 5551 "site marked musttail"); 5552 5553 // When long calls (i.e. indirect calls) are always used, calls are always 5554 // made via function pointer. If we have a function name, first translate it 5555 // into a pointer. 5556 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5557 !isTailCall) 5558 Callee = LowerGlobalAddress(Callee, DAG); 5559 5560 CallFlags CFlags( 5561 CallConv, isTailCall, isVarArg, isPatchPoint, 5562 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5563 // hasNest 5564 Subtarget.is64BitELFABI() && 5565 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5566 CLI.NoMerge); 5567 5568 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5569 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5570 InVals, CB); 5571 5572 if (Subtarget.isSVR4ABI()) 5573 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5574 InVals, CB); 5575 5576 if (Subtarget.isAIXABI()) 5577 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5578 InVals, CB); 5579 5580 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5581 InVals, CB); 5582 } 5583 5584 SDValue PPCTargetLowering::LowerCall_32SVR4( 5585 SDValue Chain, SDValue Callee, CallFlags CFlags, 5586 const SmallVectorImpl<ISD::OutputArg> &Outs, 5587 const SmallVectorImpl<SDValue> &OutVals, 5588 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5589 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5590 const CallBase *CB) const { 5591 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5592 // of the 32-bit SVR4 ABI stack frame layout. 5593 5594 const CallingConv::ID CallConv = CFlags.CallConv; 5595 const bool IsVarArg = CFlags.IsVarArg; 5596 const bool IsTailCall = CFlags.IsTailCall; 5597 5598 assert((CallConv == CallingConv::C || 5599 CallConv == CallingConv::Cold || 5600 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5601 5602 const Align PtrAlign(4); 5603 5604 MachineFunction &MF = DAG.getMachineFunction(); 5605 5606 // Mark this function as potentially containing a function that contains a 5607 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5608 // and restoring the callers stack pointer in this functions epilog. This is 5609 // done because by tail calling the called function might overwrite the value 5610 // in this function's (MF) stack pointer stack slot 0(SP). 5611 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5612 CallConv == CallingConv::Fast) 5613 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5614 5615 // Count how many bytes are to be pushed on the stack, including the linkage 5616 // area, parameter list area and the part of the local variable space which 5617 // contains copies of aggregates which are passed by value. 5618 5619 // Assign locations to all of the outgoing arguments. 5620 SmallVector<CCValAssign, 16> ArgLocs; 5621 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5622 5623 // Reserve space for the linkage area on the stack. 5624 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5625 PtrAlign); 5626 if (useSoftFloat()) 5627 CCInfo.PreAnalyzeCallOperands(Outs); 5628 5629 if (IsVarArg) { 5630 // Handle fixed and variable vector arguments differently. 5631 // Fixed vector arguments go into registers as long as registers are 5632 // available. Variable vector arguments always go into memory. 5633 unsigned NumArgs = Outs.size(); 5634 5635 for (unsigned i = 0; i != NumArgs; ++i) { 5636 MVT ArgVT = Outs[i].VT; 5637 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5638 bool Result; 5639 5640 if (Outs[i].IsFixed) { 5641 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5642 CCInfo); 5643 } else { 5644 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5645 ArgFlags, CCInfo); 5646 } 5647 5648 if (Result) { 5649 #ifndef NDEBUG 5650 errs() << "Call operand #" << i << " has unhandled type " 5651 << EVT(ArgVT).getEVTString() << "\n"; 5652 #endif 5653 llvm_unreachable(nullptr); 5654 } 5655 } 5656 } else { 5657 // All arguments are treated the same. 5658 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5659 } 5660 CCInfo.clearWasPPCF128(); 5661 5662 // Assign locations to all of the outgoing aggregate by value arguments. 5663 SmallVector<CCValAssign, 16> ByValArgLocs; 5664 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5665 5666 // Reserve stack space for the allocations in CCInfo. 5667 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5668 5669 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5670 5671 // Size of the linkage area, parameter list area and the part of the local 5672 // space variable where copies of aggregates which are passed by value are 5673 // stored. 5674 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5675 5676 // Calculate by how many bytes the stack has to be adjusted in case of tail 5677 // call optimization. 5678 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5679 5680 // Adjust the stack pointer for the new arguments... 5681 // These operations are automatically eliminated by the prolog/epilog pass 5682 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5683 SDValue CallSeqStart = Chain; 5684 5685 // Load the return address and frame pointer so it can be moved somewhere else 5686 // later. 5687 SDValue LROp, FPOp; 5688 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5689 5690 // Set up a copy of the stack pointer for use loading and storing any 5691 // arguments that may not fit in the registers available for argument 5692 // passing. 5693 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5694 5695 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5696 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5697 SmallVector<SDValue, 8> MemOpChains; 5698 5699 bool seenFloatArg = false; 5700 // Walk the register/memloc assignments, inserting copies/loads. 5701 // i - Tracks the index into the list of registers allocated for the call 5702 // RealArgIdx - Tracks the index into the list of actual function arguments 5703 // j - Tracks the index into the list of byval arguments 5704 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5705 i != e; 5706 ++i, ++RealArgIdx) { 5707 CCValAssign &VA = ArgLocs[i]; 5708 SDValue Arg = OutVals[RealArgIdx]; 5709 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5710 5711 if (Flags.isByVal()) { 5712 // Argument is an aggregate which is passed by value, thus we need to 5713 // create a copy of it in the local variable space of the current stack 5714 // frame (which is the stack frame of the caller) and pass the address of 5715 // this copy to the callee. 5716 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5717 CCValAssign &ByValVA = ByValArgLocs[j++]; 5718 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5719 5720 // Memory reserved in the local variable space of the callers stack frame. 5721 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5722 5723 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5724 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5725 StackPtr, PtrOff); 5726 5727 // Create a copy of the argument in the local area of the current 5728 // stack frame. 5729 SDValue MemcpyCall = 5730 CreateCopyOfByValArgument(Arg, PtrOff, 5731 CallSeqStart.getNode()->getOperand(0), 5732 Flags, DAG, dl); 5733 5734 // This must go outside the CALLSEQ_START..END. 5735 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5736 SDLoc(MemcpyCall)); 5737 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5738 NewCallSeqStart.getNode()); 5739 Chain = CallSeqStart = NewCallSeqStart; 5740 5741 // Pass the address of the aggregate copy on the stack either in a 5742 // physical register or in the parameter list area of the current stack 5743 // frame to the callee. 5744 Arg = PtrOff; 5745 } 5746 5747 // When useCRBits() is true, there can be i1 arguments. 5748 // It is because getRegisterType(MVT::i1) => MVT::i1, 5749 // and for other integer types getRegisterType() => MVT::i32. 5750 // Extend i1 and ensure callee will get i32. 5751 if (Arg.getValueType() == MVT::i1) 5752 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5753 dl, MVT::i32, Arg); 5754 5755 if (VA.isRegLoc()) { 5756 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5757 // Put argument in a physical register. 5758 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5759 bool IsLE = Subtarget.isLittleEndian(); 5760 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5761 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5762 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5763 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5764 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5765 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5766 SVal.getValue(0))); 5767 } else 5768 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5769 } else { 5770 // Put argument in the parameter list area of the current stack frame. 5771 assert(VA.isMemLoc()); 5772 unsigned LocMemOffset = VA.getLocMemOffset(); 5773 5774 if (!IsTailCall) { 5775 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5776 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5777 StackPtr, PtrOff); 5778 5779 MemOpChains.push_back( 5780 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5781 } else { 5782 // Calculate and remember argument location. 5783 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5784 TailCallArguments); 5785 } 5786 } 5787 } 5788 5789 if (!MemOpChains.empty()) 5790 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5791 5792 // Build a sequence of copy-to-reg nodes chained together with token chain 5793 // and flag operands which copy the outgoing args into the appropriate regs. 5794 SDValue InFlag; 5795 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5796 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5797 RegsToPass[i].second, InFlag); 5798 InFlag = Chain.getValue(1); 5799 } 5800 5801 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5802 // registers. 5803 if (IsVarArg) { 5804 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5805 SDValue Ops[] = { Chain, InFlag }; 5806 5807 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5808 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5809 5810 InFlag = Chain.getValue(1); 5811 } 5812 5813 if (IsTailCall) 5814 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5815 TailCallArguments); 5816 5817 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5818 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5819 } 5820 5821 // Copy an argument into memory, being careful to do this outside the 5822 // call sequence for the call to which the argument belongs. 5823 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5824 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5825 SelectionDAG &DAG, const SDLoc &dl) const { 5826 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5827 CallSeqStart.getNode()->getOperand(0), 5828 Flags, DAG, dl); 5829 // The MEMCPY must go outside the CALLSEQ_START..END. 5830 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5831 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5832 SDLoc(MemcpyCall)); 5833 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5834 NewCallSeqStart.getNode()); 5835 return NewCallSeqStart; 5836 } 5837 5838 SDValue PPCTargetLowering::LowerCall_64SVR4( 5839 SDValue Chain, SDValue Callee, CallFlags CFlags, 5840 const SmallVectorImpl<ISD::OutputArg> &Outs, 5841 const SmallVectorImpl<SDValue> &OutVals, 5842 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5843 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5844 const CallBase *CB) const { 5845 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5846 bool isLittleEndian = Subtarget.isLittleEndian(); 5847 unsigned NumOps = Outs.size(); 5848 bool IsSibCall = false; 5849 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5850 5851 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5852 unsigned PtrByteSize = 8; 5853 5854 MachineFunction &MF = DAG.getMachineFunction(); 5855 5856 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5857 IsSibCall = true; 5858 5859 // Mark this function as potentially containing a function that contains a 5860 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5861 // and restoring the callers stack pointer in this functions epilog. This is 5862 // done because by tail calling the called function might overwrite the value 5863 // in this function's (MF) stack pointer stack slot 0(SP). 5864 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5865 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5866 5867 assert(!(IsFastCall && CFlags.IsVarArg) && 5868 "fastcc not supported on varargs functions"); 5869 5870 // Count how many bytes are to be pushed on the stack, including the linkage 5871 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5872 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5873 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5874 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5875 unsigned NumBytes = LinkageSize; 5876 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5877 5878 static const MCPhysReg GPR[] = { 5879 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5880 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5881 }; 5882 static const MCPhysReg VR[] = { 5883 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5884 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5885 }; 5886 5887 const unsigned NumGPRs = array_lengthof(GPR); 5888 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5889 const unsigned NumVRs = array_lengthof(VR); 5890 5891 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5892 // can be passed to the callee in registers. 5893 // For the fast calling convention, there is another check below. 5894 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5895 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5896 if (!HasParameterArea) { 5897 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5898 unsigned AvailableFPRs = NumFPRs; 5899 unsigned AvailableVRs = NumVRs; 5900 unsigned NumBytesTmp = NumBytes; 5901 for (unsigned i = 0; i != NumOps; ++i) { 5902 if (Outs[i].Flags.isNest()) continue; 5903 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5904 PtrByteSize, LinkageSize, ParamAreaSize, 5905 NumBytesTmp, AvailableFPRs, AvailableVRs)) 5906 HasParameterArea = true; 5907 } 5908 } 5909 5910 // When using the fast calling convention, we don't provide backing for 5911 // arguments that will be in registers. 5912 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5913 5914 // Avoid allocating parameter area for fastcc functions if all the arguments 5915 // can be passed in the registers. 5916 if (IsFastCall) 5917 HasParameterArea = false; 5918 5919 // Add up all the space actually used. 5920 for (unsigned i = 0; i != NumOps; ++i) { 5921 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5922 EVT ArgVT = Outs[i].VT; 5923 EVT OrigVT = Outs[i].ArgVT; 5924 5925 if (Flags.isNest()) 5926 continue; 5927 5928 if (IsFastCall) { 5929 if (Flags.isByVal()) { 5930 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5931 if (NumGPRsUsed > NumGPRs) 5932 HasParameterArea = true; 5933 } else { 5934 switch (ArgVT.getSimpleVT().SimpleTy) { 5935 default: llvm_unreachable("Unexpected ValueType for argument!"); 5936 case MVT::i1: 5937 case MVT::i32: 5938 case MVT::i64: 5939 if (++NumGPRsUsed <= NumGPRs) 5940 continue; 5941 break; 5942 case MVT::v4i32: 5943 case MVT::v8i16: 5944 case MVT::v16i8: 5945 case MVT::v2f64: 5946 case MVT::v2i64: 5947 case MVT::v1i128: 5948 case MVT::f128: 5949 if (++NumVRsUsed <= NumVRs) 5950 continue; 5951 break; 5952 case MVT::v4f32: 5953 if (++NumVRsUsed <= NumVRs) 5954 continue; 5955 break; 5956 case MVT::f32: 5957 case MVT::f64: 5958 if (++NumFPRsUsed <= NumFPRs) 5959 continue; 5960 break; 5961 } 5962 HasParameterArea = true; 5963 } 5964 } 5965 5966 /* Respect alignment of argument on the stack. */ 5967 auto Alignement = 5968 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5969 NumBytes = alignTo(NumBytes, Alignement); 5970 5971 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5972 if (Flags.isInConsecutiveRegsLast()) 5973 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5974 } 5975 5976 unsigned NumBytesActuallyUsed = NumBytes; 5977 5978 // In the old ELFv1 ABI, 5979 // the prolog code of the callee may store up to 8 GPR argument registers to 5980 // the stack, allowing va_start to index over them in memory if its varargs. 5981 // Because we cannot tell if this is needed on the caller side, we have to 5982 // conservatively assume that it is needed. As such, make sure we have at 5983 // least enough stack space for the caller to store the 8 GPRs. 5984 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5985 // really requires memory operands, e.g. a vararg function. 5986 if (HasParameterArea) 5987 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5988 else 5989 NumBytes = LinkageSize; 5990 5991 // Tail call needs the stack to be aligned. 5992 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5993 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5994 5995 int SPDiff = 0; 5996 5997 // Calculate by how many bytes the stack has to be adjusted in case of tail 5998 // call optimization. 5999 if (!IsSibCall) 6000 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6001 6002 // To protect arguments on the stack from being clobbered in a tail call, 6003 // force all the loads to happen before doing any other lowering. 6004 if (CFlags.IsTailCall) 6005 Chain = DAG.getStackArgumentTokenFactor(Chain); 6006 6007 // Adjust the stack pointer for the new arguments... 6008 // These operations are automatically eliminated by the prolog/epilog pass 6009 if (!IsSibCall) 6010 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6011 SDValue CallSeqStart = Chain; 6012 6013 // Load the return address and frame pointer so it can be move somewhere else 6014 // later. 6015 SDValue LROp, FPOp; 6016 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6017 6018 // Set up a copy of the stack pointer for use loading and storing any 6019 // arguments that may not fit in the registers available for argument 6020 // passing. 6021 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6022 6023 // Figure out which arguments are going to go in registers, and which in 6024 // memory. Also, if this is a vararg function, floating point operations 6025 // must be stored to our stack, and loaded into integer regs as well, if 6026 // any integer regs are available for argument passing. 6027 unsigned ArgOffset = LinkageSize; 6028 6029 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6030 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6031 6032 SmallVector<SDValue, 8> MemOpChains; 6033 for (unsigned i = 0; i != NumOps; ++i) { 6034 SDValue Arg = OutVals[i]; 6035 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6036 EVT ArgVT = Outs[i].VT; 6037 EVT OrigVT = Outs[i].ArgVT; 6038 6039 // PtrOff will be used to store the current argument to the stack if a 6040 // register cannot be found for it. 6041 SDValue PtrOff; 6042 6043 // We re-align the argument offset for each argument, except when using the 6044 // fast calling convention, when we need to make sure we do that only when 6045 // we'll actually use a stack slot. 6046 auto ComputePtrOff = [&]() { 6047 /* Respect alignment of argument on the stack. */ 6048 auto Alignment = 6049 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6050 ArgOffset = alignTo(ArgOffset, Alignment); 6051 6052 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6053 6054 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6055 }; 6056 6057 if (!IsFastCall) { 6058 ComputePtrOff(); 6059 6060 /* Compute GPR index associated with argument offset. */ 6061 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6062 GPR_idx = std::min(GPR_idx, NumGPRs); 6063 } 6064 6065 // Promote integers to 64-bit values. 6066 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6067 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6068 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6069 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6070 } 6071 6072 // FIXME memcpy is used way more than necessary. Correctness first. 6073 // Note: "by value" is code for passing a structure by value, not 6074 // basic types. 6075 if (Flags.isByVal()) { 6076 // Note: Size includes alignment padding, so 6077 // struct x { short a; char b; } 6078 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6079 // These are the proper values we need for right-justifying the 6080 // aggregate in a parameter register. 6081 unsigned Size = Flags.getByValSize(); 6082 6083 // An empty aggregate parameter takes up no storage and no 6084 // registers. 6085 if (Size == 0) 6086 continue; 6087 6088 if (IsFastCall) 6089 ComputePtrOff(); 6090 6091 // All aggregates smaller than 8 bytes must be passed right-justified. 6092 if (Size==1 || Size==2 || Size==4) { 6093 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6094 if (GPR_idx != NumGPRs) { 6095 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6096 MachinePointerInfo(), VT); 6097 MemOpChains.push_back(Load.getValue(1)); 6098 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6099 6100 ArgOffset += PtrByteSize; 6101 continue; 6102 } 6103 } 6104 6105 if (GPR_idx == NumGPRs && Size < 8) { 6106 SDValue AddPtr = PtrOff; 6107 if (!isLittleEndian) { 6108 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6109 PtrOff.getValueType()); 6110 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6111 } 6112 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6113 CallSeqStart, 6114 Flags, DAG, dl); 6115 ArgOffset += PtrByteSize; 6116 continue; 6117 } 6118 // Copy entire object into memory. There are cases where gcc-generated 6119 // code assumes it is there, even if it could be put entirely into 6120 // registers. (This is not what the doc says.) 6121 6122 // FIXME: The above statement is likely due to a misunderstanding of the 6123 // documents. All arguments must be copied into the parameter area BY 6124 // THE CALLEE in the event that the callee takes the address of any 6125 // formal argument. That has not yet been implemented. However, it is 6126 // reasonable to use the stack area as a staging area for the register 6127 // load. 6128 6129 // Skip this for small aggregates, as we will use the same slot for a 6130 // right-justified copy, below. 6131 if (Size >= 8) 6132 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6133 CallSeqStart, 6134 Flags, DAG, dl); 6135 6136 // When a register is available, pass a small aggregate right-justified. 6137 if (Size < 8 && GPR_idx != NumGPRs) { 6138 // The easiest way to get this right-justified in a register 6139 // is to copy the structure into the rightmost portion of a 6140 // local variable slot, then load the whole slot into the 6141 // register. 6142 // FIXME: The memcpy seems to produce pretty awful code for 6143 // small aggregates, particularly for packed ones. 6144 // FIXME: It would be preferable to use the slot in the 6145 // parameter save area instead of a new local variable. 6146 SDValue AddPtr = PtrOff; 6147 if (!isLittleEndian) { 6148 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6149 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6150 } 6151 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6152 CallSeqStart, 6153 Flags, DAG, dl); 6154 6155 // Load the slot into the register. 6156 SDValue Load = 6157 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6158 MemOpChains.push_back(Load.getValue(1)); 6159 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6160 6161 // Done with this argument. 6162 ArgOffset += PtrByteSize; 6163 continue; 6164 } 6165 6166 // For aggregates larger than PtrByteSize, copy the pieces of the 6167 // object that fit into registers from the parameter save area. 6168 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6169 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6170 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6171 if (GPR_idx != NumGPRs) { 6172 SDValue Load = 6173 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6174 MemOpChains.push_back(Load.getValue(1)); 6175 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6176 ArgOffset += PtrByteSize; 6177 } else { 6178 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6179 break; 6180 } 6181 } 6182 continue; 6183 } 6184 6185 switch (Arg.getSimpleValueType().SimpleTy) { 6186 default: llvm_unreachable("Unexpected ValueType for argument!"); 6187 case MVT::i1: 6188 case MVT::i32: 6189 case MVT::i64: 6190 if (Flags.isNest()) { 6191 // The 'nest' parameter, if any, is passed in R11. 6192 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6193 break; 6194 } 6195 6196 // These can be scalar arguments or elements of an integer array type 6197 // passed directly. Clang may use those instead of "byval" aggregate 6198 // types to avoid forcing arguments to memory unnecessarily. 6199 if (GPR_idx != NumGPRs) { 6200 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6201 } else { 6202 if (IsFastCall) 6203 ComputePtrOff(); 6204 6205 assert(HasParameterArea && 6206 "Parameter area must exist to pass an argument in memory."); 6207 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6208 true, CFlags.IsTailCall, false, MemOpChains, 6209 TailCallArguments, dl); 6210 if (IsFastCall) 6211 ArgOffset += PtrByteSize; 6212 } 6213 if (!IsFastCall) 6214 ArgOffset += PtrByteSize; 6215 break; 6216 case MVT::f32: 6217 case MVT::f64: { 6218 // These can be scalar arguments or elements of a float array type 6219 // passed directly. The latter are used to implement ELFv2 homogenous 6220 // float aggregates. 6221 6222 // Named arguments go into FPRs first, and once they overflow, the 6223 // remaining arguments go into GPRs and then the parameter save area. 6224 // Unnamed arguments for vararg functions always go to GPRs and 6225 // then the parameter save area. For now, put all arguments to vararg 6226 // routines always in both locations (FPR *and* GPR or stack slot). 6227 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6228 bool NeededLoad = false; 6229 6230 // First load the argument into the next available FPR. 6231 if (FPR_idx != NumFPRs) 6232 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6233 6234 // Next, load the argument into GPR or stack slot if needed. 6235 if (!NeedGPROrStack) 6236 ; 6237 else if (GPR_idx != NumGPRs && !IsFastCall) { 6238 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6239 // once we support fp <-> gpr moves. 6240 6241 // In the non-vararg case, this can only ever happen in the 6242 // presence of f32 array types, since otherwise we never run 6243 // out of FPRs before running out of GPRs. 6244 SDValue ArgVal; 6245 6246 // Double values are always passed in a single GPR. 6247 if (Arg.getValueType() != MVT::f32) { 6248 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6249 6250 // Non-array float values are extended and passed in a GPR. 6251 } else if (!Flags.isInConsecutiveRegs()) { 6252 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6253 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6254 6255 // If we have an array of floats, we collect every odd element 6256 // together with its predecessor into one GPR. 6257 } else if (ArgOffset % PtrByteSize != 0) { 6258 SDValue Lo, Hi; 6259 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6260 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6261 if (!isLittleEndian) 6262 std::swap(Lo, Hi); 6263 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6264 6265 // The final element, if even, goes into the first half of a GPR. 6266 } else if (Flags.isInConsecutiveRegsLast()) { 6267 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6268 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6269 if (!isLittleEndian) 6270 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6271 DAG.getConstant(32, dl, MVT::i32)); 6272 6273 // Non-final even elements are skipped; they will be handled 6274 // together the with subsequent argument on the next go-around. 6275 } else 6276 ArgVal = SDValue(); 6277 6278 if (ArgVal.getNode()) 6279 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6280 } else { 6281 if (IsFastCall) 6282 ComputePtrOff(); 6283 6284 // Single-precision floating-point values are mapped to the 6285 // second (rightmost) word of the stack doubleword. 6286 if (Arg.getValueType() == MVT::f32 && 6287 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6288 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6289 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6290 } 6291 6292 assert(HasParameterArea && 6293 "Parameter area must exist to pass an argument in memory."); 6294 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6295 true, CFlags.IsTailCall, false, MemOpChains, 6296 TailCallArguments, dl); 6297 6298 NeededLoad = true; 6299 } 6300 // When passing an array of floats, the array occupies consecutive 6301 // space in the argument area; only round up to the next doubleword 6302 // at the end of the array. Otherwise, each float takes 8 bytes. 6303 if (!IsFastCall || NeededLoad) { 6304 ArgOffset += (Arg.getValueType() == MVT::f32 && 6305 Flags.isInConsecutiveRegs()) ? 4 : 8; 6306 if (Flags.isInConsecutiveRegsLast()) 6307 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6308 } 6309 break; 6310 } 6311 case MVT::v4f32: 6312 case MVT::v4i32: 6313 case MVT::v8i16: 6314 case MVT::v16i8: 6315 case MVT::v2f64: 6316 case MVT::v2i64: 6317 case MVT::v1i128: 6318 case MVT::f128: 6319 // These can be scalar arguments or elements of a vector array type 6320 // passed directly. The latter are used to implement ELFv2 homogenous 6321 // vector aggregates. 6322 6323 // For a varargs call, named arguments go into VRs or on the stack as 6324 // usual; unnamed arguments always go to the stack or the corresponding 6325 // GPRs when within range. For now, we always put the value in both 6326 // locations (or even all three). 6327 if (CFlags.IsVarArg) { 6328 assert(HasParameterArea && 6329 "Parameter area must exist if we have a varargs call."); 6330 // We could elide this store in the case where the object fits 6331 // entirely in R registers. Maybe later. 6332 SDValue Store = 6333 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6334 MemOpChains.push_back(Store); 6335 if (VR_idx != NumVRs) { 6336 SDValue Load = 6337 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6338 MemOpChains.push_back(Load.getValue(1)); 6339 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6340 } 6341 ArgOffset += 16; 6342 for (unsigned i=0; i<16; i+=PtrByteSize) { 6343 if (GPR_idx == NumGPRs) 6344 break; 6345 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6346 DAG.getConstant(i, dl, PtrVT)); 6347 SDValue Load = 6348 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6349 MemOpChains.push_back(Load.getValue(1)); 6350 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6351 } 6352 break; 6353 } 6354 6355 // Non-varargs Altivec params go into VRs or on the stack. 6356 if (VR_idx != NumVRs) { 6357 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6358 } else { 6359 if (IsFastCall) 6360 ComputePtrOff(); 6361 6362 assert(HasParameterArea && 6363 "Parameter area must exist to pass an argument in memory."); 6364 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6365 true, CFlags.IsTailCall, true, MemOpChains, 6366 TailCallArguments, dl); 6367 if (IsFastCall) 6368 ArgOffset += 16; 6369 } 6370 6371 if (!IsFastCall) 6372 ArgOffset += 16; 6373 break; 6374 } 6375 } 6376 6377 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6378 "mismatch in size of parameter area"); 6379 (void)NumBytesActuallyUsed; 6380 6381 if (!MemOpChains.empty()) 6382 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6383 6384 // Check if this is an indirect call (MTCTR/BCTRL). 6385 // See prepareDescriptorIndirectCall and buildCallOperands for more 6386 // information about calls through function pointers in the 64-bit SVR4 ABI. 6387 if (CFlags.IsIndirect) { 6388 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6389 // caller in the TOC save area. 6390 if (isTOCSaveRestoreRequired(Subtarget)) { 6391 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6392 // Load r2 into a virtual register and store it to the TOC save area. 6393 setUsesTOCBasePtr(DAG); 6394 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6395 // TOC save area offset. 6396 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6397 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6398 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6399 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6400 MachinePointerInfo::getStack( 6401 DAG.getMachineFunction(), TOCSaveOffset)); 6402 } 6403 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6404 // This does not mean the MTCTR instruction must use R12; it's easier 6405 // to model this as an extra parameter, so do that. 6406 if (isELFv2ABI && !CFlags.IsPatchPoint) 6407 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6408 } 6409 6410 // Build a sequence of copy-to-reg nodes chained together with token chain 6411 // and flag operands which copy the outgoing args into the appropriate regs. 6412 SDValue InFlag; 6413 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6414 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6415 RegsToPass[i].second, InFlag); 6416 InFlag = Chain.getValue(1); 6417 } 6418 6419 if (CFlags.IsTailCall && !IsSibCall) 6420 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6421 TailCallArguments); 6422 6423 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6424 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6425 } 6426 6427 SDValue PPCTargetLowering::LowerCall_Darwin( 6428 SDValue Chain, SDValue Callee, CallFlags CFlags, 6429 const SmallVectorImpl<ISD::OutputArg> &Outs, 6430 const SmallVectorImpl<SDValue> &OutVals, 6431 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6432 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6433 const CallBase *CB) const { 6434 unsigned NumOps = Outs.size(); 6435 6436 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6437 bool isPPC64 = PtrVT == MVT::i64; 6438 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6439 6440 MachineFunction &MF = DAG.getMachineFunction(); 6441 6442 // Mark this function as potentially containing a function that contains a 6443 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6444 // and restoring the callers stack pointer in this functions epilog. This is 6445 // done because by tail calling the called function might overwrite the value 6446 // in this function's (MF) stack pointer stack slot 0(SP). 6447 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6448 CFlags.CallConv == CallingConv::Fast) 6449 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6450 6451 // Count how many bytes are to be pushed on the stack, including the linkage 6452 // area, and parameter passing area. We start with 24/48 bytes, which is 6453 // prereserved space for [SP][CR][LR][3 x unused]. 6454 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6455 unsigned NumBytes = LinkageSize; 6456 6457 // Add up all the space actually used. 6458 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6459 // they all go in registers, but we must reserve stack space for them for 6460 // possible use by the caller. In varargs or 64-bit calls, parameters are 6461 // assigned stack space in order, with padding so Altivec parameters are 6462 // 16-byte aligned. 6463 unsigned nAltivecParamsAtEnd = 0; 6464 for (unsigned i = 0; i != NumOps; ++i) { 6465 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6466 EVT ArgVT = Outs[i].VT; 6467 // Varargs Altivec parameters are padded to a 16 byte boundary. 6468 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6469 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6470 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6471 if (!CFlags.IsVarArg && !isPPC64) { 6472 // Non-varargs Altivec parameters go after all the non-Altivec 6473 // parameters; handle those later so we know how much padding we need. 6474 nAltivecParamsAtEnd++; 6475 continue; 6476 } 6477 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6478 NumBytes = ((NumBytes+15)/16)*16; 6479 } 6480 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6481 } 6482 6483 // Allow for Altivec parameters at the end, if needed. 6484 if (nAltivecParamsAtEnd) { 6485 NumBytes = ((NumBytes+15)/16)*16; 6486 NumBytes += 16*nAltivecParamsAtEnd; 6487 } 6488 6489 // The prolog code of the callee may store up to 8 GPR argument registers to 6490 // the stack, allowing va_start to index over them in memory if its varargs. 6491 // Because we cannot tell if this is needed on the caller side, we have to 6492 // conservatively assume that it is needed. As such, make sure we have at 6493 // least enough stack space for the caller to store the 8 GPRs. 6494 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6495 6496 // Tail call needs the stack to be aligned. 6497 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6498 CFlags.CallConv == CallingConv::Fast) 6499 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6500 6501 // Calculate by how many bytes the stack has to be adjusted in case of tail 6502 // call optimization. 6503 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6504 6505 // To protect arguments on the stack from being clobbered in a tail call, 6506 // force all the loads to happen before doing any other lowering. 6507 if (CFlags.IsTailCall) 6508 Chain = DAG.getStackArgumentTokenFactor(Chain); 6509 6510 // Adjust the stack pointer for the new arguments... 6511 // These operations are automatically eliminated by the prolog/epilog pass 6512 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6513 SDValue CallSeqStart = Chain; 6514 6515 // Load the return address and frame pointer so it can be move somewhere else 6516 // later. 6517 SDValue LROp, FPOp; 6518 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6519 6520 // Set up a copy of the stack pointer for use loading and storing any 6521 // arguments that may not fit in the registers available for argument 6522 // passing. 6523 SDValue StackPtr; 6524 if (isPPC64) 6525 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6526 else 6527 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6528 6529 // Figure out which arguments are going to go in registers, and which in 6530 // memory. Also, if this is a vararg function, floating point operations 6531 // must be stored to our stack, and loaded into integer regs as well, if 6532 // any integer regs are available for argument passing. 6533 unsigned ArgOffset = LinkageSize; 6534 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6535 6536 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6537 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6538 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6539 }; 6540 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6541 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6542 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6543 }; 6544 static const MCPhysReg VR[] = { 6545 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6546 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6547 }; 6548 const unsigned NumGPRs = array_lengthof(GPR_32); 6549 const unsigned NumFPRs = 13; 6550 const unsigned NumVRs = array_lengthof(VR); 6551 6552 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6553 6554 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6555 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6556 6557 SmallVector<SDValue, 8> MemOpChains; 6558 for (unsigned i = 0; i != NumOps; ++i) { 6559 SDValue Arg = OutVals[i]; 6560 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6561 6562 // PtrOff will be used to store the current argument to the stack if a 6563 // register cannot be found for it. 6564 SDValue PtrOff; 6565 6566 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6567 6568 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6569 6570 // On PPC64, promote integers to 64-bit values. 6571 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6572 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6573 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6574 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6575 } 6576 6577 // FIXME memcpy is used way more than necessary. Correctness first. 6578 // Note: "by value" is code for passing a structure by value, not 6579 // basic types. 6580 if (Flags.isByVal()) { 6581 unsigned Size = Flags.getByValSize(); 6582 // Very small objects are passed right-justified. Everything else is 6583 // passed left-justified. 6584 if (Size==1 || Size==2) { 6585 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6586 if (GPR_idx != NumGPRs) { 6587 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6588 MachinePointerInfo(), VT); 6589 MemOpChains.push_back(Load.getValue(1)); 6590 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6591 6592 ArgOffset += PtrByteSize; 6593 } else { 6594 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6595 PtrOff.getValueType()); 6596 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6597 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6598 CallSeqStart, 6599 Flags, DAG, dl); 6600 ArgOffset += PtrByteSize; 6601 } 6602 continue; 6603 } 6604 // Copy entire object into memory. There are cases where gcc-generated 6605 // code assumes it is there, even if it could be put entirely into 6606 // registers. (This is not what the doc says.) 6607 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6608 CallSeqStart, 6609 Flags, DAG, dl); 6610 6611 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6612 // copy the pieces of the object that fit into registers from the 6613 // parameter save area. 6614 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6615 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6616 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6617 if (GPR_idx != NumGPRs) { 6618 SDValue Load = 6619 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6620 MemOpChains.push_back(Load.getValue(1)); 6621 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6622 ArgOffset += PtrByteSize; 6623 } else { 6624 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6625 break; 6626 } 6627 } 6628 continue; 6629 } 6630 6631 switch (Arg.getSimpleValueType().SimpleTy) { 6632 default: llvm_unreachable("Unexpected ValueType for argument!"); 6633 case MVT::i1: 6634 case MVT::i32: 6635 case MVT::i64: 6636 if (GPR_idx != NumGPRs) { 6637 if (Arg.getValueType() == MVT::i1) 6638 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6639 6640 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6641 } else { 6642 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6643 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6644 TailCallArguments, dl); 6645 } 6646 ArgOffset += PtrByteSize; 6647 break; 6648 case MVT::f32: 6649 case MVT::f64: 6650 if (FPR_idx != NumFPRs) { 6651 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6652 6653 if (CFlags.IsVarArg) { 6654 SDValue Store = 6655 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6656 MemOpChains.push_back(Store); 6657 6658 // Float varargs are always shadowed in available integer registers 6659 if (GPR_idx != NumGPRs) { 6660 SDValue Load = 6661 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6662 MemOpChains.push_back(Load.getValue(1)); 6663 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6664 } 6665 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6666 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6667 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6668 SDValue Load = 6669 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6670 MemOpChains.push_back(Load.getValue(1)); 6671 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6672 } 6673 } else { 6674 // If we have any FPRs remaining, we may also have GPRs remaining. 6675 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6676 // GPRs. 6677 if (GPR_idx != NumGPRs) 6678 ++GPR_idx; 6679 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6680 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6681 ++GPR_idx; 6682 } 6683 } else 6684 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6685 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6686 TailCallArguments, dl); 6687 if (isPPC64) 6688 ArgOffset += 8; 6689 else 6690 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6691 break; 6692 case MVT::v4f32: 6693 case MVT::v4i32: 6694 case MVT::v8i16: 6695 case MVT::v16i8: 6696 if (CFlags.IsVarArg) { 6697 // These go aligned on the stack, or in the corresponding R registers 6698 // when within range. The Darwin PPC ABI doc claims they also go in 6699 // V registers; in fact gcc does this only for arguments that are 6700 // prototyped, not for those that match the ... We do it for all 6701 // arguments, seems to work. 6702 while (ArgOffset % 16 !=0) { 6703 ArgOffset += PtrByteSize; 6704 if (GPR_idx != NumGPRs) 6705 GPR_idx++; 6706 } 6707 // We could elide this store in the case where the object fits 6708 // entirely in R registers. Maybe later. 6709 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6710 DAG.getConstant(ArgOffset, dl, PtrVT)); 6711 SDValue Store = 6712 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6713 MemOpChains.push_back(Store); 6714 if (VR_idx != NumVRs) { 6715 SDValue Load = 6716 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6717 MemOpChains.push_back(Load.getValue(1)); 6718 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6719 } 6720 ArgOffset += 16; 6721 for (unsigned i=0; i<16; i+=PtrByteSize) { 6722 if (GPR_idx == NumGPRs) 6723 break; 6724 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6725 DAG.getConstant(i, dl, PtrVT)); 6726 SDValue Load = 6727 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6728 MemOpChains.push_back(Load.getValue(1)); 6729 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6730 } 6731 break; 6732 } 6733 6734 // Non-varargs Altivec params generally go in registers, but have 6735 // stack space allocated at the end. 6736 if (VR_idx != NumVRs) { 6737 // Doesn't have GPR space allocated. 6738 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6739 } else if (nAltivecParamsAtEnd==0) { 6740 // We are emitting Altivec params in order. 6741 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6742 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6743 TailCallArguments, dl); 6744 ArgOffset += 16; 6745 } 6746 break; 6747 } 6748 } 6749 // If all Altivec parameters fit in registers, as they usually do, 6750 // they get stack space following the non-Altivec parameters. We 6751 // don't track this here because nobody below needs it. 6752 // If there are more Altivec parameters than fit in registers emit 6753 // the stores here. 6754 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6755 unsigned j = 0; 6756 // Offset is aligned; skip 1st 12 params which go in V registers. 6757 ArgOffset = ((ArgOffset+15)/16)*16; 6758 ArgOffset += 12*16; 6759 for (unsigned i = 0; i != NumOps; ++i) { 6760 SDValue Arg = OutVals[i]; 6761 EVT ArgType = Outs[i].VT; 6762 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6763 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6764 if (++j > NumVRs) { 6765 SDValue PtrOff; 6766 // We are emitting Altivec params in order. 6767 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6768 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6769 TailCallArguments, dl); 6770 ArgOffset += 16; 6771 } 6772 } 6773 } 6774 } 6775 6776 if (!MemOpChains.empty()) 6777 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6778 6779 // On Darwin, R12 must contain the address of an indirect callee. This does 6780 // not mean the MTCTR instruction must use R12; it's easier to model this as 6781 // an extra parameter, so do that. 6782 if (CFlags.IsIndirect) { 6783 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6784 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6785 PPC::R12), Callee)); 6786 } 6787 6788 // Build a sequence of copy-to-reg nodes chained together with token chain 6789 // and flag operands which copy the outgoing args into the appropriate regs. 6790 SDValue InFlag; 6791 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6792 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6793 RegsToPass[i].second, InFlag); 6794 InFlag = Chain.getValue(1); 6795 } 6796 6797 if (CFlags.IsTailCall) 6798 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6799 TailCallArguments); 6800 6801 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6802 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6803 } 6804 6805 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6806 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6807 CCState &State) { 6808 6809 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6810 State.getMachineFunction().getSubtarget()); 6811 const bool IsPPC64 = Subtarget.isPPC64(); 6812 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6813 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6814 6815 assert((!ValVT.isInteger() || 6816 (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) && 6817 "Integer argument exceeds register size: should have been legalized"); 6818 6819 if (ValVT == MVT::f128) 6820 report_fatal_error("f128 is unimplemented on AIX."); 6821 6822 if (ArgFlags.isNest()) 6823 report_fatal_error("Nest arguments are unimplemented."); 6824 6825 if (ValVT.isVector() || LocVT.isVector()) 6826 report_fatal_error("Vector arguments are unimplemented on AIX."); 6827 6828 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6829 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6830 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6831 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6832 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6833 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6834 6835 if (ArgFlags.isByVal()) { 6836 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6837 report_fatal_error("Pass-by-value arguments with alignment greater than " 6838 "register width are not supported."); 6839 6840 const unsigned ByValSize = ArgFlags.getByValSize(); 6841 6842 // An empty aggregate parameter takes up no storage and no registers, 6843 // but needs a MemLoc for a stack slot for the formal arguments side. 6844 if (ByValSize == 0) { 6845 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6846 State.getNextStackOffset(), RegVT, 6847 LocInfo)); 6848 return false; 6849 } 6850 6851 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6852 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6853 for (const unsigned E = Offset + StackSize; Offset < E; 6854 Offset += PtrAlign.value()) { 6855 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6856 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6857 else { 6858 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6859 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6860 LocInfo)); 6861 break; 6862 } 6863 } 6864 return false; 6865 } 6866 6867 // Arguments always reserve parameter save area. 6868 switch (ValVT.SimpleTy) { 6869 default: 6870 report_fatal_error("Unhandled value type for argument."); 6871 case MVT::i64: 6872 // i64 arguments should have been split to i32 for PPC32. 6873 assert(IsPPC64 && "PPC32 should have split i64 values."); 6874 LLVM_FALLTHROUGH; 6875 case MVT::i1: 6876 case MVT::i32: { 6877 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6878 // AIX integer arguments are always passed in register width. 6879 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6880 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6881 : CCValAssign::LocInfo::ZExt; 6882 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6883 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6884 else 6885 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6886 6887 return false; 6888 } 6889 case MVT::f32: 6890 case MVT::f64: { 6891 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6892 const unsigned StoreSize = LocVT.getStoreSize(); 6893 // Floats are always 4-byte aligned in the PSA on AIX. 6894 // This includes f64 in 64-bit mode for ABI compatibility. 6895 const unsigned Offset = 6896 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6897 unsigned FReg = State.AllocateReg(FPR); 6898 if (FReg) 6899 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6900 6901 // Reserve and initialize GPRs or initialize the PSA as required. 6902 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6903 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6904 assert(FReg && "An FPR should be available when a GPR is reserved."); 6905 if (State.isVarArg()) { 6906 // Successfully reserved GPRs are only initialized for vararg calls. 6907 // Custom handling is required for: 6908 // f64 in PPC32 needs to be split into 2 GPRs. 6909 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6910 State.addLoc( 6911 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6912 } 6913 } else { 6914 // If there are insufficient GPRs, the PSA needs to be initialized. 6915 // Initialization occurs even if an FPR was initialized for 6916 // compatibility with the AIX XL compiler. The full memory for the 6917 // argument will be initialized even if a prior word is saved in GPR. 6918 // A custom memLoc is used when the argument also passes in FPR so 6919 // that the callee handling can skip over it easily. 6920 State.addLoc( 6921 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6922 LocInfo) 6923 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6924 break; 6925 } 6926 } 6927 6928 return false; 6929 } 6930 } 6931 return true; 6932 } 6933 6934 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6935 bool IsPPC64) { 6936 assert((IsPPC64 || SVT != MVT::i64) && 6937 "i64 should have been split for 32-bit codegen."); 6938 6939 switch (SVT) { 6940 default: 6941 report_fatal_error("Unexpected value type for formal argument"); 6942 case MVT::i1: 6943 case MVT::i32: 6944 case MVT::i64: 6945 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6946 case MVT::f32: 6947 return &PPC::F4RCRegClass; 6948 case MVT::f64: 6949 return &PPC::F8RCRegClass; 6950 } 6951 } 6952 6953 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6954 SelectionDAG &DAG, SDValue ArgValue, 6955 MVT LocVT, const SDLoc &dl) { 6956 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6957 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6958 6959 if (Flags.isSExt()) 6960 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6961 DAG.getValueType(ValVT)); 6962 else if (Flags.isZExt()) 6963 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6964 DAG.getValueType(ValVT)); 6965 6966 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6967 } 6968 6969 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6970 const unsigned LASize = FL->getLinkageSize(); 6971 6972 if (PPC::GPRCRegClass.contains(Reg)) { 6973 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6974 "Reg must be a valid argument register!"); 6975 return LASize + 4 * (Reg - PPC::R3); 6976 } 6977 6978 if (PPC::G8RCRegClass.contains(Reg)) { 6979 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6980 "Reg must be a valid argument register!"); 6981 return LASize + 8 * (Reg - PPC::X3); 6982 } 6983 6984 llvm_unreachable("Only general purpose registers expected."); 6985 } 6986 6987 // AIX ABI Stack Frame Layout: 6988 // 6989 // Low Memory +--------------------------------------------+ 6990 // SP +---> | Back chain | ---+ 6991 // | +--------------------------------------------+ | 6992 // | | Saved Condition Register | | 6993 // | +--------------------------------------------+ | 6994 // | | Saved Linkage Register | | 6995 // | +--------------------------------------------+ | Linkage Area 6996 // | | Reserved for compilers | | 6997 // | +--------------------------------------------+ | 6998 // | | Reserved for binders | | 6999 // | +--------------------------------------------+ | 7000 // | | Saved TOC pointer | ---+ 7001 // | +--------------------------------------------+ 7002 // | | Parameter save area | 7003 // | +--------------------------------------------+ 7004 // | | Alloca space | 7005 // | +--------------------------------------------+ 7006 // | | Local variable space | 7007 // | +--------------------------------------------+ 7008 // | | Float/int conversion temporary | 7009 // | +--------------------------------------------+ 7010 // | | Save area for AltiVec registers | 7011 // | +--------------------------------------------+ 7012 // | | AltiVec alignment padding | 7013 // | +--------------------------------------------+ 7014 // | | Save area for VRSAVE register | 7015 // | +--------------------------------------------+ 7016 // | | Save area for General Purpose registers | 7017 // | +--------------------------------------------+ 7018 // | | Save area for Floating Point registers | 7019 // | +--------------------------------------------+ 7020 // +---- | Back chain | 7021 // High Memory +--------------------------------------------+ 7022 // 7023 // Specifications: 7024 // AIX 7.2 Assembler Language Reference 7025 // Subroutine linkage convention 7026 7027 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 7028 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 7029 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7030 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 7031 7032 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 7033 CallConv == CallingConv::Fast) && 7034 "Unexpected calling convention!"); 7035 7036 if (getTargetMachine().Options.GuaranteedTailCallOpt) 7037 report_fatal_error("Tail call support is unimplemented on AIX."); 7038 7039 if (useSoftFloat()) 7040 report_fatal_error("Soft float support is unimplemented on AIX."); 7041 7042 const PPCSubtarget &Subtarget = 7043 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 7044 7045 const bool IsPPC64 = Subtarget.isPPC64(); 7046 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7047 7048 // Assign locations to all of the incoming arguments. 7049 SmallVector<CCValAssign, 16> ArgLocs; 7050 MachineFunction &MF = DAG.getMachineFunction(); 7051 MachineFrameInfo &MFI = MF.getFrameInfo(); 7052 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 7053 7054 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 7055 // Reserve space for the linkage area on the stack. 7056 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7057 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7058 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 7059 7060 SmallVector<SDValue, 8> MemOps; 7061 7062 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 7063 CCValAssign &VA = ArgLocs[I++]; 7064 MVT LocVT = VA.getLocVT(); 7065 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7066 7067 // For compatibility with the AIX XL compiler, the float args in the 7068 // parameter save area are initialized even if the argument is available 7069 // in register. The caller is required to initialize both the register 7070 // and memory, however, the callee can choose to expect it in either. 7071 // The memloc is dismissed here because the argument is retrieved from 7072 // the register. 7073 if (VA.isMemLoc() && VA.needsCustom()) 7074 continue; 7075 7076 if (Flags.isByVal() && VA.isMemLoc()) { 7077 const unsigned Size = 7078 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7079 PtrByteSize); 7080 const int FI = MF.getFrameInfo().CreateFixedObject( 7081 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7082 /* IsAliased */ true); 7083 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7084 InVals.push_back(FIN); 7085 7086 continue; 7087 } 7088 7089 if (Flags.isByVal()) { 7090 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7091 7092 const MCPhysReg ArgReg = VA.getLocReg(); 7093 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7094 7095 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7096 report_fatal_error("Over aligned byvals not supported yet."); 7097 7098 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7099 const int FI = MF.getFrameInfo().CreateFixedObject( 7100 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7101 /* IsAliased */ true); 7102 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7103 InVals.push_back(FIN); 7104 7105 // Add live ins for all the RegLocs for the same ByVal. 7106 const TargetRegisterClass *RegClass = 7107 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7108 7109 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7110 unsigned Offset) { 7111 const unsigned VReg = MF.addLiveIn(PhysReg, RegClass); 7112 // Since the callers side has left justified the aggregate in the 7113 // register, we can simply store the entire register into the stack 7114 // slot. 7115 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7116 // The store to the fixedstack object is needed becuase accessing a 7117 // field of the ByVal will use a gep and load. Ideally we will optimize 7118 // to extracting the value from the register directly, and elide the 7119 // stores when the arguments address is not taken, but that will need to 7120 // be future work. 7121 SDValue Store = DAG.getStore( 7122 CopyFrom.getValue(1), dl, CopyFrom, 7123 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7124 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7125 7126 MemOps.push_back(Store); 7127 }; 7128 7129 unsigned Offset = 0; 7130 HandleRegLoc(VA.getLocReg(), Offset); 7131 Offset += PtrByteSize; 7132 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7133 Offset += PtrByteSize) { 7134 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7135 "RegLocs should be for ByVal argument."); 7136 7137 const CCValAssign RL = ArgLocs[I++]; 7138 HandleRegLoc(RL.getLocReg(), Offset); 7139 } 7140 7141 if (Offset != StackSize) { 7142 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7143 "Expected MemLoc for remaining bytes."); 7144 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7145 // Consume the MemLoc.The InVal has already been emitted, so nothing 7146 // more needs to be done. 7147 ++I; 7148 } 7149 7150 continue; 7151 } 7152 7153 EVT ValVT = VA.getValVT(); 7154 if (VA.isRegLoc() && !VA.needsCustom()) { 7155 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 7156 unsigned VReg = 7157 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7158 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7159 if (ValVT.isScalarInteger() && 7160 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7161 ArgValue = 7162 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7163 } 7164 InVals.push_back(ArgValue); 7165 continue; 7166 } 7167 if (VA.isMemLoc()) { 7168 const unsigned LocSize = LocVT.getStoreSize(); 7169 const unsigned ValSize = ValVT.getStoreSize(); 7170 assert((ValSize <= LocSize) && 7171 "Object size is larger than size of MemLoc"); 7172 int CurArgOffset = VA.getLocMemOffset(); 7173 // Objects are right-justified because AIX is big-endian. 7174 if (LocSize > ValSize) 7175 CurArgOffset += LocSize - ValSize; 7176 // Potential tail calls could cause overwriting of argument stack slots. 7177 const bool IsImmutable = 7178 !(getTargetMachine().Options.GuaranteedTailCallOpt && 7179 (CallConv == CallingConv::Fast)); 7180 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 7181 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7182 SDValue ArgValue = 7183 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 7184 InVals.push_back(ArgValue); 7185 continue; 7186 } 7187 } 7188 7189 // On AIX a minimum of 8 words is saved to the parameter save area. 7190 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7191 // Area that is at least reserved in the caller of this function. 7192 unsigned CallerReservedArea = 7193 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7194 7195 // Set the size that is at least reserved in caller of this function. Tail 7196 // call optimized function's reserved stack space needs to be aligned so 7197 // that taking the difference between two stack areas will result in an 7198 // aligned stack. 7199 CallerReservedArea = 7200 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7201 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7202 FuncInfo->setMinReservedArea(CallerReservedArea); 7203 7204 if (isVarArg) { 7205 FuncInfo->setVarArgsFrameIndex( 7206 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7207 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7208 7209 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7210 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7211 7212 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7213 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7214 const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32); 7215 7216 // The fixed integer arguments of a variadic function are stored to the 7217 // VarArgsFrameIndex on the stack so that they may be loaded by 7218 // dereferencing the result of va_next. 7219 for (unsigned GPRIndex = 7220 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7221 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7222 7223 const unsigned VReg = 7224 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7225 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7226 7227 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7228 SDValue Store = 7229 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7230 MemOps.push_back(Store); 7231 // Increment the address for the next argument to store. 7232 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7233 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7234 } 7235 } 7236 7237 if (!MemOps.empty()) 7238 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7239 7240 return Chain; 7241 } 7242 7243 SDValue PPCTargetLowering::LowerCall_AIX( 7244 SDValue Chain, SDValue Callee, CallFlags CFlags, 7245 const SmallVectorImpl<ISD::OutputArg> &Outs, 7246 const SmallVectorImpl<SDValue> &OutVals, 7247 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7248 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7249 const CallBase *CB) const { 7250 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7251 // AIX ABI stack frame layout. 7252 7253 assert((CFlags.CallConv == CallingConv::C || 7254 CFlags.CallConv == CallingConv::Cold || 7255 CFlags.CallConv == CallingConv::Fast) && 7256 "Unexpected calling convention!"); 7257 7258 if (CFlags.IsPatchPoint) 7259 report_fatal_error("This call type is unimplemented on AIX."); 7260 7261 const PPCSubtarget& Subtarget = 7262 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7263 if (Subtarget.hasAltivec()) 7264 report_fatal_error("Altivec support is unimplemented on AIX."); 7265 7266 MachineFunction &MF = DAG.getMachineFunction(); 7267 SmallVector<CCValAssign, 16> ArgLocs; 7268 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7269 *DAG.getContext()); 7270 7271 // Reserve space for the linkage save area (LSA) on the stack. 7272 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7273 // [SP][CR][LR][2 x reserved][TOC]. 7274 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7275 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7276 const bool IsPPC64 = Subtarget.isPPC64(); 7277 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7278 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7279 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7280 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7281 7282 // The prolog code of the callee may store up to 8 GPR argument registers to 7283 // the stack, allowing va_start to index over them in memory if the callee 7284 // is variadic. 7285 // Because we cannot tell if this is needed on the caller side, we have to 7286 // conservatively assume that it is needed. As such, make sure we have at 7287 // least enough stack space for the caller to store the 8 GPRs. 7288 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7289 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7290 CCInfo.getNextStackOffset()); 7291 7292 // Adjust the stack pointer for the new arguments... 7293 // These operations are automatically eliminated by the prolog/epilog pass. 7294 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7295 SDValue CallSeqStart = Chain; 7296 7297 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7298 SmallVector<SDValue, 8> MemOpChains; 7299 7300 // Set up a copy of the stack pointer for loading and storing any 7301 // arguments that may not fit in the registers available for argument 7302 // passing. 7303 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7304 : DAG.getRegister(PPC::R1, MVT::i32); 7305 7306 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7307 const unsigned ValNo = ArgLocs[I].getValNo(); 7308 SDValue Arg = OutVals[ValNo]; 7309 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7310 7311 if (Flags.isByVal()) { 7312 const unsigned ByValSize = Flags.getByValSize(); 7313 7314 // Nothing to do for zero-sized ByVals on the caller side. 7315 if (!ByValSize) { 7316 ++I; 7317 continue; 7318 } 7319 7320 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7321 return DAG.getExtLoad( 7322 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7323 (LoadOffset != 0) 7324 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7325 : Arg, 7326 MachinePointerInfo(), VT); 7327 }; 7328 7329 unsigned LoadOffset = 0; 7330 7331 // Initialize registers, which are fully occupied by the by-val argument. 7332 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7333 SDValue Load = GetLoad(PtrVT, LoadOffset); 7334 MemOpChains.push_back(Load.getValue(1)); 7335 LoadOffset += PtrByteSize; 7336 const CCValAssign &ByValVA = ArgLocs[I++]; 7337 assert(ByValVA.getValNo() == ValNo && 7338 "Unexpected location for pass-by-value argument."); 7339 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7340 } 7341 7342 if (LoadOffset == ByValSize) 7343 continue; 7344 7345 // There must be one more loc to handle the remainder. 7346 assert(ArgLocs[I].getValNo() == ValNo && 7347 "Expected additional location for by-value argument."); 7348 7349 if (ArgLocs[I].isMemLoc()) { 7350 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7351 const CCValAssign &ByValVA = ArgLocs[I++]; 7352 ISD::ArgFlagsTy MemcpyFlags = Flags; 7353 // Only memcpy the bytes that don't pass in register. 7354 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7355 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7356 (LoadOffset != 0) 7357 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7358 : Arg, 7359 DAG.getObjectPtrOffset(dl, StackPtr, 7360 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7361 CallSeqStart, MemcpyFlags, DAG, dl); 7362 continue; 7363 } 7364 7365 // Initialize the final register residue. 7366 // Any residue that occupies the final by-val arg register must be 7367 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7368 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7369 // 2 and 1 byte loads. 7370 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7371 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7372 "Unexpected register residue for by-value argument."); 7373 SDValue ResidueVal; 7374 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7375 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7376 const MVT VT = 7377 N == 1 ? MVT::i8 7378 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7379 SDValue Load = GetLoad(VT, LoadOffset); 7380 MemOpChains.push_back(Load.getValue(1)); 7381 LoadOffset += N; 7382 Bytes += N; 7383 7384 // By-val arguments are passed left-justfied in register. 7385 // Every load here needs to be shifted, otherwise a full register load 7386 // should have been used. 7387 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7388 "Unexpected load emitted during handling of pass-by-value " 7389 "argument."); 7390 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7391 EVT ShiftAmountTy = 7392 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7393 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7394 SDValue ShiftedLoad = 7395 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7396 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7397 ShiftedLoad) 7398 : ShiftedLoad; 7399 } 7400 7401 const CCValAssign &ByValVA = ArgLocs[I++]; 7402 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7403 continue; 7404 } 7405 7406 CCValAssign &VA = ArgLocs[I++]; 7407 const MVT LocVT = VA.getLocVT(); 7408 const MVT ValVT = VA.getValVT(); 7409 7410 switch (VA.getLocInfo()) { 7411 default: 7412 report_fatal_error("Unexpected argument extension type."); 7413 case CCValAssign::Full: 7414 break; 7415 case CCValAssign::ZExt: 7416 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7417 break; 7418 case CCValAssign::SExt: 7419 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7420 break; 7421 } 7422 7423 if (VA.isRegLoc() && !VA.needsCustom()) { 7424 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7425 continue; 7426 } 7427 7428 if (VA.isMemLoc()) { 7429 SDValue PtrOff = 7430 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7431 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7432 MemOpChains.push_back( 7433 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7434 7435 continue; 7436 } 7437 7438 // Custom handling is used for GPR initializations for vararg float 7439 // arguments. 7440 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7441 ValVT.isFloatingPoint() && LocVT.isInteger() && 7442 "Unexpected register handling for calling convention."); 7443 7444 SDValue ArgAsInt = 7445 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7446 7447 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7448 // f32 in 32-bit GPR 7449 // f64 in 64-bit GPR 7450 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7451 else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits()) 7452 // f32 in 64-bit GPR. 7453 RegsToPass.push_back(std::make_pair( 7454 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7455 else { 7456 // f64 in two 32-bit GPRs 7457 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7458 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7459 "Unexpected custom register for argument!"); 7460 CCValAssign &GPR1 = VA; 7461 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7462 DAG.getConstant(32, dl, MVT::i8)); 7463 RegsToPass.push_back(std::make_pair( 7464 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7465 7466 if (I != E) { 7467 // If only 1 GPR was available, there will only be one custom GPR and 7468 // the argument will also pass in memory. 7469 CCValAssign &PeekArg = ArgLocs[I]; 7470 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7471 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7472 CCValAssign &GPR2 = ArgLocs[I++]; 7473 RegsToPass.push_back(std::make_pair( 7474 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7475 } 7476 } 7477 } 7478 } 7479 7480 if (!MemOpChains.empty()) 7481 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7482 7483 // For indirect calls, we need to save the TOC base to the stack for 7484 // restoration after the call. 7485 if (CFlags.IsIndirect) { 7486 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7487 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7488 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7489 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7490 const unsigned TOCSaveOffset = 7491 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7492 7493 setUsesTOCBasePtr(DAG); 7494 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7495 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7496 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7497 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7498 Chain = DAG.getStore( 7499 Val.getValue(1), dl, Val, AddPtr, 7500 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7501 } 7502 7503 // Build a sequence of copy-to-reg nodes chained together with token chain 7504 // and flag operands which copy the outgoing args into the appropriate regs. 7505 SDValue InFlag; 7506 for (auto Reg : RegsToPass) { 7507 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7508 InFlag = Chain.getValue(1); 7509 } 7510 7511 const int SPDiff = 0; 7512 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7513 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7514 } 7515 7516 bool 7517 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7518 MachineFunction &MF, bool isVarArg, 7519 const SmallVectorImpl<ISD::OutputArg> &Outs, 7520 LLVMContext &Context) const { 7521 SmallVector<CCValAssign, 16> RVLocs; 7522 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7523 return CCInfo.CheckReturn( 7524 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7525 ? RetCC_PPC_Cold 7526 : RetCC_PPC); 7527 } 7528 7529 SDValue 7530 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7531 bool isVarArg, 7532 const SmallVectorImpl<ISD::OutputArg> &Outs, 7533 const SmallVectorImpl<SDValue> &OutVals, 7534 const SDLoc &dl, SelectionDAG &DAG) const { 7535 SmallVector<CCValAssign, 16> RVLocs; 7536 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7537 *DAG.getContext()); 7538 CCInfo.AnalyzeReturn(Outs, 7539 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7540 ? RetCC_PPC_Cold 7541 : RetCC_PPC); 7542 7543 SDValue Flag; 7544 SmallVector<SDValue, 4> RetOps(1, Chain); 7545 7546 // Copy the result values into the output registers. 7547 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7548 CCValAssign &VA = RVLocs[i]; 7549 assert(VA.isRegLoc() && "Can only return in registers!"); 7550 7551 SDValue Arg = OutVals[RealResIdx]; 7552 7553 switch (VA.getLocInfo()) { 7554 default: llvm_unreachable("Unknown loc info!"); 7555 case CCValAssign::Full: break; 7556 case CCValAssign::AExt: 7557 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7558 break; 7559 case CCValAssign::ZExt: 7560 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7561 break; 7562 case CCValAssign::SExt: 7563 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7564 break; 7565 } 7566 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7567 bool isLittleEndian = Subtarget.isLittleEndian(); 7568 // Legalize ret f64 -> ret 2 x i32. 7569 SDValue SVal = 7570 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7571 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7572 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7573 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7574 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7575 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7576 Flag = Chain.getValue(1); 7577 VA = RVLocs[++i]; // skip ahead to next loc 7578 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7579 } else 7580 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7581 Flag = Chain.getValue(1); 7582 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7583 } 7584 7585 RetOps[0] = Chain; // Update chain. 7586 7587 // Add the flag if we have it. 7588 if (Flag.getNode()) 7589 RetOps.push_back(Flag); 7590 7591 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7592 } 7593 7594 SDValue 7595 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7596 SelectionDAG &DAG) const { 7597 SDLoc dl(Op); 7598 7599 // Get the correct type for integers. 7600 EVT IntVT = Op.getValueType(); 7601 7602 // Get the inputs. 7603 SDValue Chain = Op.getOperand(0); 7604 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7605 // Build a DYNAREAOFFSET node. 7606 SDValue Ops[2] = {Chain, FPSIdx}; 7607 SDVTList VTs = DAG.getVTList(IntVT); 7608 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7609 } 7610 7611 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7612 SelectionDAG &DAG) const { 7613 // When we pop the dynamic allocation we need to restore the SP link. 7614 SDLoc dl(Op); 7615 7616 // Get the correct type for pointers. 7617 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7618 7619 // Construct the stack pointer operand. 7620 bool isPPC64 = Subtarget.isPPC64(); 7621 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7622 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7623 7624 // Get the operands for the STACKRESTORE. 7625 SDValue Chain = Op.getOperand(0); 7626 SDValue SaveSP = Op.getOperand(1); 7627 7628 // Load the old link SP. 7629 SDValue LoadLinkSP = 7630 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7631 7632 // Restore the stack pointer. 7633 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7634 7635 // Store the old link SP. 7636 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7637 } 7638 7639 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7640 MachineFunction &MF = DAG.getMachineFunction(); 7641 bool isPPC64 = Subtarget.isPPC64(); 7642 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7643 7644 // Get current frame pointer save index. The users of this index will be 7645 // primarily DYNALLOC instructions. 7646 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7647 int RASI = FI->getReturnAddrSaveIndex(); 7648 7649 // If the frame pointer save index hasn't been defined yet. 7650 if (!RASI) { 7651 // Find out what the fix offset of the frame pointer save area. 7652 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7653 // Allocate the frame index for frame pointer save area. 7654 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7655 // Save the result. 7656 FI->setReturnAddrSaveIndex(RASI); 7657 } 7658 return DAG.getFrameIndex(RASI, PtrVT); 7659 } 7660 7661 SDValue 7662 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7663 MachineFunction &MF = DAG.getMachineFunction(); 7664 bool isPPC64 = Subtarget.isPPC64(); 7665 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7666 7667 // Get current frame pointer save index. The users of this index will be 7668 // primarily DYNALLOC instructions. 7669 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7670 int FPSI = FI->getFramePointerSaveIndex(); 7671 7672 // If the frame pointer save index hasn't been defined yet. 7673 if (!FPSI) { 7674 // Find out what the fix offset of the frame pointer save area. 7675 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7676 // Allocate the frame index for frame pointer save area. 7677 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7678 // Save the result. 7679 FI->setFramePointerSaveIndex(FPSI); 7680 } 7681 return DAG.getFrameIndex(FPSI, PtrVT); 7682 } 7683 7684 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7685 SelectionDAG &DAG) const { 7686 MachineFunction &MF = DAG.getMachineFunction(); 7687 // Get the inputs. 7688 SDValue Chain = Op.getOperand(0); 7689 SDValue Size = Op.getOperand(1); 7690 SDLoc dl(Op); 7691 7692 // Get the correct type for pointers. 7693 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7694 // Negate the size. 7695 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7696 DAG.getConstant(0, dl, PtrVT), Size); 7697 // Construct a node for the frame pointer save index. 7698 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7699 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7700 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7701 if (hasInlineStackProbe(MF)) 7702 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7703 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7704 } 7705 7706 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7707 SelectionDAG &DAG) const { 7708 MachineFunction &MF = DAG.getMachineFunction(); 7709 7710 bool isPPC64 = Subtarget.isPPC64(); 7711 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7712 7713 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7714 return DAG.getFrameIndex(FI, PtrVT); 7715 } 7716 7717 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7718 SelectionDAG &DAG) const { 7719 SDLoc DL(Op); 7720 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7721 DAG.getVTList(MVT::i32, MVT::Other), 7722 Op.getOperand(0), Op.getOperand(1)); 7723 } 7724 7725 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7726 SelectionDAG &DAG) const { 7727 SDLoc DL(Op); 7728 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7729 Op.getOperand(0), Op.getOperand(1)); 7730 } 7731 7732 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7733 7734 assert(Op.getValueType() == MVT::i1 && 7735 "Custom lowering only for i1 loads"); 7736 7737 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7738 7739 SDLoc dl(Op); 7740 LoadSDNode *LD = cast<LoadSDNode>(Op); 7741 7742 SDValue Chain = LD->getChain(); 7743 SDValue BasePtr = LD->getBasePtr(); 7744 MachineMemOperand *MMO = LD->getMemOperand(); 7745 7746 SDValue NewLD = 7747 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7748 BasePtr, MVT::i8, MMO); 7749 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7750 7751 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7752 return DAG.getMergeValues(Ops, dl); 7753 } 7754 7755 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7756 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7757 "Custom lowering only for i1 stores"); 7758 7759 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7760 7761 SDLoc dl(Op); 7762 StoreSDNode *ST = cast<StoreSDNode>(Op); 7763 7764 SDValue Chain = ST->getChain(); 7765 SDValue BasePtr = ST->getBasePtr(); 7766 SDValue Value = ST->getValue(); 7767 MachineMemOperand *MMO = ST->getMemOperand(); 7768 7769 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7770 Value); 7771 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7772 } 7773 7774 // FIXME: Remove this once the ANDI glue bug is fixed: 7775 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7776 assert(Op.getValueType() == MVT::i1 && 7777 "Custom lowering only for i1 results"); 7778 7779 SDLoc DL(Op); 7780 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7781 } 7782 7783 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7784 SelectionDAG &DAG) const { 7785 7786 // Implements a vector truncate that fits in a vector register as a shuffle. 7787 // We want to legalize vector truncates down to where the source fits in 7788 // a vector register (and target is therefore smaller than vector register 7789 // size). At that point legalization will try to custom lower the sub-legal 7790 // result and get here - where we can contain the truncate as a single target 7791 // operation. 7792 7793 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7794 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7795 // 7796 // We will implement it for big-endian ordering as this (where x denotes 7797 // undefined): 7798 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7799 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7800 // 7801 // The same operation in little-endian ordering will be: 7802 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7803 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7804 7805 assert(Op.getValueType().isVector() && "Vector type expected."); 7806 7807 SDLoc DL(Op); 7808 SDValue N1 = Op.getOperand(0); 7809 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7810 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7811 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7812 7813 EVT TrgVT = Op.getValueType(); 7814 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7815 EVT EltVT = TrgVT.getVectorElementType(); 7816 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7817 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7818 7819 // First list the elements we want to keep. 7820 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7821 SmallVector<int, 16> ShuffV; 7822 if (Subtarget.isLittleEndian()) 7823 for (unsigned i = 0; i < TrgNumElts; ++i) 7824 ShuffV.push_back(i * SizeMult); 7825 else 7826 for (unsigned i = 1; i <= TrgNumElts; ++i) 7827 ShuffV.push_back(i * SizeMult - 1); 7828 7829 // Populate the remaining elements with undefs. 7830 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7831 // ShuffV.push_back(i + WideNumElts); 7832 ShuffV.push_back(WideNumElts + 1); 7833 7834 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7835 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7836 } 7837 7838 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7839 /// possible. 7840 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7841 // Not FP, or using SPE? Not a fsel. 7842 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7843 !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE()) 7844 return Op; 7845 7846 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7847 7848 EVT ResVT = Op.getValueType(); 7849 EVT CmpVT = Op.getOperand(0).getValueType(); 7850 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7851 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7852 SDLoc dl(Op); 7853 SDNodeFlags Flags = Op.getNode()->getFlags(); 7854 7855 // We have xsmaxcdp/xsmincdp which are OK to emit even in the 7856 // presence of infinities. 7857 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7858 switch (CC) { 7859 default: 7860 break; 7861 case ISD::SETOGT: 7862 case ISD::SETGT: 7863 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7864 case ISD::SETOLT: 7865 case ISD::SETLT: 7866 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7867 } 7868 } 7869 7870 // We might be able to do better than this under some circumstances, but in 7871 // general, fsel-based lowering of select is a finite-math-only optimization. 7872 // For more information, see section F.3 of the 2.06 ISA specification. 7873 // With ISA 3.0 7874 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7875 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7876 return Op; 7877 7878 // If the RHS of the comparison is a 0.0, we don't need to do the 7879 // subtraction at all. 7880 SDValue Sel1; 7881 if (isFloatingPointZero(RHS)) 7882 switch (CC) { 7883 default: break; // SETUO etc aren't handled by fsel. 7884 case ISD::SETNE: 7885 std::swap(TV, FV); 7886 LLVM_FALLTHROUGH; 7887 case ISD::SETEQ: 7888 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7889 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7890 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7891 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7892 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7893 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7894 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7895 case ISD::SETULT: 7896 case ISD::SETLT: 7897 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7898 LLVM_FALLTHROUGH; 7899 case ISD::SETOGE: 7900 case ISD::SETGE: 7901 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7902 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7903 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7904 case ISD::SETUGT: 7905 case ISD::SETGT: 7906 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7907 LLVM_FALLTHROUGH; 7908 case ISD::SETOLE: 7909 case ISD::SETLE: 7910 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7911 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7912 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7913 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7914 } 7915 7916 SDValue Cmp; 7917 switch (CC) { 7918 default: break; // SETUO etc aren't handled by fsel. 7919 case ISD::SETNE: 7920 std::swap(TV, FV); 7921 LLVM_FALLTHROUGH; 7922 case ISD::SETEQ: 7923 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7924 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7925 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7926 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7927 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7928 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7929 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7930 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7931 case ISD::SETULT: 7932 case ISD::SETLT: 7933 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7934 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7935 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7936 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7937 case ISD::SETOGE: 7938 case ISD::SETGE: 7939 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7940 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7941 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7942 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7943 case ISD::SETUGT: 7944 case ISD::SETGT: 7945 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7946 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7947 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7948 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7949 case ISD::SETOLE: 7950 case ISD::SETLE: 7951 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7952 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7953 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7954 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7955 } 7956 return Op; 7957 } 7958 7959 static unsigned getPPCStrictOpcode(unsigned Opc) { 7960 switch (Opc) { 7961 default: 7962 llvm_unreachable("No strict version of this opcode!"); 7963 case PPCISD::FCTIDZ: 7964 return PPCISD::STRICT_FCTIDZ; 7965 case PPCISD::FCTIWZ: 7966 return PPCISD::STRICT_FCTIWZ; 7967 case PPCISD::FCTIDUZ: 7968 return PPCISD::STRICT_FCTIDUZ; 7969 case PPCISD::FCTIWUZ: 7970 return PPCISD::STRICT_FCTIWUZ; 7971 } 7972 } 7973 7974 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 7975 const PPCSubtarget &Subtarget) { 7976 SDLoc dl(Op); 7977 bool IsStrict = Op->isStrictFPOpcode(); 7978 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 7979 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 7980 // For strict nodes, source is the second operand. 7981 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 7982 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 7983 assert(Src.getValueType().isFloatingPoint()); 7984 if (Src.getValueType() == MVT::f32) { 7985 if (IsStrict) { 7986 Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other}, 7987 {Chain, Src}); 7988 Chain = Src.getValue(1); 7989 } else 7990 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7991 } 7992 SDValue Conv; 7993 unsigned Opc = ISD::DELETED_NODE; 7994 switch (Op.getSimpleValueType().SimpleTy) { 7995 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7996 case MVT::i32: 7997 Opc = IsSigned ? PPCISD::FCTIWZ 7998 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 7999 break; 8000 case MVT::i64: 8001 assert((IsSigned || Subtarget.hasFPCVT()) && 8002 "i64 FP_TO_UINT is supported only with FPCVT"); 8003 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8004 } 8005 if (IsStrict) { 8006 Opc = getPPCStrictOpcode(Opc); 8007 Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src}); 8008 } else { 8009 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8010 } 8011 return Conv; 8012 } 8013 8014 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8015 SelectionDAG &DAG, 8016 const SDLoc &dl) const { 8017 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8018 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8019 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8020 bool IsStrict = Op->isStrictFPOpcode(); 8021 8022 // Convert the FP value to an int value through memory. 8023 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8024 (IsSigned || Subtarget.hasFPCVT()); 8025 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8026 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8027 MachinePointerInfo MPI = 8028 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8029 8030 // Emit a store to the stack slot. 8031 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8032 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8033 if (i32Stack) { 8034 MachineFunction &MF = DAG.getMachineFunction(); 8035 Alignment = Align(4); 8036 MachineMemOperand *MMO = 8037 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8038 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8039 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8040 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8041 } else 8042 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8043 8044 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8045 // add in a bias on big endian. 8046 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8047 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8048 DAG.getConstant(4, dl, FIPtr.getValueType())); 8049 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8050 } 8051 8052 RLI.Chain = Chain; 8053 RLI.Ptr = FIPtr; 8054 RLI.MPI = MPI; 8055 RLI.Alignment = Alignment; 8056 } 8057 8058 /// Custom lowers floating point to integer conversions to use 8059 /// the direct move instructions available in ISA 2.07 to avoid the 8060 /// need for load/store combinations. 8061 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8062 SelectionDAG &DAG, 8063 const SDLoc &dl) const { 8064 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8065 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8066 if (Op->isStrictFPOpcode()) 8067 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8068 else 8069 return Mov; 8070 } 8071 8072 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8073 const SDLoc &dl) const { 8074 bool IsStrict = Op->isStrictFPOpcode(); 8075 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8076 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8077 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8078 // FP to INT conversions are legal for f128. 8079 if (Src.getValueType() == MVT::f128) 8080 return Op; 8081 8082 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8083 // PPC (the libcall is not available). 8084 if (Src.getValueType() == MVT::ppcf128 && !IsStrict) { 8085 if (Op.getValueType() == MVT::i32) { 8086 if (IsSigned) { 8087 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8088 DAG.getIntPtrConstant(0, dl)); 8089 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8090 DAG.getIntPtrConstant(1, dl)); 8091 8092 // Add the two halves of the long double in round-to-zero mode. 8093 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8094 8095 // Now use a smaller FP_TO_SINT. 8096 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8097 } else { 8098 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8099 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8100 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 8101 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8102 // FIXME: generated code sucks. 8103 // TODO: Are there fast-math-flags to propagate to this FSUB? 8104 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp); 8105 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8106 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 8107 DAG.getConstant(0x80000000, dl, MVT::i32)); 8108 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8109 return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE); 8110 } 8111 } 8112 8113 return SDValue(); 8114 } 8115 8116 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8117 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8118 8119 ReuseLoadInfo RLI; 8120 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8121 8122 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8123 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8124 } 8125 8126 // We're trying to insert a regular store, S, and then a load, L. If the 8127 // incoming value, O, is a load, we might just be able to have our load use the 8128 // address used by O. However, we don't know if anything else will store to 8129 // that address before we can load from it. To prevent this situation, we need 8130 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8131 // the same chain operand as O, we create a token factor from the chain results 8132 // of O and L, and we replace all uses of O's chain result with that token 8133 // factor (see spliceIntoChain below for this last part). 8134 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8135 ReuseLoadInfo &RLI, 8136 SelectionDAG &DAG, 8137 ISD::LoadExtType ET) const { 8138 SDLoc dl(Op); 8139 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8140 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8141 if (ET == ISD::NON_EXTLOAD && 8142 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8143 isOperationLegalOrCustom(Op.getOpcode(), 8144 Op.getOperand(0).getValueType())) { 8145 8146 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8147 return true; 8148 } 8149 8150 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8151 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8152 LD->isNonTemporal()) 8153 return false; 8154 if (LD->getMemoryVT() != MemVT) 8155 return false; 8156 8157 RLI.Ptr = LD->getBasePtr(); 8158 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8159 assert(LD->getAddressingMode() == ISD::PRE_INC && 8160 "Non-pre-inc AM on PPC?"); 8161 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8162 LD->getOffset()); 8163 } 8164 8165 RLI.Chain = LD->getChain(); 8166 RLI.MPI = LD->getPointerInfo(); 8167 RLI.IsDereferenceable = LD->isDereferenceable(); 8168 RLI.IsInvariant = LD->isInvariant(); 8169 RLI.Alignment = LD->getAlign(); 8170 RLI.AAInfo = LD->getAAInfo(); 8171 RLI.Ranges = LD->getRanges(); 8172 8173 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8174 return true; 8175 } 8176 8177 // Given the head of the old chain, ResChain, insert a token factor containing 8178 // it and NewResChain, and make users of ResChain now be users of that token 8179 // factor. 8180 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8181 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8182 SDValue NewResChain, 8183 SelectionDAG &DAG) const { 8184 if (!ResChain) 8185 return; 8186 8187 SDLoc dl(NewResChain); 8188 8189 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8190 NewResChain, DAG.getUNDEF(MVT::Other)); 8191 assert(TF.getNode() != NewResChain.getNode() && 8192 "A new TF really is required here"); 8193 8194 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8195 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8196 } 8197 8198 /// Analyze profitability of direct move 8199 /// prefer float load to int load plus direct move 8200 /// when there is no integer use of int load 8201 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8202 SDNode *Origin = Op.getOperand(0).getNode(); 8203 if (Origin->getOpcode() != ISD::LOAD) 8204 return true; 8205 8206 // If there is no LXSIBZX/LXSIHZX, like Power8, 8207 // prefer direct move if the memory size is 1 or 2 bytes. 8208 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8209 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8210 return true; 8211 8212 for (SDNode::use_iterator UI = Origin->use_begin(), 8213 UE = Origin->use_end(); 8214 UI != UE; ++UI) { 8215 8216 // Only look at the users of the loaded value. 8217 if (UI.getUse().get().getResNo() != 0) 8218 continue; 8219 8220 if (UI->getOpcode() != ISD::SINT_TO_FP && 8221 UI->getOpcode() != ISD::UINT_TO_FP) 8222 return true; 8223 } 8224 8225 return false; 8226 } 8227 8228 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8229 const PPCSubtarget &Subtarget) { 8230 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP; 8231 SDLoc dl(Op); 8232 // If we have FCFIDS, then use it when converting to single-precision. 8233 // Otherwise, convert to double-precision and then round. 8234 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8235 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8236 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8237 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8238 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8239 } 8240 8241 /// Custom lowers integer to floating point conversions to use 8242 /// the direct move instructions available in ISA 2.07 to avoid the 8243 /// need for load/store combinations. 8244 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8245 SelectionDAG &DAG, 8246 const SDLoc &dl) const { 8247 assert((Op.getValueType() == MVT::f32 || 8248 Op.getValueType() == MVT::f64) && 8249 "Invalid floating point type as target of conversion"); 8250 assert(Subtarget.hasFPCVT() && 8251 "Int to FP conversions with direct moves require FPCVT"); 8252 SDValue Src = Op.getOperand(0); 8253 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8254 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 8255 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8256 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8257 return convertIntToFP(Op, Mov, DAG, Subtarget); 8258 } 8259 8260 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8261 8262 EVT VecVT = Vec.getValueType(); 8263 assert(VecVT.isVector() && "Expected a vector type."); 8264 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8265 8266 EVT EltVT = VecVT.getVectorElementType(); 8267 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8268 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8269 8270 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8271 SmallVector<SDValue, 16> Ops(NumConcat); 8272 Ops[0] = Vec; 8273 SDValue UndefVec = DAG.getUNDEF(VecVT); 8274 for (unsigned i = 1; i < NumConcat; ++i) 8275 Ops[i] = UndefVec; 8276 8277 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8278 } 8279 8280 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8281 const SDLoc &dl) const { 8282 8283 unsigned Opc = Op.getOpcode(); 8284 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 8285 "Unexpected conversion type"); 8286 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8287 "Supports conversions to v2f64/v4f32 only."); 8288 8289 bool SignedConv = Opc == ISD::SINT_TO_FP; 8290 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8291 8292 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 8293 EVT WideVT = Wide.getValueType(); 8294 unsigned WideNumElts = WideVT.getVectorNumElements(); 8295 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8296 8297 SmallVector<int, 16> ShuffV; 8298 for (unsigned i = 0; i < WideNumElts; ++i) 8299 ShuffV.push_back(i + WideNumElts); 8300 8301 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8302 int SaveElts = FourEltRes ? 4 : 2; 8303 if (Subtarget.isLittleEndian()) 8304 for (int i = 0; i < SaveElts; i++) 8305 ShuffV[i * Stride] = i; 8306 else 8307 for (int i = 1; i <= SaveElts; i++) 8308 ShuffV[i * Stride - 1] = i - 1; 8309 8310 SDValue ShuffleSrc2 = 8311 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8312 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8313 8314 SDValue Extend; 8315 if (SignedConv) { 8316 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8317 EVT ExtVT = Op.getOperand(0).getValueType(); 8318 if (Subtarget.hasP9Altivec()) 8319 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8320 IntermediateVT.getVectorNumElements()); 8321 8322 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8323 DAG.getValueType(ExtVT)); 8324 } else 8325 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8326 8327 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8328 } 8329 8330 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8331 SelectionDAG &DAG) const { 8332 SDLoc dl(Op); 8333 SDValue Src = Op.getOperand(0); 8334 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP; 8335 8336 EVT InVT = Src.getValueType(); 8337 EVT OutVT = Op.getValueType(); 8338 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8339 isOperationCustom(Op.getOpcode(), InVT)) 8340 return LowerINT_TO_FPVector(Op, DAG, dl); 8341 8342 // Conversions to f128 are legal. 8343 if (Op.getValueType() == MVT::f128) 8344 return Op; 8345 8346 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8347 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8348 return SDValue(); 8349 8350 if (Src.getValueType() == MVT::i1) 8351 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8352 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8353 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8354 8355 // If we have direct moves, we can do all the conversion, skip the store/load 8356 // however, without FPCVT we can't do most conversions. 8357 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8358 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8359 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8360 8361 assert((IsSigned || Subtarget.hasFPCVT()) && 8362 "UINT_TO_FP is supported only with FPCVT"); 8363 8364 if (Src.getValueType() == MVT::i64) { 8365 SDValue SINT = Src; 8366 // When converting to single-precision, we actually need to convert 8367 // to double-precision first and then round to single-precision. 8368 // To avoid double-rounding effects during that operation, we have 8369 // to prepare the input operand. Bits that might be truncated when 8370 // converting to double-precision are replaced by a bit that won't 8371 // be lost at this stage, but is below the single-precision rounding 8372 // position. 8373 // 8374 // However, if -enable-unsafe-fp-math is in effect, accept double 8375 // rounding to avoid the extra overhead. 8376 if (Op.getValueType() == MVT::f32 && 8377 !Subtarget.hasFPCVT() && 8378 !DAG.getTarget().Options.UnsafeFPMath) { 8379 8380 // Twiddle input to make sure the low 11 bits are zero. (If this 8381 // is the case, we are guaranteed the value will fit into the 53 bit 8382 // mantissa of an IEEE double-precision value without rounding.) 8383 // If any of those low 11 bits were not zero originally, make sure 8384 // bit 12 (value 2048) is set instead, so that the final rounding 8385 // to single-precision gets the correct result. 8386 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8387 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8388 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8389 Round, DAG.getConstant(2047, dl, MVT::i64)); 8390 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8391 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8392 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8393 8394 // However, we cannot use that value unconditionally: if the magnitude 8395 // of the input value is small, the bit-twiddling we did above might 8396 // end up visibly changing the output. Fortunately, in that case, we 8397 // don't need to twiddle bits since the original input will convert 8398 // exactly to double-precision floating-point already. Therefore, 8399 // construct a conditional to use the original value if the top 11 8400 // bits are all sign-bit copies, and use the rounded value computed 8401 // above otherwise. 8402 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8403 SINT, DAG.getConstant(53, dl, MVT::i32)); 8404 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8405 Cond, DAG.getConstant(1, dl, MVT::i64)); 8406 Cond = DAG.getSetCC( 8407 dl, 8408 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8409 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8410 8411 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8412 } 8413 8414 ReuseLoadInfo RLI; 8415 SDValue Bits; 8416 8417 MachineFunction &MF = DAG.getMachineFunction(); 8418 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8419 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8420 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8421 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8422 } else if (Subtarget.hasLFIWAX() && 8423 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8424 MachineMemOperand *MMO = 8425 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8426 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8427 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8428 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8429 DAG.getVTList(MVT::f64, MVT::Other), 8430 Ops, MVT::i32, MMO); 8431 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8432 } else if (Subtarget.hasFPCVT() && 8433 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8434 MachineMemOperand *MMO = 8435 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8436 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8437 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8438 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8439 DAG.getVTList(MVT::f64, MVT::Other), 8440 Ops, MVT::i32, MMO); 8441 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8442 } else if (((Subtarget.hasLFIWAX() && 8443 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8444 (Subtarget.hasFPCVT() && 8445 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8446 SINT.getOperand(0).getValueType() == MVT::i32) { 8447 MachineFrameInfo &MFI = MF.getFrameInfo(); 8448 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8449 8450 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8451 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8452 8453 SDValue Store = 8454 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8455 MachinePointerInfo::getFixedStack( 8456 DAG.getMachineFunction(), FrameIdx)); 8457 8458 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8459 "Expected an i32 store"); 8460 8461 RLI.Ptr = FIdx; 8462 RLI.Chain = Store; 8463 RLI.MPI = 8464 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8465 RLI.Alignment = Align(4); 8466 8467 MachineMemOperand *MMO = 8468 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8469 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8470 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8471 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8472 PPCISD::LFIWZX : PPCISD::LFIWAX, 8473 dl, DAG.getVTList(MVT::f64, MVT::Other), 8474 Ops, MVT::i32, MMO); 8475 } else 8476 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8477 8478 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget); 8479 8480 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8481 FP = DAG.getNode(ISD::FP_ROUND, dl, 8482 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8483 return FP; 8484 } 8485 8486 assert(Src.getValueType() == MVT::i32 && 8487 "Unhandled INT_TO_FP type in custom expander!"); 8488 // Since we only generate this in 64-bit mode, we can take advantage of 8489 // 64-bit registers. In particular, sign extend the input value into the 8490 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8491 // then lfd it and fcfid it. 8492 MachineFunction &MF = DAG.getMachineFunction(); 8493 MachineFrameInfo &MFI = MF.getFrameInfo(); 8494 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8495 8496 SDValue Ld; 8497 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8498 ReuseLoadInfo RLI; 8499 bool ReusingLoad; 8500 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8501 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8502 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8503 8504 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Src, FIdx, 8505 MachinePointerInfo::getFixedStack( 8506 DAG.getMachineFunction(), FrameIdx)); 8507 8508 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8509 "Expected an i32 store"); 8510 8511 RLI.Ptr = FIdx; 8512 RLI.Chain = Store; 8513 RLI.MPI = 8514 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8515 RLI.Alignment = Align(4); 8516 } 8517 8518 MachineMemOperand *MMO = 8519 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8520 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8521 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8522 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8523 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8524 MVT::i32, MMO); 8525 if (ReusingLoad) 8526 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8527 } else { 8528 assert(Subtarget.isPPC64() && 8529 "i32->FP without LFIWAX supported only on PPC64"); 8530 8531 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8532 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8533 8534 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8535 8536 // STD the extended value into the stack slot. 8537 SDValue Store = DAG.getStore( 8538 DAG.getEntryNode(), dl, Ext64, FIdx, 8539 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8540 8541 // Load the value as a double. 8542 Ld = DAG.getLoad( 8543 MVT::f64, dl, Store, FIdx, 8544 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8545 } 8546 8547 // FCFID it and return it. 8548 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget); 8549 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8550 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8551 DAG.getIntPtrConstant(0, dl)); 8552 return FP; 8553 } 8554 8555 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8556 SelectionDAG &DAG) const { 8557 SDLoc dl(Op); 8558 /* 8559 The rounding mode is in bits 30:31 of FPSR, and has the following 8560 settings: 8561 00 Round to nearest 8562 01 Round to 0 8563 10 Round to +inf 8564 11 Round to -inf 8565 8566 FLT_ROUNDS, on the other hand, expects the following: 8567 -1 Undefined 8568 0 Round to 0 8569 1 Round to nearest 8570 2 Round to +inf 8571 3 Round to -inf 8572 8573 To perform the conversion, we do: 8574 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8575 */ 8576 8577 MachineFunction &MF = DAG.getMachineFunction(); 8578 EVT VT = Op.getValueType(); 8579 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8580 8581 // Save FP Control Word to register 8582 SDValue Chain = Op.getOperand(0); 8583 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8584 Chain = MFFS.getValue(1); 8585 8586 // Save FP register to stack slot 8587 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8588 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8589 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8590 8591 // Load FP Control Word from low 32 bits of stack slot. 8592 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8593 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8594 SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8595 Chain = CWD.getValue(1); 8596 8597 // Transform as necessary 8598 SDValue CWD1 = 8599 DAG.getNode(ISD::AND, dl, MVT::i32, 8600 CWD, DAG.getConstant(3, dl, MVT::i32)); 8601 SDValue CWD2 = 8602 DAG.getNode(ISD::SRL, dl, MVT::i32, 8603 DAG.getNode(ISD::AND, dl, MVT::i32, 8604 DAG.getNode(ISD::XOR, dl, MVT::i32, 8605 CWD, DAG.getConstant(3, dl, MVT::i32)), 8606 DAG.getConstant(3, dl, MVT::i32)), 8607 DAG.getConstant(1, dl, MVT::i32)); 8608 8609 SDValue RetVal = 8610 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8611 8612 RetVal = 8613 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8614 dl, VT, RetVal); 8615 8616 return DAG.getMergeValues({RetVal, Chain}, dl); 8617 } 8618 8619 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8620 EVT VT = Op.getValueType(); 8621 unsigned BitWidth = VT.getSizeInBits(); 8622 SDLoc dl(Op); 8623 assert(Op.getNumOperands() == 3 && 8624 VT == Op.getOperand(1).getValueType() && 8625 "Unexpected SHL!"); 8626 8627 // Expand into a bunch of logical ops. Note that these ops 8628 // depend on the PPC behavior for oversized shift amounts. 8629 SDValue Lo = Op.getOperand(0); 8630 SDValue Hi = Op.getOperand(1); 8631 SDValue Amt = Op.getOperand(2); 8632 EVT AmtVT = Amt.getValueType(); 8633 8634 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8635 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8636 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8637 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8638 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8639 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8640 DAG.getConstant(-BitWidth, dl, AmtVT)); 8641 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8642 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8643 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8644 SDValue OutOps[] = { OutLo, OutHi }; 8645 return DAG.getMergeValues(OutOps, dl); 8646 } 8647 8648 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8649 EVT VT = Op.getValueType(); 8650 SDLoc dl(Op); 8651 unsigned BitWidth = VT.getSizeInBits(); 8652 assert(Op.getNumOperands() == 3 && 8653 VT == Op.getOperand(1).getValueType() && 8654 "Unexpected SRL!"); 8655 8656 // Expand into a bunch of logical ops. Note that these ops 8657 // depend on the PPC behavior for oversized shift amounts. 8658 SDValue Lo = Op.getOperand(0); 8659 SDValue Hi = Op.getOperand(1); 8660 SDValue Amt = Op.getOperand(2); 8661 EVT AmtVT = Amt.getValueType(); 8662 8663 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8664 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8665 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8666 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8667 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8668 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8669 DAG.getConstant(-BitWidth, dl, AmtVT)); 8670 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8671 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8672 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8673 SDValue OutOps[] = { OutLo, OutHi }; 8674 return DAG.getMergeValues(OutOps, dl); 8675 } 8676 8677 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8678 SDLoc dl(Op); 8679 EVT VT = Op.getValueType(); 8680 unsigned BitWidth = VT.getSizeInBits(); 8681 assert(Op.getNumOperands() == 3 && 8682 VT == Op.getOperand(1).getValueType() && 8683 "Unexpected SRA!"); 8684 8685 // Expand into a bunch of logical ops, followed by a select_cc. 8686 SDValue Lo = Op.getOperand(0); 8687 SDValue Hi = Op.getOperand(1); 8688 SDValue Amt = Op.getOperand(2); 8689 EVT AmtVT = Amt.getValueType(); 8690 8691 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8692 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8693 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8694 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8695 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8696 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8697 DAG.getConstant(-BitWidth, dl, AmtVT)); 8698 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8699 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8700 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8701 Tmp4, Tmp6, ISD::SETLE); 8702 SDValue OutOps[] = { OutLo, OutHi }; 8703 return DAG.getMergeValues(OutOps, dl); 8704 } 8705 8706 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8707 SelectionDAG &DAG) const { 8708 SDLoc dl(Op); 8709 EVT VT = Op.getValueType(); 8710 unsigned BitWidth = VT.getSizeInBits(); 8711 8712 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8713 SDValue X = Op.getOperand(0); 8714 SDValue Y = Op.getOperand(1); 8715 SDValue Z = Op.getOperand(2); 8716 EVT AmtVT = Z.getValueType(); 8717 8718 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8719 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8720 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8721 // on PowerPC shift by BW being well defined. 8722 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8723 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8724 SDValue SubZ = 8725 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8726 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8727 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8728 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8729 } 8730 8731 //===----------------------------------------------------------------------===// 8732 // Vector related lowering. 8733 // 8734 8735 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8736 /// element size of SplatSize. Cast the result to VT. 8737 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8738 SelectionDAG &DAG, const SDLoc &dl) { 8739 static const MVT VTys[] = { // canonical VT to use for each size. 8740 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8741 }; 8742 8743 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8744 8745 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8746 if (Val == ((1LU << (SplatSize * 8)) - 1)) { 8747 SplatSize = 1; 8748 Val = 0xFF; 8749 } 8750 8751 EVT CanonicalVT = VTys[SplatSize-1]; 8752 8753 // Build a canonical splat for this value. 8754 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8755 } 8756 8757 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8758 /// specified intrinsic ID. 8759 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8760 const SDLoc &dl, EVT DestVT = MVT::Other) { 8761 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8762 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8763 DAG.getConstant(IID, dl, MVT::i32), Op); 8764 } 8765 8766 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8767 /// specified intrinsic ID. 8768 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8769 SelectionDAG &DAG, const SDLoc &dl, 8770 EVT DestVT = MVT::Other) { 8771 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8772 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8773 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8774 } 8775 8776 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8777 /// specified intrinsic ID. 8778 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8779 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8780 EVT DestVT = MVT::Other) { 8781 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8782 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8783 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8784 } 8785 8786 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8787 /// amount. The result has the specified value type. 8788 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8789 SelectionDAG &DAG, const SDLoc &dl) { 8790 // Force LHS/RHS to be the right type. 8791 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8792 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8793 8794 int Ops[16]; 8795 for (unsigned i = 0; i != 16; ++i) 8796 Ops[i] = i + Amt; 8797 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8798 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8799 } 8800 8801 /// Do we have an efficient pattern in a .td file for this node? 8802 /// 8803 /// \param V - pointer to the BuildVectorSDNode being matched 8804 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8805 /// 8806 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8807 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8808 /// the opposite is true (expansion is beneficial) are: 8809 /// - The node builds a vector out of integers that are not 32 or 64-bits 8810 /// - The node builds a vector out of constants 8811 /// - The node is a "load-and-splat" 8812 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8813 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8814 bool HasDirectMove, 8815 bool HasP8Vector) { 8816 EVT VecVT = V->getValueType(0); 8817 bool RightType = VecVT == MVT::v2f64 || 8818 (HasP8Vector && VecVT == MVT::v4f32) || 8819 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8820 if (!RightType) 8821 return false; 8822 8823 bool IsSplat = true; 8824 bool IsLoad = false; 8825 SDValue Op0 = V->getOperand(0); 8826 8827 // This function is called in a block that confirms the node is not a constant 8828 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8829 // different constants. 8830 if (V->isConstant()) 8831 return false; 8832 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8833 if (V->getOperand(i).isUndef()) 8834 return false; 8835 // We want to expand nodes that represent load-and-splat even if the 8836 // loaded value is a floating point truncation or conversion to int. 8837 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8838 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8839 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8840 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8841 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8842 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8843 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8844 IsLoad = true; 8845 // If the operands are different or the input is not a load and has more 8846 // uses than just this BV node, then it isn't a splat. 8847 if (V->getOperand(i) != Op0 || 8848 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8849 IsSplat = false; 8850 } 8851 return !(IsSplat && IsLoad); 8852 } 8853 8854 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8855 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8856 8857 SDLoc dl(Op); 8858 SDValue Op0 = Op->getOperand(0); 8859 8860 if ((Op.getValueType() != MVT::f128) || 8861 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8862 (Op0.getOperand(0).getValueType() != MVT::i64) || 8863 (Op0.getOperand(1).getValueType() != MVT::i64)) 8864 return SDValue(); 8865 8866 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8867 Op0.getOperand(1)); 8868 } 8869 8870 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 8871 const SDValue *InputLoad = &Op; 8872 if (InputLoad->getOpcode() == ISD::BITCAST) 8873 InputLoad = &InputLoad->getOperand(0); 8874 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 8875 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 8876 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 8877 InputLoad = &InputLoad->getOperand(0); 8878 } 8879 if (InputLoad->getOpcode() != ISD::LOAD) 8880 return nullptr; 8881 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8882 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8883 } 8884 8885 // Convert the argument APFloat to a single precision APFloat if there is no 8886 // loss in information during the conversion to single precision APFloat and the 8887 // resulting number is not a denormal number. Return true if successful. 8888 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 8889 APFloat APFloatToConvert = ArgAPFloat; 8890 bool LosesInfo = true; 8891 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 8892 &LosesInfo); 8893 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 8894 if (Success) 8895 ArgAPFloat = APFloatToConvert; 8896 return Success; 8897 } 8898 8899 // Bitcast the argument APInt to a double and convert it to a single precision 8900 // APFloat, bitcast the APFloat to an APInt and assign it to the original 8901 // argument if there is no loss in information during the conversion from 8902 // double to single precision APFloat and the resulting number is not a denormal 8903 // number. Return true if successful. 8904 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 8905 double DpValue = ArgAPInt.bitsToDouble(); 8906 APFloat APFloatDp(DpValue); 8907 bool Success = convertToNonDenormSingle(APFloatDp); 8908 if (Success) 8909 ArgAPInt = APFloatDp.bitcastToAPInt(); 8910 return Success; 8911 } 8912 8913 // If this is a case we can't handle, return null and let the default 8914 // expansion code take care of it. If we CAN select this case, and if it 8915 // selects to a single instruction, return Op. Otherwise, if we can codegen 8916 // this case more efficiently than a constant pool load, lower it to the 8917 // sequence of ops that should be used. 8918 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8919 SelectionDAG &DAG) const { 8920 SDLoc dl(Op); 8921 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8922 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8923 8924 // Check if this is a splat of a constant value. 8925 APInt APSplatBits, APSplatUndef; 8926 unsigned SplatBitSize; 8927 bool HasAnyUndefs; 8928 bool BVNIsConstantSplat = 8929 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8930 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 8931 8932 // If it is a splat of a double, check if we can shrink it to a 32 bit 8933 // non-denormal float which when converted back to double gives us the same 8934 // double. This is to exploit the XXSPLTIDP instruction. 8935 if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() && 8936 (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) && 8937 convertToNonDenormSingle(APSplatBits)) { 8938 SDValue SplatNode = DAG.getNode( 8939 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 8940 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 8941 return DAG.getBitcast(Op.getValueType(), SplatNode); 8942 } 8943 8944 if (!BVNIsConstantSplat || SplatBitSize > 32) { 8945 8946 bool IsPermutedLoad = false; 8947 const SDValue *InputLoad = 8948 getNormalLoadInput(Op.getOperand(0), IsPermutedLoad); 8949 // Handle load-and-splat patterns as we have instructions that will do this 8950 // in one go. 8951 if (InputLoad && DAG.isSplatValue(Op, true)) { 8952 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8953 8954 // We have handling for 4 and 8 byte elements. 8955 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8956 8957 // Checking for a single use of this load, we have to check for vector 8958 // width (128 bits) / ElementSize uses (since each operand of the 8959 // BUILD_VECTOR is a separate use of the value. 8960 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8961 ((Subtarget.hasVSX() && ElementSize == 64) || 8962 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8963 SDValue Ops[] = { 8964 LD->getChain(), // Chain 8965 LD->getBasePtr(), // Ptr 8966 DAG.getValueType(Op.getValueType()) // VT 8967 }; 8968 return 8969 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8970 DAG.getVTList(Op.getValueType(), MVT::Other), 8971 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8972 } 8973 } 8974 8975 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8976 // lowered to VSX instructions under certain conditions. 8977 // Without VSX, there is no pattern more efficient than expanding the node. 8978 if (Subtarget.hasVSX() && 8979 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8980 Subtarget.hasP8Vector())) 8981 return Op; 8982 return SDValue(); 8983 } 8984 8985 uint64_t SplatBits = APSplatBits.getZExtValue(); 8986 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 8987 unsigned SplatSize = SplatBitSize / 8; 8988 8989 // First, handle single instruction cases. 8990 8991 // All zeros? 8992 if (SplatBits == 0) { 8993 // Canonicalize all zero vectors to be v4i32. 8994 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8995 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8996 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8997 } 8998 return Op; 8999 } 9000 9001 // We have XXSPLTIW for constant splats four bytes wide. 9002 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9003 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9004 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9005 // turned into a 4-byte splat of 0xABABABAB. 9006 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9007 return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2, 9008 Op.getValueType(), DAG, dl); 9009 9010 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9011 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9012 dl); 9013 9014 // We have XXSPLTIB for constant splats one byte wide. 9015 if (Subtarget.hasP9Vector() && SplatSize == 1) 9016 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9017 dl); 9018 9019 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9020 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9021 (32-SplatBitSize)); 9022 if (SextVal >= -16 && SextVal <= 15) 9023 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9024 dl); 9025 9026 // Two instruction sequences. 9027 9028 // If this value is in the range [-32,30] and is even, use: 9029 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9030 // If this value is in the range [17,31] and is odd, use: 9031 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9032 // If this value is in the range [-31,-17] and is odd, use: 9033 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9034 // Note the last two are three-instruction sequences. 9035 if (SextVal >= -32 && SextVal <= 31) { 9036 // To avoid having these optimizations undone by constant folding, 9037 // we convert to a pseudo that will be expanded later into one of 9038 // the above forms. 9039 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9040 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9041 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9042 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9043 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9044 if (VT == Op.getValueType()) 9045 return RetVal; 9046 else 9047 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9048 } 9049 9050 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9051 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9052 // for fneg/fabs. 9053 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9054 // Make -1 and vspltisw -1: 9055 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9056 9057 // Make the VSLW intrinsic, computing 0x8000_0000. 9058 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9059 OnesV, DAG, dl); 9060 9061 // xor by OnesV to invert it. 9062 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9063 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9064 } 9065 9066 // Check to see if this is a wide variety of vsplti*, binop self cases. 9067 static const signed char SplatCsts[] = { 9068 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9069 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9070 }; 9071 9072 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 9073 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9074 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9075 int i = SplatCsts[idx]; 9076 9077 // Figure out what shift amount will be used by altivec if shifted by i in 9078 // this splat size. 9079 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9080 9081 // vsplti + shl self. 9082 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9083 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9084 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9085 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9086 Intrinsic::ppc_altivec_vslw 9087 }; 9088 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9089 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9090 } 9091 9092 // vsplti + srl self. 9093 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9094 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9095 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9096 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9097 Intrinsic::ppc_altivec_vsrw 9098 }; 9099 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9100 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9101 } 9102 9103 // vsplti + sra self. 9104 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9105 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9106 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9107 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 9108 Intrinsic::ppc_altivec_vsraw 9109 }; 9110 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9111 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9112 } 9113 9114 // vsplti + rol self. 9115 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9116 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9117 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9118 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9119 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9120 Intrinsic::ppc_altivec_vrlw 9121 }; 9122 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9123 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9124 } 9125 9126 // t = vsplti c, result = vsldoi t, t, 1 9127 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9128 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9129 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9130 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9131 } 9132 // t = vsplti c, result = vsldoi t, t, 2 9133 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9134 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9135 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9136 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9137 } 9138 // t = vsplti c, result = vsldoi t, t, 3 9139 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9140 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9141 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9142 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9143 } 9144 } 9145 9146 return SDValue(); 9147 } 9148 9149 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9150 /// the specified operations to build the shuffle. 9151 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9152 SDValue RHS, SelectionDAG &DAG, 9153 const SDLoc &dl) { 9154 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9155 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9156 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9157 9158 enum { 9159 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9160 OP_VMRGHW, 9161 OP_VMRGLW, 9162 OP_VSPLTISW0, 9163 OP_VSPLTISW1, 9164 OP_VSPLTISW2, 9165 OP_VSPLTISW3, 9166 OP_VSLDOI4, 9167 OP_VSLDOI8, 9168 OP_VSLDOI12 9169 }; 9170 9171 if (OpNum == OP_COPY) { 9172 if (LHSID == (1*9+2)*9+3) return LHS; 9173 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9174 return RHS; 9175 } 9176 9177 SDValue OpLHS, OpRHS; 9178 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9179 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9180 9181 int ShufIdxs[16]; 9182 switch (OpNum) { 9183 default: llvm_unreachable("Unknown i32 permute!"); 9184 case OP_VMRGHW: 9185 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9186 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9187 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9188 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9189 break; 9190 case OP_VMRGLW: 9191 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9192 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9193 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9194 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9195 break; 9196 case OP_VSPLTISW0: 9197 for (unsigned i = 0; i != 16; ++i) 9198 ShufIdxs[i] = (i&3)+0; 9199 break; 9200 case OP_VSPLTISW1: 9201 for (unsigned i = 0; i != 16; ++i) 9202 ShufIdxs[i] = (i&3)+4; 9203 break; 9204 case OP_VSPLTISW2: 9205 for (unsigned i = 0; i != 16; ++i) 9206 ShufIdxs[i] = (i&3)+8; 9207 break; 9208 case OP_VSPLTISW3: 9209 for (unsigned i = 0; i != 16; ++i) 9210 ShufIdxs[i] = (i&3)+12; 9211 break; 9212 case OP_VSLDOI4: 9213 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9214 case OP_VSLDOI8: 9215 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9216 case OP_VSLDOI12: 9217 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9218 } 9219 EVT VT = OpLHS.getValueType(); 9220 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9221 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9222 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9223 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9224 } 9225 9226 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9227 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9228 /// SDValue. 9229 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9230 SelectionDAG &DAG) const { 9231 const unsigned BytesInVector = 16; 9232 bool IsLE = Subtarget.isLittleEndian(); 9233 SDLoc dl(N); 9234 SDValue V1 = N->getOperand(0); 9235 SDValue V2 = N->getOperand(1); 9236 unsigned ShiftElts = 0, InsertAtByte = 0; 9237 bool Swap = false; 9238 9239 // Shifts required to get the byte we want at element 7. 9240 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9241 0, 15, 14, 13, 12, 11, 10, 9}; 9242 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9243 1, 2, 3, 4, 5, 6, 7, 8}; 9244 9245 ArrayRef<int> Mask = N->getMask(); 9246 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9247 9248 // For each mask element, find out if we're just inserting something 9249 // from V2 into V1 or vice versa. 9250 // Possible permutations inserting an element from V2 into V1: 9251 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9252 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9253 // ... 9254 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9255 // Inserting from V1 into V2 will be similar, except mask range will be 9256 // [16,31]. 9257 9258 bool FoundCandidate = false; 9259 // If both vector operands for the shuffle are the same vector, the mask 9260 // will contain only elements from the first one and the second one will be 9261 // undef. 9262 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9263 // Go through the mask of half-words to find an element that's being moved 9264 // from one vector to the other. 9265 for (unsigned i = 0; i < BytesInVector; ++i) { 9266 unsigned CurrentElement = Mask[i]; 9267 // If 2nd operand is undefined, we should only look for element 7 in the 9268 // Mask. 9269 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9270 continue; 9271 9272 bool OtherElementsInOrder = true; 9273 // Examine the other elements in the Mask to see if they're in original 9274 // order. 9275 for (unsigned j = 0; j < BytesInVector; ++j) { 9276 if (j == i) 9277 continue; 9278 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9279 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9280 // in which we always assume we're always picking from the 1st operand. 9281 int MaskOffset = 9282 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9283 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9284 OtherElementsInOrder = false; 9285 break; 9286 } 9287 } 9288 // If other elements are in original order, we record the number of shifts 9289 // we need to get the element we want into element 7. Also record which byte 9290 // in the vector we should insert into. 9291 if (OtherElementsInOrder) { 9292 // If 2nd operand is undefined, we assume no shifts and no swapping. 9293 if (V2.isUndef()) { 9294 ShiftElts = 0; 9295 Swap = false; 9296 } else { 9297 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9298 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9299 : BigEndianShifts[CurrentElement & 0xF]; 9300 Swap = CurrentElement < BytesInVector; 9301 } 9302 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9303 FoundCandidate = true; 9304 break; 9305 } 9306 } 9307 9308 if (!FoundCandidate) 9309 return SDValue(); 9310 9311 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9312 // optionally with VECSHL if shift is required. 9313 if (Swap) 9314 std::swap(V1, V2); 9315 if (V2.isUndef()) 9316 V2 = V1; 9317 if (ShiftElts) { 9318 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9319 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9320 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9321 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9322 } 9323 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9324 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9325 } 9326 9327 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9328 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9329 /// SDValue. 9330 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9331 SelectionDAG &DAG) const { 9332 const unsigned NumHalfWords = 8; 9333 const unsigned BytesInVector = NumHalfWords * 2; 9334 // Check that the shuffle is on half-words. 9335 if (!isNByteElemShuffleMask(N, 2, 1)) 9336 return SDValue(); 9337 9338 bool IsLE = Subtarget.isLittleEndian(); 9339 SDLoc dl(N); 9340 SDValue V1 = N->getOperand(0); 9341 SDValue V2 = N->getOperand(1); 9342 unsigned ShiftElts = 0, InsertAtByte = 0; 9343 bool Swap = false; 9344 9345 // Shifts required to get the half-word we want at element 3. 9346 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9347 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9348 9349 uint32_t Mask = 0; 9350 uint32_t OriginalOrderLow = 0x1234567; 9351 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9352 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9353 // 32-bit space, only need 4-bit nibbles per element. 9354 for (unsigned i = 0; i < NumHalfWords; ++i) { 9355 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9356 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9357 } 9358 9359 // For each mask element, find out if we're just inserting something 9360 // from V2 into V1 or vice versa. Possible permutations inserting an element 9361 // from V2 into V1: 9362 // X, 1, 2, 3, 4, 5, 6, 7 9363 // 0, X, 2, 3, 4, 5, 6, 7 9364 // 0, 1, X, 3, 4, 5, 6, 7 9365 // 0, 1, 2, X, 4, 5, 6, 7 9366 // 0, 1, 2, 3, X, 5, 6, 7 9367 // 0, 1, 2, 3, 4, X, 6, 7 9368 // 0, 1, 2, 3, 4, 5, X, 7 9369 // 0, 1, 2, 3, 4, 5, 6, X 9370 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9371 9372 bool FoundCandidate = false; 9373 // Go through the mask of half-words to find an element that's being moved 9374 // from one vector to the other. 9375 for (unsigned i = 0; i < NumHalfWords; ++i) { 9376 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9377 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9378 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9379 uint32_t TargetOrder = 0x0; 9380 9381 // If both vector operands for the shuffle are the same vector, the mask 9382 // will contain only elements from the first one and the second one will be 9383 // undef. 9384 if (V2.isUndef()) { 9385 ShiftElts = 0; 9386 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9387 TargetOrder = OriginalOrderLow; 9388 Swap = false; 9389 // Skip if not the correct element or mask of other elements don't equal 9390 // to our expected order. 9391 if (MaskOneElt == VINSERTHSrcElem && 9392 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9393 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9394 FoundCandidate = true; 9395 break; 9396 } 9397 } else { // If both operands are defined. 9398 // Target order is [8,15] if the current mask is between [0,7]. 9399 TargetOrder = 9400 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9401 // Skip if mask of other elements don't equal our expected order. 9402 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9403 // We only need the last 3 bits for the number of shifts. 9404 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9405 : BigEndianShifts[MaskOneElt & 0x7]; 9406 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9407 Swap = MaskOneElt < NumHalfWords; 9408 FoundCandidate = true; 9409 break; 9410 } 9411 } 9412 } 9413 9414 if (!FoundCandidate) 9415 return SDValue(); 9416 9417 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9418 // optionally with VECSHL if shift is required. 9419 if (Swap) 9420 std::swap(V1, V2); 9421 if (V2.isUndef()) 9422 V2 = V1; 9423 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9424 if (ShiftElts) { 9425 // Double ShiftElts because we're left shifting on v16i8 type. 9426 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9427 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9428 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9429 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9430 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9431 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9432 } 9433 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9434 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9435 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9436 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9437 } 9438 9439 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9440 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9441 /// return the default SDValue. 9442 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9443 SelectionDAG &DAG) const { 9444 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9445 // to v16i8. Peek through the bitcasts to get the actual operands. 9446 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9447 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9448 9449 auto ShuffleMask = SVN->getMask(); 9450 SDValue VecShuffle(SVN, 0); 9451 SDLoc DL(SVN); 9452 9453 // Check that we have a four byte shuffle. 9454 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9455 return SDValue(); 9456 9457 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9458 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9459 std::swap(LHS, RHS); 9460 VecShuffle = DAG.getCommutedVectorShuffle(*SVN); 9461 ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask(); 9462 } 9463 9464 // Ensure that the RHS is a vector of constants. 9465 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9466 if (!BVN) 9467 return SDValue(); 9468 9469 // Check if RHS is a splat of 4-bytes (or smaller). 9470 APInt APSplatValue, APSplatUndef; 9471 unsigned SplatBitSize; 9472 bool HasAnyUndefs; 9473 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9474 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9475 SplatBitSize > 32) 9476 return SDValue(); 9477 9478 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9479 // The instruction splats a constant C into two words of the source vector 9480 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9481 // Thus we check that the shuffle mask is the equivalent of 9482 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9483 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9484 // within each word are consecutive, so we only need to check the first byte. 9485 SDValue Index; 9486 bool IsLE = Subtarget.isLittleEndian(); 9487 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9488 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9489 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9490 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9491 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9492 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9493 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9494 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9495 else 9496 return SDValue(); 9497 9498 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9499 // for XXSPLTI32DX. 9500 unsigned SplatVal = APSplatValue.getZExtValue(); 9501 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9502 SplatVal |= (SplatVal << SplatBitSize); 9503 9504 SDValue SplatNode = DAG.getNode( 9505 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9506 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9507 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9508 } 9509 9510 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9511 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9512 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9513 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9514 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9515 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9516 assert(Op.getValueType() == MVT::v1i128 && 9517 "Only set v1i128 as custom, other type shouldn't reach here!"); 9518 SDLoc dl(Op); 9519 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9520 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9521 unsigned SHLAmt = N1.getConstantOperandVal(0); 9522 if (SHLAmt % 8 == 0) { 9523 SmallVector<int, 16> Mask(16, 0); 9524 std::iota(Mask.begin(), Mask.end(), 0); 9525 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9526 if (SDValue Shuffle = 9527 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9528 DAG.getUNDEF(MVT::v16i8), Mask)) 9529 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9530 } 9531 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9532 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9533 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9534 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9535 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9536 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9537 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9538 } 9539 9540 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9541 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9542 /// return the code it can be lowered into. Worst case, it can always be 9543 /// lowered into a vperm. 9544 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9545 SelectionDAG &DAG) const { 9546 SDLoc dl(Op); 9547 SDValue V1 = Op.getOperand(0); 9548 SDValue V2 = Op.getOperand(1); 9549 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9550 9551 // Any nodes that were combined in the target-independent combiner prior 9552 // to vector legalization will not be sent to the target combine. Try to 9553 // combine it here. 9554 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9555 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9556 return NewShuffle; 9557 Op = NewShuffle; 9558 SVOp = cast<ShuffleVectorSDNode>(Op); 9559 V1 = Op.getOperand(0); 9560 V2 = Op.getOperand(1); 9561 } 9562 EVT VT = Op.getValueType(); 9563 bool isLittleEndian = Subtarget.isLittleEndian(); 9564 9565 unsigned ShiftElts, InsertAtByte; 9566 bool Swap = false; 9567 9568 // If this is a load-and-splat, we can do that with a single instruction 9569 // in some cases. However if the load has multiple uses, we don't want to 9570 // combine it because that will just produce multiple loads. 9571 bool IsPermutedLoad = false; 9572 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9573 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9574 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9575 InputLoad->hasOneUse()) { 9576 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9577 int SplatIdx = 9578 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9579 9580 // The splat index for permuted loads will be in the left half of the vector 9581 // which is strictly wider than the loaded value by 8 bytes. So we need to 9582 // adjust the splat index to point to the correct address in memory. 9583 if (IsPermutedLoad) { 9584 assert(isLittleEndian && "Unexpected permuted load on big endian target"); 9585 SplatIdx += IsFourByte ? 2 : 1; 9586 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9587 "Splat of a value outside of the loaded memory"); 9588 } 9589 9590 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9591 // For 4-byte load-and-splat, we need Power9. 9592 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9593 uint64_t Offset = 0; 9594 if (IsFourByte) 9595 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9596 else 9597 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9598 9599 SDValue BasePtr = LD->getBasePtr(); 9600 if (Offset != 0) 9601 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9602 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9603 SDValue Ops[] = { 9604 LD->getChain(), // Chain 9605 BasePtr, // BasePtr 9606 DAG.getValueType(Op.getValueType()) // VT 9607 }; 9608 SDVTList VTL = 9609 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9610 SDValue LdSplt = 9611 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9612 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9613 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9614 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9615 return LdSplt; 9616 } 9617 } 9618 if (Subtarget.hasP9Vector() && 9619 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9620 isLittleEndian)) { 9621 if (Swap) 9622 std::swap(V1, V2); 9623 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9624 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9625 if (ShiftElts) { 9626 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9627 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9628 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9629 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9630 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9631 } 9632 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9633 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9634 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9635 } 9636 9637 if (Subtarget.hasPrefixInstrs()) { 9638 SDValue SplatInsertNode; 9639 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9640 return SplatInsertNode; 9641 } 9642 9643 if (Subtarget.hasP9Altivec()) { 9644 SDValue NewISDNode; 9645 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9646 return NewISDNode; 9647 9648 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9649 return NewISDNode; 9650 } 9651 9652 if (Subtarget.hasVSX() && 9653 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9654 if (Swap) 9655 std::swap(V1, V2); 9656 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9657 SDValue Conv2 = 9658 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9659 9660 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9661 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9662 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9663 } 9664 9665 if (Subtarget.hasVSX() && 9666 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9667 if (Swap) 9668 std::swap(V1, V2); 9669 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9670 SDValue Conv2 = 9671 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9672 9673 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9674 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9675 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9676 } 9677 9678 if (Subtarget.hasP9Vector()) { 9679 if (PPC::isXXBRHShuffleMask(SVOp)) { 9680 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9681 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9682 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9683 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9684 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9685 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9686 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9687 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9688 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9689 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9690 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9691 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9692 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9693 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9694 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9695 } 9696 } 9697 9698 if (Subtarget.hasVSX()) { 9699 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9700 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9701 9702 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9703 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9704 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9705 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9706 } 9707 9708 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9709 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9710 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9711 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9712 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9713 } 9714 } 9715 9716 // Cases that are handled by instructions that take permute immediates 9717 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9718 // selected by the instruction selector. 9719 if (V2.isUndef()) { 9720 if (PPC::isSplatShuffleMask(SVOp, 1) || 9721 PPC::isSplatShuffleMask(SVOp, 2) || 9722 PPC::isSplatShuffleMask(SVOp, 4) || 9723 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9724 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9725 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9726 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9727 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9728 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9729 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9730 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9731 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9732 (Subtarget.hasP8Altivec() && ( 9733 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9734 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9735 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9736 return Op; 9737 } 9738 } 9739 9740 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9741 // and produce a fixed permutation. If any of these match, do not lower to 9742 // VPERM. 9743 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9744 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9745 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9746 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9747 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9748 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9749 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9750 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9751 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9752 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9753 (Subtarget.hasP8Altivec() && ( 9754 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9755 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9756 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9757 return Op; 9758 9759 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9760 // perfect shuffle table to emit an optimal matching sequence. 9761 ArrayRef<int> PermMask = SVOp->getMask(); 9762 9763 unsigned PFIndexes[4]; 9764 bool isFourElementShuffle = true; 9765 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9766 unsigned EltNo = 8; // Start out undef. 9767 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9768 if (PermMask[i*4+j] < 0) 9769 continue; // Undef, ignore it. 9770 9771 unsigned ByteSource = PermMask[i*4+j]; 9772 if ((ByteSource & 3) != j) { 9773 isFourElementShuffle = false; 9774 break; 9775 } 9776 9777 if (EltNo == 8) { 9778 EltNo = ByteSource/4; 9779 } else if (EltNo != ByteSource/4) { 9780 isFourElementShuffle = false; 9781 break; 9782 } 9783 } 9784 PFIndexes[i] = EltNo; 9785 } 9786 9787 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9788 // perfect shuffle vector to determine if it is cost effective to do this as 9789 // discrete instructions, or whether we should use a vperm. 9790 // For now, we skip this for little endian until such time as we have a 9791 // little-endian perfect shuffle table. 9792 if (isFourElementShuffle && !isLittleEndian) { 9793 // Compute the index in the perfect shuffle table. 9794 unsigned PFTableIndex = 9795 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9796 9797 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9798 unsigned Cost = (PFEntry >> 30); 9799 9800 // Determining when to avoid vperm is tricky. Many things affect the cost 9801 // of vperm, particularly how many times the perm mask needs to be computed. 9802 // For example, if the perm mask can be hoisted out of a loop or is already 9803 // used (perhaps because there are multiple permutes with the same shuffle 9804 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9805 // the loop requires an extra register. 9806 // 9807 // As a compromise, we only emit discrete instructions if the shuffle can be 9808 // generated in 3 or fewer operations. When we have loop information 9809 // available, if this block is within a loop, we should avoid using vperm 9810 // for 3-operation perms and use a constant pool load instead. 9811 if (Cost < 3) 9812 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9813 } 9814 9815 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9816 // vector that will get spilled to the constant pool. 9817 if (V2.isUndef()) V2 = V1; 9818 9819 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9820 // that it is in input element units, not in bytes. Convert now. 9821 9822 // For little endian, the order of the input vectors is reversed, and 9823 // the permutation mask is complemented with respect to 31. This is 9824 // necessary to produce proper semantics with the big-endian-biased vperm 9825 // instruction. 9826 EVT EltVT = V1.getValueType().getVectorElementType(); 9827 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9828 9829 SmallVector<SDValue, 16> ResultMask; 9830 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9831 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9832 9833 for (unsigned j = 0; j != BytesPerElement; ++j) 9834 if (isLittleEndian) 9835 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9836 dl, MVT::i32)); 9837 else 9838 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9839 MVT::i32)); 9840 } 9841 9842 ShufflesHandledWithVPERM++; 9843 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9844 LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n"); 9845 LLVM_DEBUG(SVOp->dump()); 9846 LLVM_DEBUG(dbgs() << "With the following permute control vector:\n"); 9847 LLVM_DEBUG(VPermMask.dump()); 9848 9849 if (isLittleEndian) 9850 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9851 V2, V1, VPermMask); 9852 else 9853 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9854 V1, V2, VPermMask); 9855 } 9856 9857 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9858 /// vector comparison. If it is, return true and fill in Opc/isDot with 9859 /// information about the intrinsic. 9860 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9861 bool &isDot, const PPCSubtarget &Subtarget) { 9862 unsigned IntrinsicID = 9863 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9864 CompareOpc = -1; 9865 isDot = false; 9866 switch (IntrinsicID) { 9867 default: 9868 return false; 9869 // Comparison predicates. 9870 case Intrinsic::ppc_altivec_vcmpbfp_p: 9871 CompareOpc = 966; 9872 isDot = true; 9873 break; 9874 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9875 CompareOpc = 198; 9876 isDot = true; 9877 break; 9878 case Intrinsic::ppc_altivec_vcmpequb_p: 9879 CompareOpc = 6; 9880 isDot = true; 9881 break; 9882 case Intrinsic::ppc_altivec_vcmpequh_p: 9883 CompareOpc = 70; 9884 isDot = true; 9885 break; 9886 case Intrinsic::ppc_altivec_vcmpequw_p: 9887 CompareOpc = 134; 9888 isDot = true; 9889 break; 9890 case Intrinsic::ppc_altivec_vcmpequd_p: 9891 if (Subtarget.hasP8Altivec()) { 9892 CompareOpc = 199; 9893 isDot = true; 9894 } else 9895 return false; 9896 break; 9897 case Intrinsic::ppc_altivec_vcmpneb_p: 9898 case Intrinsic::ppc_altivec_vcmpneh_p: 9899 case Intrinsic::ppc_altivec_vcmpnew_p: 9900 case Intrinsic::ppc_altivec_vcmpnezb_p: 9901 case Intrinsic::ppc_altivec_vcmpnezh_p: 9902 case Intrinsic::ppc_altivec_vcmpnezw_p: 9903 if (Subtarget.hasP9Altivec()) { 9904 switch (IntrinsicID) { 9905 default: 9906 llvm_unreachable("Unknown comparison intrinsic."); 9907 case Intrinsic::ppc_altivec_vcmpneb_p: 9908 CompareOpc = 7; 9909 break; 9910 case Intrinsic::ppc_altivec_vcmpneh_p: 9911 CompareOpc = 71; 9912 break; 9913 case Intrinsic::ppc_altivec_vcmpnew_p: 9914 CompareOpc = 135; 9915 break; 9916 case Intrinsic::ppc_altivec_vcmpnezb_p: 9917 CompareOpc = 263; 9918 break; 9919 case Intrinsic::ppc_altivec_vcmpnezh_p: 9920 CompareOpc = 327; 9921 break; 9922 case Intrinsic::ppc_altivec_vcmpnezw_p: 9923 CompareOpc = 391; 9924 break; 9925 } 9926 isDot = true; 9927 } else 9928 return false; 9929 break; 9930 case Intrinsic::ppc_altivec_vcmpgefp_p: 9931 CompareOpc = 454; 9932 isDot = true; 9933 break; 9934 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9935 CompareOpc = 710; 9936 isDot = true; 9937 break; 9938 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9939 CompareOpc = 774; 9940 isDot = true; 9941 break; 9942 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9943 CompareOpc = 838; 9944 isDot = true; 9945 break; 9946 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9947 CompareOpc = 902; 9948 isDot = true; 9949 break; 9950 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9951 if (Subtarget.hasP8Altivec()) { 9952 CompareOpc = 967; 9953 isDot = true; 9954 } else 9955 return false; 9956 break; 9957 case Intrinsic::ppc_altivec_vcmpgtub_p: 9958 CompareOpc = 518; 9959 isDot = true; 9960 break; 9961 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9962 CompareOpc = 582; 9963 isDot = true; 9964 break; 9965 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9966 CompareOpc = 646; 9967 isDot = true; 9968 break; 9969 case Intrinsic::ppc_altivec_vcmpgtud_p: 9970 if (Subtarget.hasP8Altivec()) { 9971 CompareOpc = 711; 9972 isDot = true; 9973 } else 9974 return false; 9975 break; 9976 9977 // VSX predicate comparisons use the same infrastructure 9978 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9979 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9980 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9981 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9982 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9983 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9984 if (Subtarget.hasVSX()) { 9985 switch (IntrinsicID) { 9986 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9987 CompareOpc = 99; 9988 break; 9989 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9990 CompareOpc = 115; 9991 break; 9992 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9993 CompareOpc = 107; 9994 break; 9995 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9996 CompareOpc = 67; 9997 break; 9998 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9999 CompareOpc = 83; 10000 break; 10001 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10002 CompareOpc = 75; 10003 break; 10004 } 10005 isDot = true; 10006 } else 10007 return false; 10008 break; 10009 10010 // Normal Comparisons. 10011 case Intrinsic::ppc_altivec_vcmpbfp: 10012 CompareOpc = 966; 10013 break; 10014 case Intrinsic::ppc_altivec_vcmpeqfp: 10015 CompareOpc = 198; 10016 break; 10017 case Intrinsic::ppc_altivec_vcmpequb: 10018 CompareOpc = 6; 10019 break; 10020 case Intrinsic::ppc_altivec_vcmpequh: 10021 CompareOpc = 70; 10022 break; 10023 case Intrinsic::ppc_altivec_vcmpequw: 10024 CompareOpc = 134; 10025 break; 10026 case Intrinsic::ppc_altivec_vcmpequd: 10027 if (Subtarget.hasP8Altivec()) 10028 CompareOpc = 199; 10029 else 10030 return false; 10031 break; 10032 case Intrinsic::ppc_altivec_vcmpneb: 10033 case Intrinsic::ppc_altivec_vcmpneh: 10034 case Intrinsic::ppc_altivec_vcmpnew: 10035 case Intrinsic::ppc_altivec_vcmpnezb: 10036 case Intrinsic::ppc_altivec_vcmpnezh: 10037 case Intrinsic::ppc_altivec_vcmpnezw: 10038 if (Subtarget.hasP9Altivec()) 10039 switch (IntrinsicID) { 10040 default: 10041 llvm_unreachable("Unknown comparison intrinsic."); 10042 case Intrinsic::ppc_altivec_vcmpneb: 10043 CompareOpc = 7; 10044 break; 10045 case Intrinsic::ppc_altivec_vcmpneh: 10046 CompareOpc = 71; 10047 break; 10048 case Intrinsic::ppc_altivec_vcmpnew: 10049 CompareOpc = 135; 10050 break; 10051 case Intrinsic::ppc_altivec_vcmpnezb: 10052 CompareOpc = 263; 10053 break; 10054 case Intrinsic::ppc_altivec_vcmpnezh: 10055 CompareOpc = 327; 10056 break; 10057 case Intrinsic::ppc_altivec_vcmpnezw: 10058 CompareOpc = 391; 10059 break; 10060 } 10061 else 10062 return false; 10063 break; 10064 case Intrinsic::ppc_altivec_vcmpgefp: 10065 CompareOpc = 454; 10066 break; 10067 case Intrinsic::ppc_altivec_vcmpgtfp: 10068 CompareOpc = 710; 10069 break; 10070 case Intrinsic::ppc_altivec_vcmpgtsb: 10071 CompareOpc = 774; 10072 break; 10073 case Intrinsic::ppc_altivec_vcmpgtsh: 10074 CompareOpc = 838; 10075 break; 10076 case Intrinsic::ppc_altivec_vcmpgtsw: 10077 CompareOpc = 902; 10078 break; 10079 case Intrinsic::ppc_altivec_vcmpgtsd: 10080 if (Subtarget.hasP8Altivec()) 10081 CompareOpc = 967; 10082 else 10083 return false; 10084 break; 10085 case Intrinsic::ppc_altivec_vcmpgtub: 10086 CompareOpc = 518; 10087 break; 10088 case Intrinsic::ppc_altivec_vcmpgtuh: 10089 CompareOpc = 582; 10090 break; 10091 case Intrinsic::ppc_altivec_vcmpgtuw: 10092 CompareOpc = 646; 10093 break; 10094 case Intrinsic::ppc_altivec_vcmpgtud: 10095 if (Subtarget.hasP8Altivec()) 10096 CompareOpc = 711; 10097 else 10098 return false; 10099 break; 10100 } 10101 return true; 10102 } 10103 10104 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10105 /// lower, do it, otherwise return null. 10106 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10107 SelectionDAG &DAG) const { 10108 unsigned IntrinsicID = 10109 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10110 10111 SDLoc dl(Op); 10112 10113 if (IntrinsicID == Intrinsic::thread_pointer) { 10114 // Reads the thread pointer register, used for __builtin_thread_pointer. 10115 if (Subtarget.isPPC64()) 10116 return DAG.getRegister(PPC::X13, MVT::i64); 10117 return DAG.getRegister(PPC::R2, MVT::i32); 10118 } 10119 10120 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10121 // opcode number of the comparison. 10122 int CompareOpc; 10123 bool isDot; 10124 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10125 return SDValue(); // Don't custom lower most intrinsics. 10126 10127 // If this is a non-dot comparison, make the VCMP node and we are done. 10128 if (!isDot) { 10129 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10130 Op.getOperand(1), Op.getOperand(2), 10131 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10132 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10133 } 10134 10135 // Create the PPCISD altivec 'dot' comparison node. 10136 SDValue Ops[] = { 10137 Op.getOperand(2), // LHS 10138 Op.getOperand(3), // RHS 10139 DAG.getConstant(CompareOpc, dl, MVT::i32) 10140 }; 10141 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10142 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 10143 10144 // Now that we have the comparison, emit a copy from the CR to a GPR. 10145 // This is flagged to the above dot comparison. 10146 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10147 DAG.getRegister(PPC::CR6, MVT::i32), 10148 CompNode.getValue(1)); 10149 10150 // Unpack the result based on how the target uses it. 10151 unsigned BitNo; // Bit # of CR6. 10152 bool InvertBit; // Invert result? 10153 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10154 default: // Can't happen, don't crash on invalid number though. 10155 case 0: // Return the value of the EQ bit of CR6. 10156 BitNo = 0; InvertBit = false; 10157 break; 10158 case 1: // Return the inverted value of the EQ bit of CR6. 10159 BitNo = 0; InvertBit = true; 10160 break; 10161 case 2: // Return the value of the LT bit of CR6. 10162 BitNo = 2; InvertBit = false; 10163 break; 10164 case 3: // Return the inverted value of the LT bit of CR6. 10165 BitNo = 2; InvertBit = true; 10166 break; 10167 } 10168 10169 // Shift the bit into the low position. 10170 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10171 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10172 // Isolate the bit. 10173 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10174 DAG.getConstant(1, dl, MVT::i32)); 10175 10176 // If we are supposed to, toggle the bit. 10177 if (InvertBit) 10178 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10179 DAG.getConstant(1, dl, MVT::i32)); 10180 return Flags; 10181 } 10182 10183 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10184 SelectionDAG &DAG) const { 10185 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10186 // the beginning of the argument list. 10187 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10188 SDLoc DL(Op); 10189 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10190 case Intrinsic::ppc_cfence: { 10191 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10192 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10193 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10194 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 10195 Op.getOperand(ArgStart + 1)), 10196 Op.getOperand(0)), 10197 0); 10198 } 10199 default: 10200 break; 10201 } 10202 return SDValue(); 10203 } 10204 10205 // Lower scalar BSWAP64 to xxbrd. 10206 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10207 SDLoc dl(Op); 10208 // MTVSRDD 10209 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10210 Op.getOperand(0)); 10211 // XXBRD 10212 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10213 // MFVSRD 10214 int VectorIndex = 0; 10215 if (Subtarget.isLittleEndian()) 10216 VectorIndex = 1; 10217 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10218 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10219 return Op; 10220 } 10221 10222 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10223 // compared to a value that is atomically loaded (atomic loads zero-extend). 10224 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10225 SelectionDAG &DAG) const { 10226 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10227 "Expecting an atomic compare-and-swap here."); 10228 SDLoc dl(Op); 10229 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10230 EVT MemVT = AtomicNode->getMemoryVT(); 10231 if (MemVT.getSizeInBits() >= 32) 10232 return Op; 10233 10234 SDValue CmpOp = Op.getOperand(2); 10235 // If this is already correctly zero-extended, leave it alone. 10236 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10237 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10238 return Op; 10239 10240 // Clear the high bits of the compare operand. 10241 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10242 SDValue NewCmpOp = 10243 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10244 DAG.getConstant(MaskVal, dl, MVT::i32)); 10245 10246 // Replace the existing compare operand with the properly zero-extended one. 10247 SmallVector<SDValue, 4> Ops; 10248 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10249 Ops.push_back(AtomicNode->getOperand(i)); 10250 Ops[2] = NewCmpOp; 10251 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10252 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10253 auto NodeTy = 10254 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10255 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10256 } 10257 10258 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10259 SelectionDAG &DAG) const { 10260 SDLoc dl(Op); 10261 // Create a stack slot that is 16-byte aligned. 10262 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10263 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10264 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10265 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10266 10267 // Store the input value into Value#0 of the stack slot. 10268 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10269 MachinePointerInfo()); 10270 // Load it out. 10271 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10272 } 10273 10274 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10275 SelectionDAG &DAG) const { 10276 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10277 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10278 10279 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10280 // We have legal lowering for constant indices but not for variable ones. 10281 if (!C) 10282 return SDValue(); 10283 10284 EVT VT = Op.getValueType(); 10285 SDLoc dl(Op); 10286 SDValue V1 = Op.getOperand(0); 10287 SDValue V2 = Op.getOperand(1); 10288 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 10289 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 10290 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 10291 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 10292 unsigned InsertAtElement = C->getZExtValue(); 10293 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 10294 if (Subtarget.isLittleEndian()) { 10295 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 10296 } 10297 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 10298 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 10299 } 10300 return Op; 10301 } 10302 10303 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10304 SDLoc dl(Op); 10305 if (Op.getValueType() == MVT::v4i32) { 10306 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10307 10308 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 10309 // +16 as shift amt. 10310 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 10311 SDValue RHSSwap = // = vrlw RHS, 16 10312 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10313 10314 // Shrinkify inputs to v8i16. 10315 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10316 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10317 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10318 10319 // Low parts multiplied together, generating 32-bit results (we ignore the 10320 // top parts). 10321 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10322 LHS, RHS, DAG, dl, MVT::v4i32); 10323 10324 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10325 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10326 // Shift the high parts up 16 bits. 10327 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10328 Neg16, DAG, dl); 10329 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10330 } else if (Op.getValueType() == MVT::v16i8) { 10331 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10332 bool isLittleEndian = Subtarget.isLittleEndian(); 10333 10334 // Multiply the even 8-bit parts, producing 16-bit sums. 10335 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10336 LHS, RHS, DAG, dl, MVT::v8i16); 10337 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10338 10339 // Multiply the odd 8-bit parts, producing 16-bit sums. 10340 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10341 LHS, RHS, DAG, dl, MVT::v8i16); 10342 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10343 10344 // Merge the results together. Because vmuleub and vmuloub are 10345 // instructions with a big-endian bias, we must reverse the 10346 // element numbering and reverse the meaning of "odd" and "even" 10347 // when generating little endian code. 10348 int Ops[16]; 10349 for (unsigned i = 0; i != 8; ++i) { 10350 if (isLittleEndian) { 10351 Ops[i*2 ] = 2*i; 10352 Ops[i*2+1] = 2*i+16; 10353 } else { 10354 Ops[i*2 ] = 2*i+1; 10355 Ops[i*2+1] = 2*i+1+16; 10356 } 10357 } 10358 if (isLittleEndian) 10359 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10360 else 10361 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10362 } else { 10363 llvm_unreachable("Unknown mul to lower!"); 10364 } 10365 } 10366 10367 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10368 10369 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10370 10371 EVT VT = Op.getValueType(); 10372 assert(VT.isVector() && 10373 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10374 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10375 VT == MVT::v16i8) && 10376 "Unexpected vector element type!"); 10377 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10378 "Current subtarget doesn't support smax v2i64!"); 10379 10380 // For vector abs, it can be lowered to: 10381 // abs x 10382 // ==> 10383 // y = -x 10384 // smax(x, y) 10385 10386 SDLoc dl(Op); 10387 SDValue X = Op.getOperand(0); 10388 SDValue Zero = DAG.getConstant(0, dl, VT); 10389 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10390 10391 // SMAX patch https://reviews.llvm.org/D47332 10392 // hasn't landed yet, so use intrinsic first here. 10393 // TODO: Should use SMAX directly once SMAX patch landed 10394 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10395 if (VT == MVT::v2i64) 10396 BifID = Intrinsic::ppc_altivec_vmaxsd; 10397 else if (VT == MVT::v8i16) 10398 BifID = Intrinsic::ppc_altivec_vmaxsh; 10399 else if (VT == MVT::v16i8) 10400 BifID = Intrinsic::ppc_altivec_vmaxsb; 10401 10402 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10403 } 10404 10405 // Custom lowering for fpext vf32 to v2f64 10406 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10407 10408 assert(Op.getOpcode() == ISD::FP_EXTEND && 10409 "Should only be called for ISD::FP_EXTEND"); 10410 10411 // FIXME: handle extends from half precision float vectors on P9. 10412 // We only want to custom lower an extend from v2f32 to v2f64. 10413 if (Op.getValueType() != MVT::v2f64 || 10414 Op.getOperand(0).getValueType() != MVT::v2f32) 10415 return SDValue(); 10416 10417 SDLoc dl(Op); 10418 SDValue Op0 = Op.getOperand(0); 10419 10420 switch (Op0.getOpcode()) { 10421 default: 10422 return SDValue(); 10423 case ISD::EXTRACT_SUBVECTOR: { 10424 assert(Op0.getNumOperands() == 2 && 10425 isa<ConstantSDNode>(Op0->getOperand(1)) && 10426 "Node should have 2 operands with second one being a constant!"); 10427 10428 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10429 return SDValue(); 10430 10431 // Custom lower is only done for high or low doubleword. 10432 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10433 if (Idx % 2 != 0) 10434 return SDValue(); 10435 10436 // Since input is v4f32, at this point Idx is either 0 or 2. 10437 // Shift to get the doubleword position we want. 10438 int DWord = Idx >> 1; 10439 10440 // High and low word positions are different on little endian. 10441 if (Subtarget.isLittleEndian()) 10442 DWord ^= 0x1; 10443 10444 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10445 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10446 } 10447 case ISD::FADD: 10448 case ISD::FMUL: 10449 case ISD::FSUB: { 10450 SDValue NewLoad[2]; 10451 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10452 // Ensure both input are loads. 10453 SDValue LdOp = Op0.getOperand(i); 10454 if (LdOp.getOpcode() != ISD::LOAD) 10455 return SDValue(); 10456 // Generate new load node. 10457 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10458 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10459 NewLoad[i] = DAG.getMemIntrinsicNode( 10460 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10461 LD->getMemoryVT(), LD->getMemOperand()); 10462 } 10463 SDValue NewOp = 10464 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10465 NewLoad[1], Op0.getNode()->getFlags()); 10466 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10467 DAG.getConstant(0, dl, MVT::i32)); 10468 } 10469 case ISD::LOAD: { 10470 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10471 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10472 SDValue NewLd = DAG.getMemIntrinsicNode( 10473 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10474 LD->getMemoryVT(), LD->getMemOperand()); 10475 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10476 DAG.getConstant(0, dl, MVT::i32)); 10477 } 10478 } 10479 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10480 } 10481 10482 /// LowerOperation - Provide custom lowering hooks for some operations. 10483 /// 10484 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10485 switch (Op.getOpcode()) { 10486 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10487 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10488 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10489 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10490 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10491 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10492 case ISD::SETCC: return LowerSETCC(Op, DAG); 10493 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10494 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10495 10496 // Variable argument lowering. 10497 case ISD::VASTART: return LowerVASTART(Op, DAG); 10498 case ISD::VAARG: return LowerVAARG(Op, DAG); 10499 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10500 10501 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10502 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10503 case ISD::GET_DYNAMIC_AREA_OFFSET: 10504 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10505 10506 // Exception handling lowering. 10507 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10508 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10509 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10510 10511 case ISD::LOAD: return LowerLOAD(Op, DAG); 10512 case ISD::STORE: return LowerSTORE(Op, DAG); 10513 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10514 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10515 case ISD::STRICT_FP_TO_UINT: 10516 case ISD::STRICT_FP_TO_SINT: 10517 case ISD::FP_TO_UINT: 10518 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10519 case ISD::UINT_TO_FP: 10520 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10521 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10522 10523 // Lower 64-bit shifts. 10524 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10525 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10526 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10527 10528 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 10529 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 10530 10531 // Vector-related lowering. 10532 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10533 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10534 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10535 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10536 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10537 case ISD::MUL: return LowerMUL(Op, DAG); 10538 case ISD::ABS: return LowerABS(Op, DAG); 10539 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10540 case ISD::ROTL: return LowerROTL(Op, DAG); 10541 10542 // For counter-based loop handling. 10543 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10544 10545 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10546 10547 // Frame & Return address. 10548 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10549 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10550 10551 case ISD::INTRINSIC_VOID: 10552 return LowerINTRINSIC_VOID(Op, DAG); 10553 case ISD::BSWAP: 10554 return LowerBSWAP(Op, DAG); 10555 case ISD::ATOMIC_CMP_SWAP: 10556 return LowerATOMIC_CMP_SWAP(Op, DAG); 10557 } 10558 } 10559 10560 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10561 SmallVectorImpl<SDValue>&Results, 10562 SelectionDAG &DAG) const { 10563 SDLoc dl(N); 10564 switch (N->getOpcode()) { 10565 default: 10566 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10567 case ISD::READCYCLECOUNTER: { 10568 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10569 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10570 10571 Results.push_back( 10572 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10573 Results.push_back(RTB.getValue(2)); 10574 break; 10575 } 10576 case ISD::INTRINSIC_W_CHAIN: { 10577 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10578 Intrinsic::loop_decrement) 10579 break; 10580 10581 assert(N->getValueType(0) == MVT::i1 && 10582 "Unexpected result type for CTR decrement intrinsic"); 10583 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10584 N->getValueType(0)); 10585 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10586 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10587 N->getOperand(1)); 10588 10589 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10590 Results.push_back(NewInt.getValue(1)); 10591 break; 10592 } 10593 case ISD::VAARG: { 10594 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10595 return; 10596 10597 EVT VT = N->getValueType(0); 10598 10599 if (VT == MVT::i64) { 10600 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10601 10602 Results.push_back(NewNode); 10603 Results.push_back(NewNode.getValue(1)); 10604 } 10605 return; 10606 } 10607 case ISD::STRICT_FP_TO_SINT: 10608 case ISD::STRICT_FP_TO_UINT: 10609 case ISD::FP_TO_SINT: 10610 case ISD::FP_TO_UINT: 10611 // LowerFP_TO_INT() can only handle f32 and f64. 10612 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 10613 MVT::ppcf128) 10614 return; 10615 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10616 return; 10617 case ISD::TRUNCATE: { 10618 EVT TrgVT = N->getValueType(0); 10619 EVT OpVT = N->getOperand(0).getValueType(); 10620 if (TrgVT.isVector() && 10621 isOperationCustom(N->getOpcode(), TrgVT) && 10622 OpVT.getSizeInBits() <= 128 && 10623 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10624 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10625 return; 10626 } 10627 case ISD::BITCAST: 10628 // Don't handle bitcast here. 10629 return; 10630 case ISD::FP_EXTEND: 10631 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 10632 if (Lowered) 10633 Results.push_back(Lowered); 10634 return; 10635 } 10636 } 10637 10638 //===----------------------------------------------------------------------===// 10639 // Other Lowering Code 10640 //===----------------------------------------------------------------------===// 10641 10642 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10643 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10644 Function *Func = Intrinsic::getDeclaration(M, Id); 10645 return Builder.CreateCall(Func, {}); 10646 } 10647 10648 // The mappings for emitLeading/TrailingFence is taken from 10649 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10650 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10651 Instruction *Inst, 10652 AtomicOrdering Ord) const { 10653 if (Ord == AtomicOrdering::SequentiallyConsistent) 10654 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10655 if (isReleaseOrStronger(Ord)) 10656 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10657 return nullptr; 10658 } 10659 10660 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10661 Instruction *Inst, 10662 AtomicOrdering Ord) const { 10663 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10664 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10665 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10666 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10667 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10668 return Builder.CreateCall( 10669 Intrinsic::getDeclaration( 10670 Builder.GetInsertBlock()->getParent()->getParent(), 10671 Intrinsic::ppc_cfence, {Inst->getType()}), 10672 {Inst}); 10673 // FIXME: Can use isync for rmw operation. 10674 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10675 } 10676 return nullptr; 10677 } 10678 10679 MachineBasicBlock * 10680 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10681 unsigned AtomicSize, 10682 unsigned BinOpcode, 10683 unsigned CmpOpcode, 10684 unsigned CmpPred) const { 10685 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10686 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10687 10688 auto LoadMnemonic = PPC::LDARX; 10689 auto StoreMnemonic = PPC::STDCX; 10690 switch (AtomicSize) { 10691 default: 10692 llvm_unreachable("Unexpected size of atomic entity"); 10693 case 1: 10694 LoadMnemonic = PPC::LBARX; 10695 StoreMnemonic = PPC::STBCX; 10696 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10697 break; 10698 case 2: 10699 LoadMnemonic = PPC::LHARX; 10700 StoreMnemonic = PPC::STHCX; 10701 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10702 break; 10703 case 4: 10704 LoadMnemonic = PPC::LWARX; 10705 StoreMnemonic = PPC::STWCX; 10706 break; 10707 case 8: 10708 LoadMnemonic = PPC::LDARX; 10709 StoreMnemonic = PPC::STDCX; 10710 break; 10711 } 10712 10713 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10714 MachineFunction *F = BB->getParent(); 10715 MachineFunction::iterator It = ++BB->getIterator(); 10716 10717 Register dest = MI.getOperand(0).getReg(); 10718 Register ptrA = MI.getOperand(1).getReg(); 10719 Register ptrB = MI.getOperand(2).getReg(); 10720 Register incr = MI.getOperand(3).getReg(); 10721 DebugLoc dl = MI.getDebugLoc(); 10722 10723 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10724 MachineBasicBlock *loop2MBB = 10725 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10726 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10727 F->insert(It, loopMBB); 10728 if (CmpOpcode) 10729 F->insert(It, loop2MBB); 10730 F->insert(It, exitMBB); 10731 exitMBB->splice(exitMBB->begin(), BB, 10732 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10733 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10734 10735 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10736 Register TmpReg = (!BinOpcode) ? incr : 10737 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10738 : &PPC::GPRCRegClass); 10739 10740 // thisMBB: 10741 // ... 10742 // fallthrough --> loopMBB 10743 BB->addSuccessor(loopMBB); 10744 10745 // loopMBB: 10746 // l[wd]arx dest, ptr 10747 // add r0, dest, incr 10748 // st[wd]cx. r0, ptr 10749 // bne- loopMBB 10750 // fallthrough --> exitMBB 10751 10752 // For max/min... 10753 // loopMBB: 10754 // l[wd]arx dest, ptr 10755 // cmpl?[wd] incr, dest 10756 // bgt exitMBB 10757 // loop2MBB: 10758 // st[wd]cx. dest, ptr 10759 // bne- loopMBB 10760 // fallthrough --> exitMBB 10761 10762 BB = loopMBB; 10763 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10764 .addReg(ptrA).addReg(ptrB); 10765 if (BinOpcode) 10766 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10767 if (CmpOpcode) { 10768 // Signed comparisons of byte or halfword values must be sign-extended. 10769 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10770 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10771 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10772 ExtReg).addReg(dest); 10773 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10774 .addReg(incr).addReg(ExtReg); 10775 } else 10776 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10777 .addReg(incr).addReg(dest); 10778 10779 BuildMI(BB, dl, TII->get(PPC::BCC)) 10780 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10781 BB->addSuccessor(loop2MBB); 10782 BB->addSuccessor(exitMBB); 10783 BB = loop2MBB; 10784 } 10785 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10786 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10787 BuildMI(BB, dl, TII->get(PPC::BCC)) 10788 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10789 BB->addSuccessor(loopMBB); 10790 BB->addSuccessor(exitMBB); 10791 10792 // exitMBB: 10793 // ... 10794 BB = exitMBB; 10795 return BB; 10796 } 10797 10798 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10799 MachineInstr &MI, MachineBasicBlock *BB, 10800 bool is8bit, // operation 10801 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10802 // If we support part-word atomic mnemonics, just use them 10803 if (Subtarget.hasPartwordAtomics()) 10804 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10805 CmpPred); 10806 10807 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10808 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10809 // In 64 bit mode we have to use 64 bits for addresses, even though the 10810 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10811 // registers without caring whether they're 32 or 64, but here we're 10812 // doing actual arithmetic on the addresses. 10813 bool is64bit = Subtarget.isPPC64(); 10814 bool isLittleEndian = Subtarget.isLittleEndian(); 10815 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10816 10817 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10818 MachineFunction *F = BB->getParent(); 10819 MachineFunction::iterator It = ++BB->getIterator(); 10820 10821 Register dest = MI.getOperand(0).getReg(); 10822 Register ptrA = MI.getOperand(1).getReg(); 10823 Register ptrB = MI.getOperand(2).getReg(); 10824 Register incr = MI.getOperand(3).getReg(); 10825 DebugLoc dl = MI.getDebugLoc(); 10826 10827 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10828 MachineBasicBlock *loop2MBB = 10829 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10830 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10831 F->insert(It, loopMBB); 10832 if (CmpOpcode) 10833 F->insert(It, loop2MBB); 10834 F->insert(It, exitMBB); 10835 exitMBB->splice(exitMBB->begin(), BB, 10836 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10837 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10838 10839 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10840 const TargetRegisterClass *RC = 10841 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10842 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10843 10844 Register PtrReg = RegInfo.createVirtualRegister(RC); 10845 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10846 Register ShiftReg = 10847 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10848 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10849 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10850 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10851 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10852 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10853 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10854 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10855 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10856 Register Ptr1Reg; 10857 Register TmpReg = 10858 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10859 10860 // thisMBB: 10861 // ... 10862 // fallthrough --> loopMBB 10863 BB->addSuccessor(loopMBB); 10864 10865 // The 4-byte load must be aligned, while a char or short may be 10866 // anywhere in the word. Hence all this nasty bookkeeping code. 10867 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10868 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10869 // xori shift, shift1, 24 [16] 10870 // rlwinm ptr, ptr1, 0, 0, 29 10871 // slw incr2, incr, shift 10872 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10873 // slw mask, mask2, shift 10874 // loopMBB: 10875 // lwarx tmpDest, ptr 10876 // add tmp, tmpDest, incr2 10877 // andc tmp2, tmpDest, mask 10878 // and tmp3, tmp, mask 10879 // or tmp4, tmp3, tmp2 10880 // stwcx. tmp4, ptr 10881 // bne- loopMBB 10882 // fallthrough --> exitMBB 10883 // srw dest, tmpDest, shift 10884 if (ptrA != ZeroReg) { 10885 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10886 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10887 .addReg(ptrA) 10888 .addReg(ptrB); 10889 } else { 10890 Ptr1Reg = ptrB; 10891 } 10892 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10893 // mode. 10894 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10895 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10896 .addImm(3) 10897 .addImm(27) 10898 .addImm(is8bit ? 28 : 27); 10899 if (!isLittleEndian) 10900 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10901 .addReg(Shift1Reg) 10902 .addImm(is8bit ? 24 : 16); 10903 if (is64bit) 10904 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10905 .addReg(Ptr1Reg) 10906 .addImm(0) 10907 .addImm(61); 10908 else 10909 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10910 .addReg(Ptr1Reg) 10911 .addImm(0) 10912 .addImm(0) 10913 .addImm(29); 10914 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10915 if (is8bit) 10916 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10917 else { 10918 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10919 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10920 .addReg(Mask3Reg) 10921 .addImm(65535); 10922 } 10923 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10924 .addReg(Mask2Reg) 10925 .addReg(ShiftReg); 10926 10927 BB = loopMBB; 10928 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10929 .addReg(ZeroReg) 10930 .addReg(PtrReg); 10931 if (BinOpcode) 10932 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10933 .addReg(Incr2Reg) 10934 .addReg(TmpDestReg); 10935 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10936 .addReg(TmpDestReg) 10937 .addReg(MaskReg); 10938 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10939 if (CmpOpcode) { 10940 // For unsigned comparisons, we can directly compare the shifted values. 10941 // For signed comparisons we shift and sign extend. 10942 Register SReg = RegInfo.createVirtualRegister(GPRC); 10943 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10944 .addReg(TmpDestReg) 10945 .addReg(MaskReg); 10946 unsigned ValueReg = SReg; 10947 unsigned CmpReg = Incr2Reg; 10948 if (CmpOpcode == PPC::CMPW) { 10949 ValueReg = RegInfo.createVirtualRegister(GPRC); 10950 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10951 .addReg(SReg) 10952 .addReg(ShiftReg); 10953 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10954 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10955 .addReg(ValueReg); 10956 ValueReg = ValueSReg; 10957 CmpReg = incr; 10958 } 10959 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10960 .addReg(CmpReg) 10961 .addReg(ValueReg); 10962 BuildMI(BB, dl, TII->get(PPC::BCC)) 10963 .addImm(CmpPred) 10964 .addReg(PPC::CR0) 10965 .addMBB(exitMBB); 10966 BB->addSuccessor(loop2MBB); 10967 BB->addSuccessor(exitMBB); 10968 BB = loop2MBB; 10969 } 10970 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10971 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10972 .addReg(Tmp4Reg) 10973 .addReg(ZeroReg) 10974 .addReg(PtrReg); 10975 BuildMI(BB, dl, TII->get(PPC::BCC)) 10976 .addImm(PPC::PRED_NE) 10977 .addReg(PPC::CR0) 10978 .addMBB(loopMBB); 10979 BB->addSuccessor(loopMBB); 10980 BB->addSuccessor(exitMBB); 10981 10982 // exitMBB: 10983 // ... 10984 BB = exitMBB; 10985 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10986 .addReg(TmpDestReg) 10987 .addReg(ShiftReg); 10988 return BB; 10989 } 10990 10991 llvm::MachineBasicBlock * 10992 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10993 MachineBasicBlock *MBB) const { 10994 DebugLoc DL = MI.getDebugLoc(); 10995 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10996 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10997 10998 MachineFunction *MF = MBB->getParent(); 10999 MachineRegisterInfo &MRI = MF->getRegInfo(); 11000 11001 const BasicBlock *BB = MBB->getBasicBlock(); 11002 MachineFunction::iterator I = ++MBB->getIterator(); 11003 11004 Register DstReg = MI.getOperand(0).getReg(); 11005 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11006 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11007 Register mainDstReg = MRI.createVirtualRegister(RC); 11008 Register restoreDstReg = MRI.createVirtualRegister(RC); 11009 11010 MVT PVT = getPointerTy(MF->getDataLayout()); 11011 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11012 "Invalid Pointer Size!"); 11013 // For v = setjmp(buf), we generate 11014 // 11015 // thisMBB: 11016 // SjLjSetup mainMBB 11017 // bl mainMBB 11018 // v_restore = 1 11019 // b sinkMBB 11020 // 11021 // mainMBB: 11022 // buf[LabelOffset] = LR 11023 // v_main = 0 11024 // 11025 // sinkMBB: 11026 // v = phi(main, restore) 11027 // 11028 11029 MachineBasicBlock *thisMBB = MBB; 11030 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11031 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11032 MF->insert(I, mainMBB); 11033 MF->insert(I, sinkMBB); 11034 11035 MachineInstrBuilder MIB; 11036 11037 // Transfer the remainder of BB and its successor edges to sinkMBB. 11038 sinkMBB->splice(sinkMBB->begin(), MBB, 11039 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11040 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11041 11042 // Note that the structure of the jmp_buf used here is not compatible 11043 // with that used by libc, and is not designed to be. Specifically, it 11044 // stores only those 'reserved' registers that LLVM does not otherwise 11045 // understand how to spill. Also, by convention, by the time this 11046 // intrinsic is called, Clang has already stored the frame address in the 11047 // first slot of the buffer and stack address in the third. Following the 11048 // X86 target code, we'll store the jump address in the second slot. We also 11049 // need to save the TOC pointer (R2) to handle jumps between shared 11050 // libraries, and that will be stored in the fourth slot. The thread 11051 // identifier (R13) is not affected. 11052 11053 // thisMBB: 11054 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11055 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11056 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11057 11058 // Prepare IP either in reg. 11059 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11060 Register LabelReg = MRI.createVirtualRegister(PtrRC); 11061 Register BufReg = MI.getOperand(1).getReg(); 11062 11063 if (Subtarget.is64BitELFABI()) { 11064 setUsesTOCBasePtr(*MBB->getParent()); 11065 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 11066 .addReg(PPC::X2) 11067 .addImm(TOCOffset) 11068 .addReg(BufReg) 11069 .cloneMemRefs(MI); 11070 } 11071 11072 // Naked functions never have a base pointer, and so we use r1. For all 11073 // other functions, this decision must be delayed until during PEI. 11074 unsigned BaseReg; 11075 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11076 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11077 else 11078 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11079 11080 MIB = BuildMI(*thisMBB, MI, DL, 11081 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11082 .addReg(BaseReg) 11083 .addImm(BPOffset) 11084 .addReg(BufReg) 11085 .cloneMemRefs(MI); 11086 11087 // Setup 11088 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11089 MIB.addRegMask(TRI->getNoPreservedMask()); 11090 11091 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11092 11093 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11094 .addMBB(mainMBB); 11095 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11096 11097 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11098 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11099 11100 // mainMBB: 11101 // mainDstReg = 0 11102 MIB = 11103 BuildMI(mainMBB, DL, 11104 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11105 11106 // Store IP 11107 if (Subtarget.isPPC64()) { 11108 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11109 .addReg(LabelReg) 11110 .addImm(LabelOffset) 11111 .addReg(BufReg); 11112 } else { 11113 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11114 .addReg(LabelReg) 11115 .addImm(LabelOffset) 11116 .addReg(BufReg); 11117 } 11118 MIB.cloneMemRefs(MI); 11119 11120 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11121 mainMBB->addSuccessor(sinkMBB); 11122 11123 // sinkMBB: 11124 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11125 TII->get(PPC::PHI), DstReg) 11126 .addReg(mainDstReg).addMBB(mainMBB) 11127 .addReg(restoreDstReg).addMBB(thisMBB); 11128 11129 MI.eraseFromParent(); 11130 return sinkMBB; 11131 } 11132 11133 MachineBasicBlock * 11134 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11135 MachineBasicBlock *MBB) const { 11136 DebugLoc DL = MI.getDebugLoc(); 11137 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11138 11139 MachineFunction *MF = MBB->getParent(); 11140 MachineRegisterInfo &MRI = MF->getRegInfo(); 11141 11142 MVT PVT = getPointerTy(MF->getDataLayout()); 11143 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11144 "Invalid Pointer Size!"); 11145 11146 const TargetRegisterClass *RC = 11147 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11148 Register Tmp = MRI.createVirtualRegister(RC); 11149 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11150 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11151 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11152 unsigned BP = 11153 (PVT == MVT::i64) 11154 ? PPC::X30 11155 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11156 : PPC::R30); 11157 11158 MachineInstrBuilder MIB; 11159 11160 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11161 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11162 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11163 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11164 11165 Register BufReg = MI.getOperand(0).getReg(); 11166 11167 // Reload FP (the jumped-to function may not have had a 11168 // frame pointer, and if so, then its r31 will be restored 11169 // as necessary). 11170 if (PVT == MVT::i64) { 11171 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11172 .addImm(0) 11173 .addReg(BufReg); 11174 } else { 11175 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11176 .addImm(0) 11177 .addReg(BufReg); 11178 } 11179 MIB.cloneMemRefs(MI); 11180 11181 // Reload IP 11182 if (PVT == MVT::i64) { 11183 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11184 .addImm(LabelOffset) 11185 .addReg(BufReg); 11186 } else { 11187 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11188 .addImm(LabelOffset) 11189 .addReg(BufReg); 11190 } 11191 MIB.cloneMemRefs(MI); 11192 11193 // Reload SP 11194 if (PVT == MVT::i64) { 11195 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11196 .addImm(SPOffset) 11197 .addReg(BufReg); 11198 } else { 11199 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11200 .addImm(SPOffset) 11201 .addReg(BufReg); 11202 } 11203 MIB.cloneMemRefs(MI); 11204 11205 // Reload BP 11206 if (PVT == MVT::i64) { 11207 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11208 .addImm(BPOffset) 11209 .addReg(BufReg); 11210 } else { 11211 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11212 .addImm(BPOffset) 11213 .addReg(BufReg); 11214 } 11215 MIB.cloneMemRefs(MI); 11216 11217 // Reload TOC 11218 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11219 setUsesTOCBasePtr(*MBB->getParent()); 11220 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11221 .addImm(TOCOffset) 11222 .addReg(BufReg) 11223 .cloneMemRefs(MI); 11224 } 11225 11226 // Jump 11227 BuildMI(*MBB, MI, DL, 11228 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11229 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11230 11231 MI.eraseFromParent(); 11232 return MBB; 11233 } 11234 11235 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const { 11236 // If the function specifically requests inline stack probes, emit them. 11237 if (MF.getFunction().hasFnAttribute("probe-stack")) 11238 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 11239 "inline-asm"; 11240 return false; 11241 } 11242 11243 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const { 11244 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 11245 unsigned StackAlign = TFI->getStackAlignment(); 11246 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 11247 "Unexpected stack alignment"); 11248 // The default stack probe size is 4096 if the function has no 11249 // stack-probe-size attribute. 11250 unsigned StackProbeSize = 4096; 11251 const Function &Fn = MF.getFunction(); 11252 if (Fn.hasFnAttribute("stack-probe-size")) 11253 Fn.getFnAttribute("stack-probe-size") 11254 .getValueAsString() 11255 .getAsInteger(0, StackProbeSize); 11256 // Round down to the stack alignment. 11257 StackProbeSize &= ~(StackAlign - 1); 11258 return StackProbeSize ? StackProbeSize : StackAlign; 11259 } 11260 11261 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 11262 // into three phases. In the first phase, it uses pseudo instruction 11263 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 11264 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 11265 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 11266 // MaxCallFrameSize so that it can calculate correct data area pointer. 11267 MachineBasicBlock * 11268 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 11269 MachineBasicBlock *MBB) const { 11270 const bool isPPC64 = Subtarget.isPPC64(); 11271 MachineFunction *MF = MBB->getParent(); 11272 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11273 DebugLoc DL = MI.getDebugLoc(); 11274 const unsigned ProbeSize = getStackProbeSize(*MF); 11275 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 11276 MachineRegisterInfo &MRI = MF->getRegInfo(); 11277 // The CFG of probing stack looks as 11278 // +-----+ 11279 // | MBB | 11280 // +--+--+ 11281 // | 11282 // +----v----+ 11283 // +--->+ TestMBB +---+ 11284 // | +----+----+ | 11285 // | | | 11286 // | +-----v----+ | 11287 // +---+ BlockMBB | | 11288 // +----------+ | 11289 // | 11290 // +---------+ | 11291 // | TailMBB +<--+ 11292 // +---------+ 11293 // In MBB, calculate previous frame pointer and final stack pointer. 11294 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 11295 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 11296 // TailMBB is spliced via \p MI. 11297 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 11298 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 11299 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 11300 11301 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 11302 MF->insert(MBBIter, TestMBB); 11303 MF->insert(MBBIter, BlockMBB); 11304 MF->insert(MBBIter, TailMBB); 11305 11306 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 11307 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11308 11309 Register DstReg = MI.getOperand(0).getReg(); 11310 Register NegSizeReg = MI.getOperand(1).getReg(); 11311 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 11312 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11313 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11314 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11315 11316 // Since value of NegSizeReg might be realigned in prologepilog, insert a 11317 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 11318 // NegSize. 11319 unsigned ProbeOpc; 11320 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 11321 ProbeOpc = 11322 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 11323 else 11324 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 11325 // and NegSizeReg will be allocated in the same phyreg to avoid 11326 // redundant copy when NegSizeReg has only one use which is current MI and 11327 // will be replaced by PREPARE_PROBED_ALLOCA then. 11328 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 11329 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 11330 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 11331 .addDef(ActualNegSizeReg) 11332 .addReg(NegSizeReg) 11333 .add(MI.getOperand(2)) 11334 .add(MI.getOperand(3)); 11335 11336 // Calculate final stack pointer, which equals to SP + ActualNegSize. 11337 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 11338 FinalStackPtr) 11339 .addReg(SPReg) 11340 .addReg(ActualNegSizeReg); 11341 11342 // Materialize a scratch register for update. 11343 int64_t NegProbeSize = -(int64_t)ProbeSize; 11344 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 11345 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11346 if (!isInt<16>(NegProbeSize)) { 11347 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11348 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 11349 .addImm(NegProbeSize >> 16); 11350 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 11351 ScratchReg) 11352 .addReg(TempReg) 11353 .addImm(NegProbeSize & 0xFFFF); 11354 } else 11355 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 11356 .addImm(NegProbeSize); 11357 11358 { 11359 // Probing leading residual part. 11360 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11361 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 11362 .addReg(ActualNegSizeReg) 11363 .addReg(ScratchReg); 11364 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11365 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 11366 .addReg(Div) 11367 .addReg(ScratchReg); 11368 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11369 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 11370 .addReg(Mul) 11371 .addReg(ActualNegSizeReg); 11372 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11373 .addReg(FramePointer) 11374 .addReg(SPReg) 11375 .addReg(NegMod); 11376 } 11377 11378 { 11379 // Remaining part should be multiple of ProbeSize. 11380 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 11381 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 11382 .addReg(SPReg) 11383 .addReg(FinalStackPtr); 11384 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 11385 .addImm(PPC::PRED_EQ) 11386 .addReg(CmpResult) 11387 .addMBB(TailMBB); 11388 TestMBB->addSuccessor(BlockMBB); 11389 TestMBB->addSuccessor(TailMBB); 11390 } 11391 11392 { 11393 // Touch the block. 11394 // |P...|P...|P... 11395 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 11396 .addReg(FramePointer) 11397 .addReg(SPReg) 11398 .addReg(ScratchReg); 11399 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 11400 BlockMBB->addSuccessor(TestMBB); 11401 } 11402 11403 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 11404 // DYNAREAOFFSET pseudo instruction to get the future result. 11405 Register MaxCallFrameSizeReg = 11406 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 11407 BuildMI(TailMBB, DL, 11408 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 11409 MaxCallFrameSizeReg) 11410 .add(MI.getOperand(2)) 11411 .add(MI.getOperand(3)); 11412 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 11413 .addReg(SPReg) 11414 .addReg(MaxCallFrameSizeReg); 11415 11416 // Splice instructions after MI to TailMBB. 11417 TailMBB->splice(TailMBB->end(), MBB, 11418 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11419 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 11420 MBB->addSuccessor(TestMBB); 11421 11422 // Delete the pseudo instruction. 11423 MI.eraseFromParent(); 11424 11425 ++NumDynamicAllocaProbed; 11426 return TailMBB; 11427 } 11428 11429 MachineBasicBlock * 11430 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11431 MachineBasicBlock *BB) const { 11432 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11433 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11434 if (Subtarget.is64BitELFABI() && 11435 MI.getOpcode() == TargetOpcode::PATCHPOINT && 11436 !Subtarget.isUsingPCRelativeCalls()) { 11437 // Call lowering should have added an r2 operand to indicate a dependence 11438 // on the TOC base pointer value. It can't however, because there is no 11439 // way to mark the dependence as implicit there, and so the stackmap code 11440 // will confuse it with a regular operand. Instead, add the dependence 11441 // here. 11442 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11443 } 11444 11445 return emitPatchPoint(MI, BB); 11446 } 11447 11448 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11449 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11450 return emitEHSjLjSetJmp(MI, BB); 11451 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11452 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11453 return emitEHSjLjLongJmp(MI, BB); 11454 } 11455 11456 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11457 11458 // To "insert" these instructions we actually have to insert their 11459 // control-flow patterns. 11460 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11461 MachineFunction::iterator It = ++BB->getIterator(); 11462 11463 MachineFunction *F = BB->getParent(); 11464 11465 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11466 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11467 MI.getOpcode() == PPC::SELECT_I8) { 11468 SmallVector<MachineOperand, 2> Cond; 11469 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11470 MI.getOpcode() == PPC::SELECT_CC_I8) 11471 Cond.push_back(MI.getOperand(4)); 11472 else 11473 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11474 Cond.push_back(MI.getOperand(1)); 11475 11476 DebugLoc dl = MI.getDebugLoc(); 11477 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11478 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11479 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11480 MI.getOpcode() == PPC::SELECT_CC_F8 || 11481 MI.getOpcode() == PPC::SELECT_CC_F16 || 11482 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11483 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11484 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11485 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11486 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11487 MI.getOpcode() == PPC::SELECT_CC_SPE || 11488 MI.getOpcode() == PPC::SELECT_F4 || 11489 MI.getOpcode() == PPC::SELECT_F8 || 11490 MI.getOpcode() == PPC::SELECT_F16 || 11491 MI.getOpcode() == PPC::SELECT_SPE || 11492 MI.getOpcode() == PPC::SELECT_SPE4 || 11493 MI.getOpcode() == PPC::SELECT_VRRC || 11494 MI.getOpcode() == PPC::SELECT_VSFRC || 11495 MI.getOpcode() == PPC::SELECT_VSSRC || 11496 MI.getOpcode() == PPC::SELECT_VSRC) { 11497 // The incoming instruction knows the destination vreg to set, the 11498 // condition code register to branch on, the true/false values to 11499 // select between, and a branch opcode to use. 11500 11501 // thisMBB: 11502 // ... 11503 // TrueVal = ... 11504 // cmpTY ccX, r1, r2 11505 // bCC copy1MBB 11506 // fallthrough --> copy0MBB 11507 MachineBasicBlock *thisMBB = BB; 11508 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11509 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11510 DebugLoc dl = MI.getDebugLoc(); 11511 F->insert(It, copy0MBB); 11512 F->insert(It, sinkMBB); 11513 11514 // Transfer the remainder of BB and its successor edges to sinkMBB. 11515 sinkMBB->splice(sinkMBB->begin(), BB, 11516 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11517 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11518 11519 // Next, add the true and fallthrough blocks as its successors. 11520 BB->addSuccessor(copy0MBB); 11521 BB->addSuccessor(sinkMBB); 11522 11523 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11524 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11525 MI.getOpcode() == PPC::SELECT_F16 || 11526 MI.getOpcode() == PPC::SELECT_SPE4 || 11527 MI.getOpcode() == PPC::SELECT_SPE || 11528 MI.getOpcode() == PPC::SELECT_VRRC || 11529 MI.getOpcode() == PPC::SELECT_VSFRC || 11530 MI.getOpcode() == PPC::SELECT_VSSRC || 11531 MI.getOpcode() == PPC::SELECT_VSRC) { 11532 BuildMI(BB, dl, TII->get(PPC::BC)) 11533 .addReg(MI.getOperand(1).getReg()) 11534 .addMBB(sinkMBB); 11535 } else { 11536 unsigned SelectPred = MI.getOperand(4).getImm(); 11537 BuildMI(BB, dl, TII->get(PPC::BCC)) 11538 .addImm(SelectPred) 11539 .addReg(MI.getOperand(1).getReg()) 11540 .addMBB(sinkMBB); 11541 } 11542 11543 // copy0MBB: 11544 // %FalseValue = ... 11545 // # fallthrough to sinkMBB 11546 BB = copy0MBB; 11547 11548 // Update machine-CFG edges 11549 BB->addSuccessor(sinkMBB); 11550 11551 // sinkMBB: 11552 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11553 // ... 11554 BB = sinkMBB; 11555 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11556 .addReg(MI.getOperand(3).getReg()) 11557 .addMBB(copy0MBB) 11558 .addReg(MI.getOperand(2).getReg()) 11559 .addMBB(thisMBB); 11560 } else if (MI.getOpcode() == PPC::ReadTB) { 11561 // To read the 64-bit time-base register on a 32-bit target, we read the 11562 // two halves. Should the counter have wrapped while it was being read, we 11563 // need to try again. 11564 // ... 11565 // readLoop: 11566 // mfspr Rx,TBU # load from TBU 11567 // mfspr Ry,TB # load from TB 11568 // mfspr Rz,TBU # load from TBU 11569 // cmpw crX,Rx,Rz # check if 'old'='new' 11570 // bne readLoop # branch if they're not equal 11571 // ... 11572 11573 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11574 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11575 DebugLoc dl = MI.getDebugLoc(); 11576 F->insert(It, readMBB); 11577 F->insert(It, sinkMBB); 11578 11579 // Transfer the remainder of BB and its successor edges to sinkMBB. 11580 sinkMBB->splice(sinkMBB->begin(), BB, 11581 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11582 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11583 11584 BB->addSuccessor(readMBB); 11585 BB = readMBB; 11586 11587 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11588 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11589 Register LoReg = MI.getOperand(0).getReg(); 11590 Register HiReg = MI.getOperand(1).getReg(); 11591 11592 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11593 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11594 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11595 11596 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11597 11598 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11599 .addReg(HiReg) 11600 .addReg(ReadAgainReg); 11601 BuildMI(BB, dl, TII->get(PPC::BCC)) 11602 .addImm(PPC::PRED_NE) 11603 .addReg(CmpReg) 11604 .addMBB(readMBB); 11605 11606 BB->addSuccessor(readMBB); 11607 BB->addSuccessor(sinkMBB); 11608 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11609 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11610 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11611 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11612 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11613 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11614 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11615 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11616 11617 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11618 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11619 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11620 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11621 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11622 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11624 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11625 11626 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11627 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11628 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11629 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11630 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11631 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11632 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11633 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11634 11635 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11636 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11637 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11638 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11639 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11640 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11641 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11642 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11643 11644 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11645 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11646 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11647 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11648 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11649 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11650 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11651 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11652 11653 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11654 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11655 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11656 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11657 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11658 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11659 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11660 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11661 11662 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11663 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11664 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11665 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11666 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11667 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11668 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11669 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11670 11671 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11672 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11673 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11674 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11675 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11676 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11677 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11678 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11679 11680 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11681 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11682 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11683 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11684 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11685 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11686 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11687 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11688 11689 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11690 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11691 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11692 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11693 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11694 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11695 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11696 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11697 11698 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11699 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11700 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11701 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11702 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11703 BB = EmitAtomicBinary(MI, BB, 4, 0); 11704 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11705 BB = EmitAtomicBinary(MI, BB, 8, 0); 11706 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11707 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11708 (Subtarget.hasPartwordAtomics() && 11709 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11710 (Subtarget.hasPartwordAtomics() && 11711 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11712 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11713 11714 auto LoadMnemonic = PPC::LDARX; 11715 auto StoreMnemonic = PPC::STDCX; 11716 switch (MI.getOpcode()) { 11717 default: 11718 llvm_unreachable("Compare and swap of unknown size"); 11719 case PPC::ATOMIC_CMP_SWAP_I8: 11720 LoadMnemonic = PPC::LBARX; 11721 StoreMnemonic = PPC::STBCX; 11722 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11723 break; 11724 case PPC::ATOMIC_CMP_SWAP_I16: 11725 LoadMnemonic = PPC::LHARX; 11726 StoreMnemonic = PPC::STHCX; 11727 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11728 break; 11729 case PPC::ATOMIC_CMP_SWAP_I32: 11730 LoadMnemonic = PPC::LWARX; 11731 StoreMnemonic = PPC::STWCX; 11732 break; 11733 case PPC::ATOMIC_CMP_SWAP_I64: 11734 LoadMnemonic = PPC::LDARX; 11735 StoreMnemonic = PPC::STDCX; 11736 break; 11737 } 11738 Register dest = MI.getOperand(0).getReg(); 11739 Register ptrA = MI.getOperand(1).getReg(); 11740 Register ptrB = MI.getOperand(2).getReg(); 11741 Register oldval = MI.getOperand(3).getReg(); 11742 Register newval = MI.getOperand(4).getReg(); 11743 DebugLoc dl = MI.getDebugLoc(); 11744 11745 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11746 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11747 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11748 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11749 F->insert(It, loop1MBB); 11750 F->insert(It, loop2MBB); 11751 F->insert(It, midMBB); 11752 F->insert(It, exitMBB); 11753 exitMBB->splice(exitMBB->begin(), BB, 11754 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11755 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11756 11757 // thisMBB: 11758 // ... 11759 // fallthrough --> loopMBB 11760 BB->addSuccessor(loop1MBB); 11761 11762 // loop1MBB: 11763 // l[bhwd]arx dest, ptr 11764 // cmp[wd] dest, oldval 11765 // bne- midMBB 11766 // loop2MBB: 11767 // st[bhwd]cx. newval, ptr 11768 // bne- loopMBB 11769 // b exitBB 11770 // midMBB: 11771 // st[bhwd]cx. dest, ptr 11772 // exitBB: 11773 BB = loop1MBB; 11774 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11775 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11776 .addReg(oldval) 11777 .addReg(dest); 11778 BuildMI(BB, dl, TII->get(PPC::BCC)) 11779 .addImm(PPC::PRED_NE) 11780 .addReg(PPC::CR0) 11781 .addMBB(midMBB); 11782 BB->addSuccessor(loop2MBB); 11783 BB->addSuccessor(midMBB); 11784 11785 BB = loop2MBB; 11786 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11787 .addReg(newval) 11788 .addReg(ptrA) 11789 .addReg(ptrB); 11790 BuildMI(BB, dl, TII->get(PPC::BCC)) 11791 .addImm(PPC::PRED_NE) 11792 .addReg(PPC::CR0) 11793 .addMBB(loop1MBB); 11794 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11795 BB->addSuccessor(loop1MBB); 11796 BB->addSuccessor(exitMBB); 11797 11798 BB = midMBB; 11799 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11800 .addReg(dest) 11801 .addReg(ptrA) 11802 .addReg(ptrB); 11803 BB->addSuccessor(exitMBB); 11804 11805 // exitMBB: 11806 // ... 11807 BB = exitMBB; 11808 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11809 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11810 // We must use 64-bit registers for addresses when targeting 64-bit, 11811 // since we're actually doing arithmetic on them. Other registers 11812 // can be 32-bit. 11813 bool is64bit = Subtarget.isPPC64(); 11814 bool isLittleEndian = Subtarget.isLittleEndian(); 11815 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11816 11817 Register dest = MI.getOperand(0).getReg(); 11818 Register ptrA = MI.getOperand(1).getReg(); 11819 Register ptrB = MI.getOperand(2).getReg(); 11820 Register oldval = MI.getOperand(3).getReg(); 11821 Register newval = MI.getOperand(4).getReg(); 11822 DebugLoc dl = MI.getDebugLoc(); 11823 11824 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11825 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11826 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11827 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11828 F->insert(It, loop1MBB); 11829 F->insert(It, loop2MBB); 11830 F->insert(It, midMBB); 11831 F->insert(It, exitMBB); 11832 exitMBB->splice(exitMBB->begin(), BB, 11833 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11834 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11835 11836 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11837 const TargetRegisterClass *RC = 11838 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11839 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11840 11841 Register PtrReg = RegInfo.createVirtualRegister(RC); 11842 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11843 Register ShiftReg = 11844 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11845 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11846 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11847 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11848 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11849 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11850 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11851 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11852 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11853 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11854 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11855 Register Ptr1Reg; 11856 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11857 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11858 // thisMBB: 11859 // ... 11860 // fallthrough --> loopMBB 11861 BB->addSuccessor(loop1MBB); 11862 11863 // The 4-byte load must be aligned, while a char or short may be 11864 // anywhere in the word. Hence all this nasty bookkeeping code. 11865 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11866 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11867 // xori shift, shift1, 24 [16] 11868 // rlwinm ptr, ptr1, 0, 0, 29 11869 // slw newval2, newval, shift 11870 // slw oldval2, oldval,shift 11871 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11872 // slw mask, mask2, shift 11873 // and newval3, newval2, mask 11874 // and oldval3, oldval2, mask 11875 // loop1MBB: 11876 // lwarx tmpDest, ptr 11877 // and tmp, tmpDest, mask 11878 // cmpw tmp, oldval3 11879 // bne- midMBB 11880 // loop2MBB: 11881 // andc tmp2, tmpDest, mask 11882 // or tmp4, tmp2, newval3 11883 // stwcx. tmp4, ptr 11884 // bne- loop1MBB 11885 // b exitBB 11886 // midMBB: 11887 // stwcx. tmpDest, ptr 11888 // exitBB: 11889 // srw dest, tmpDest, shift 11890 if (ptrA != ZeroReg) { 11891 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11892 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11893 .addReg(ptrA) 11894 .addReg(ptrB); 11895 } else { 11896 Ptr1Reg = ptrB; 11897 } 11898 11899 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11900 // mode. 11901 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11902 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11903 .addImm(3) 11904 .addImm(27) 11905 .addImm(is8bit ? 28 : 27); 11906 if (!isLittleEndian) 11907 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11908 .addReg(Shift1Reg) 11909 .addImm(is8bit ? 24 : 16); 11910 if (is64bit) 11911 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11912 .addReg(Ptr1Reg) 11913 .addImm(0) 11914 .addImm(61); 11915 else 11916 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11917 .addReg(Ptr1Reg) 11918 .addImm(0) 11919 .addImm(0) 11920 .addImm(29); 11921 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11922 .addReg(newval) 11923 .addReg(ShiftReg); 11924 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11925 .addReg(oldval) 11926 .addReg(ShiftReg); 11927 if (is8bit) 11928 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11929 else { 11930 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11931 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11932 .addReg(Mask3Reg) 11933 .addImm(65535); 11934 } 11935 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11936 .addReg(Mask2Reg) 11937 .addReg(ShiftReg); 11938 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11939 .addReg(NewVal2Reg) 11940 .addReg(MaskReg); 11941 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11942 .addReg(OldVal2Reg) 11943 .addReg(MaskReg); 11944 11945 BB = loop1MBB; 11946 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11947 .addReg(ZeroReg) 11948 .addReg(PtrReg); 11949 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11950 .addReg(TmpDestReg) 11951 .addReg(MaskReg); 11952 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11953 .addReg(TmpReg) 11954 .addReg(OldVal3Reg); 11955 BuildMI(BB, dl, TII->get(PPC::BCC)) 11956 .addImm(PPC::PRED_NE) 11957 .addReg(PPC::CR0) 11958 .addMBB(midMBB); 11959 BB->addSuccessor(loop2MBB); 11960 BB->addSuccessor(midMBB); 11961 11962 BB = loop2MBB; 11963 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11964 .addReg(TmpDestReg) 11965 .addReg(MaskReg); 11966 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11967 .addReg(Tmp2Reg) 11968 .addReg(NewVal3Reg); 11969 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11970 .addReg(Tmp4Reg) 11971 .addReg(ZeroReg) 11972 .addReg(PtrReg); 11973 BuildMI(BB, dl, TII->get(PPC::BCC)) 11974 .addImm(PPC::PRED_NE) 11975 .addReg(PPC::CR0) 11976 .addMBB(loop1MBB); 11977 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11978 BB->addSuccessor(loop1MBB); 11979 BB->addSuccessor(exitMBB); 11980 11981 BB = midMBB; 11982 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11983 .addReg(TmpDestReg) 11984 .addReg(ZeroReg) 11985 .addReg(PtrReg); 11986 BB->addSuccessor(exitMBB); 11987 11988 // exitMBB: 11989 // ... 11990 BB = exitMBB; 11991 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11992 .addReg(TmpReg) 11993 .addReg(ShiftReg); 11994 } else if (MI.getOpcode() == PPC::FADDrtz) { 11995 // This pseudo performs an FADD with rounding mode temporarily forced 11996 // to round-to-zero. We emit this via custom inserter since the FPSCR 11997 // is not modeled at the SelectionDAG level. 11998 Register Dest = MI.getOperand(0).getReg(); 11999 Register Src1 = MI.getOperand(1).getReg(); 12000 Register Src2 = MI.getOperand(2).getReg(); 12001 DebugLoc dl = MI.getDebugLoc(); 12002 12003 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12004 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12005 12006 // Save FPSCR value. 12007 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12008 12009 // Set rounding mode to round-to-zero. 12010 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12011 .addImm(31) 12012 .addReg(PPC::RM, RegState::ImplicitDefine); 12013 12014 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12015 .addImm(30) 12016 .addReg(PPC::RM, RegState::ImplicitDefine); 12017 12018 // Perform addition. 12019 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 12020 12021 // Restore FPSCR value. 12022 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12023 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12024 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12025 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12026 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12027 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12028 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12029 ? PPC::ANDI8_rec 12030 : PPC::ANDI_rec; 12031 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12032 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12033 12034 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12035 Register Dest = RegInfo.createVirtualRegister( 12036 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12037 12038 DebugLoc Dl = MI.getDebugLoc(); 12039 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12040 .addReg(MI.getOperand(1).getReg()) 12041 .addImm(1); 12042 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12043 MI.getOperand(0).getReg()) 12044 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12045 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12046 DebugLoc Dl = MI.getDebugLoc(); 12047 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12048 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12049 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12050 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12051 MI.getOperand(0).getReg()) 12052 .addReg(CRReg); 12053 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12054 DebugLoc Dl = MI.getDebugLoc(); 12055 unsigned Imm = MI.getOperand(1).getImm(); 12056 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12057 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12058 MI.getOperand(0).getReg()) 12059 .addReg(PPC::CR0EQ); 12060 } else if (MI.getOpcode() == PPC::SETRNDi) { 12061 DebugLoc dl = MI.getDebugLoc(); 12062 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12063 12064 // Save FPSCR value. 12065 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12066 12067 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12068 // the following settings: 12069 // 00 Round to nearest 12070 // 01 Round to 0 12071 // 10 Round to +inf 12072 // 11 Round to -inf 12073 12074 // When the operand is immediate, using the two least significant bits of 12075 // the immediate to set the bits 62:63 of FPSCR. 12076 unsigned Mode = MI.getOperand(1).getImm(); 12077 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 12078 .addImm(31) 12079 .addReg(PPC::RM, RegState::ImplicitDefine); 12080 12081 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 12082 .addImm(30) 12083 .addReg(PPC::RM, RegState::ImplicitDefine); 12084 } else if (MI.getOpcode() == PPC::SETRND) { 12085 DebugLoc dl = MI.getDebugLoc(); 12086 12087 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 12088 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 12089 // If the target doesn't have DirectMove, we should use stack to do the 12090 // conversion, because the target doesn't have the instructions like mtvsrd 12091 // or mfvsrd to do this conversion directly. 12092 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 12093 if (Subtarget.hasDirectMove()) { 12094 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 12095 .addReg(SrcReg); 12096 } else { 12097 // Use stack to do the register copy. 12098 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 12099 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12100 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 12101 if (RC == &PPC::F8RCRegClass) { 12102 // Copy register from F8RCRegClass to G8RCRegclass. 12103 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 12104 "Unsupported RegClass."); 12105 12106 StoreOp = PPC::STFD; 12107 LoadOp = PPC::LD; 12108 } else { 12109 // Copy register from G8RCRegClass to F8RCRegclass. 12110 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 12111 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 12112 "Unsupported RegClass."); 12113 } 12114 12115 MachineFrameInfo &MFI = F->getFrameInfo(); 12116 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 12117 12118 MachineMemOperand *MMOStore = F->getMachineMemOperand( 12119 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12120 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 12121 MFI.getObjectAlign(FrameIdx)); 12122 12123 // Store the SrcReg into the stack. 12124 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 12125 .addReg(SrcReg) 12126 .addImm(0) 12127 .addFrameIndex(FrameIdx) 12128 .addMemOperand(MMOStore); 12129 12130 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 12131 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 12132 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 12133 MFI.getObjectAlign(FrameIdx)); 12134 12135 // Load from the stack where SrcReg is stored, and save to DestReg, 12136 // so we have done the RegClass conversion from RegClass::SrcReg to 12137 // RegClass::DestReg. 12138 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 12139 .addImm(0) 12140 .addFrameIndex(FrameIdx) 12141 .addMemOperand(MMOLoad); 12142 } 12143 }; 12144 12145 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12146 12147 // Save FPSCR value. 12148 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12149 12150 // When the operand is gprc register, use two least significant bits of the 12151 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 12152 // 12153 // copy OldFPSCRTmpReg, OldFPSCRReg 12154 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 12155 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 12156 // copy NewFPSCRReg, NewFPSCRTmpReg 12157 // mtfsf 255, NewFPSCRReg 12158 MachineOperand SrcOp = MI.getOperand(1); 12159 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12160 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12161 12162 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 12163 12164 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12165 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12166 12167 // The first operand of INSERT_SUBREG should be a register which has 12168 // subregisters, we only care about its RegClass, so we should use an 12169 // IMPLICIT_DEF register. 12170 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 12171 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 12172 .addReg(ImDefReg) 12173 .add(SrcOp) 12174 .addImm(1); 12175 12176 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 12177 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 12178 .addReg(OldFPSCRTmpReg) 12179 .addReg(ExtSrcReg) 12180 .addImm(0) 12181 .addImm(62); 12182 12183 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12184 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 12185 12186 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 12187 // bits of FPSCR. 12188 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 12189 .addImm(255) 12190 .addReg(NewFPSCRReg) 12191 .addImm(0) 12192 .addImm(0); 12193 } else if (MI.getOpcode() == PPC::SETFLM) { 12194 DebugLoc Dl = MI.getDebugLoc(); 12195 12196 // Result of setflm is previous FPSCR content, so we need to save it first. 12197 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12198 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 12199 12200 // Put bits in 32:63 to FPSCR. 12201 Register NewFPSCRReg = MI.getOperand(1).getReg(); 12202 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 12203 .addImm(255) 12204 .addReg(NewFPSCRReg) 12205 .addImm(0) 12206 .addImm(0); 12207 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 12208 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 12209 return emitProbedAlloca(MI, BB); 12210 } else { 12211 llvm_unreachable("Unexpected instr type to insert"); 12212 } 12213 12214 MI.eraseFromParent(); // The pseudo instruction is gone now. 12215 return BB; 12216 } 12217 12218 //===----------------------------------------------------------------------===// 12219 // Target Optimization Hooks 12220 //===----------------------------------------------------------------------===// 12221 12222 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 12223 // For the estimates, convergence is quadratic, so we essentially double the 12224 // number of digits correct after every iteration. For both FRE and FRSQRTE, 12225 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 12226 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 12227 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 12228 if (VT.getScalarType() == MVT::f64) 12229 RefinementSteps++; 12230 return RefinementSteps; 12231 } 12232 12233 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 12234 int Enabled, int &RefinementSteps, 12235 bool &UseOneConstNR, 12236 bool Reciprocal) const { 12237 EVT VT = Operand.getValueType(); 12238 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 12239 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 12240 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12241 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12242 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12243 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12244 12245 // The Newton-Raphson computation with a single constant does not provide 12246 // enough accuracy on some CPUs. 12247 UseOneConstNR = !Subtarget.needsTwoConstNR(); 12248 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 12249 } 12250 return SDValue(); 12251 } 12252 12253 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 12254 int Enabled, 12255 int &RefinementSteps) const { 12256 EVT VT = Operand.getValueType(); 12257 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 12258 (VT == MVT::f64 && Subtarget.hasFRE()) || 12259 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 12260 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 12261 if (RefinementSteps == ReciprocalEstimate::Unspecified) 12262 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 12263 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 12264 } 12265 return SDValue(); 12266 } 12267 12268 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 12269 // Note: This functionality is used only when unsafe-fp-math is enabled, and 12270 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 12271 // enabled for division), this functionality is redundant with the default 12272 // combiner logic (once the division -> reciprocal/multiply transformation 12273 // has taken place). As a result, this matters more for older cores than for 12274 // newer ones. 12275 12276 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 12277 // reciprocal if there are two or more FDIVs (for embedded cores with only 12278 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 12279 switch (Subtarget.getCPUDirective()) { 12280 default: 12281 return 3; 12282 case PPC::DIR_440: 12283 case PPC::DIR_A2: 12284 case PPC::DIR_E500: 12285 case PPC::DIR_E500mc: 12286 case PPC::DIR_E5500: 12287 return 2; 12288 } 12289 } 12290 12291 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12292 // collapsed, and so we need to look through chains of them. 12293 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12294 int64_t& Offset, SelectionDAG &DAG) { 12295 if (DAG.isBaseWithConstantOffset(Loc)) { 12296 Base = Loc.getOperand(0); 12297 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12298 12299 // The base might itself be a base plus an offset, and if so, accumulate 12300 // that as well. 12301 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12302 } 12303 } 12304 12305 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12306 unsigned Bytes, int Dist, 12307 SelectionDAG &DAG) { 12308 if (VT.getSizeInBits() / 8 != Bytes) 12309 return false; 12310 12311 SDValue BaseLoc = Base->getBasePtr(); 12312 if (Loc.getOpcode() == ISD::FrameIndex) { 12313 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12314 return false; 12315 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12316 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12317 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12318 int FS = MFI.getObjectSize(FI); 12319 int BFS = MFI.getObjectSize(BFI); 12320 if (FS != BFS || FS != (int)Bytes) return false; 12321 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12322 } 12323 12324 SDValue Base1 = Loc, Base2 = BaseLoc; 12325 int64_t Offset1 = 0, Offset2 = 0; 12326 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12327 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12328 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12329 return true; 12330 12331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12332 const GlobalValue *GV1 = nullptr; 12333 const GlobalValue *GV2 = nullptr; 12334 Offset1 = 0; 12335 Offset2 = 0; 12336 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12337 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12338 if (isGA1 && isGA2 && GV1 == GV2) 12339 return Offset1 == (Offset2 + Dist*Bytes); 12340 return false; 12341 } 12342 12343 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12344 // not enforce equality of the chain operands. 12345 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12346 unsigned Bytes, int Dist, 12347 SelectionDAG &DAG) { 12348 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12349 EVT VT = LS->getMemoryVT(); 12350 SDValue Loc = LS->getBasePtr(); 12351 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12352 } 12353 12354 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12355 EVT VT; 12356 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12357 default: return false; 12358 case Intrinsic::ppc_altivec_lvx: 12359 case Intrinsic::ppc_altivec_lvxl: 12360 case Intrinsic::ppc_vsx_lxvw4x: 12361 case Intrinsic::ppc_vsx_lxvw4x_be: 12362 VT = MVT::v4i32; 12363 break; 12364 case Intrinsic::ppc_vsx_lxvd2x: 12365 case Intrinsic::ppc_vsx_lxvd2x_be: 12366 VT = MVT::v2f64; 12367 break; 12368 case Intrinsic::ppc_altivec_lvebx: 12369 VT = MVT::i8; 12370 break; 12371 case Intrinsic::ppc_altivec_lvehx: 12372 VT = MVT::i16; 12373 break; 12374 case Intrinsic::ppc_altivec_lvewx: 12375 VT = MVT::i32; 12376 break; 12377 } 12378 12379 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12380 } 12381 12382 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12383 EVT VT; 12384 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12385 default: return false; 12386 case Intrinsic::ppc_altivec_stvx: 12387 case Intrinsic::ppc_altivec_stvxl: 12388 case Intrinsic::ppc_vsx_stxvw4x: 12389 VT = MVT::v4i32; 12390 break; 12391 case Intrinsic::ppc_vsx_stxvd2x: 12392 VT = MVT::v2f64; 12393 break; 12394 case Intrinsic::ppc_vsx_stxvw4x_be: 12395 VT = MVT::v4i32; 12396 break; 12397 case Intrinsic::ppc_vsx_stxvd2x_be: 12398 VT = MVT::v2f64; 12399 break; 12400 case Intrinsic::ppc_altivec_stvebx: 12401 VT = MVT::i8; 12402 break; 12403 case Intrinsic::ppc_altivec_stvehx: 12404 VT = MVT::i16; 12405 break; 12406 case Intrinsic::ppc_altivec_stvewx: 12407 VT = MVT::i32; 12408 break; 12409 } 12410 12411 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12412 } 12413 12414 return false; 12415 } 12416 12417 // Return true is there is a nearyby consecutive load to the one provided 12418 // (regardless of alignment). We search up and down the chain, looking though 12419 // token factors and other loads (but nothing else). As a result, a true result 12420 // indicates that it is safe to create a new consecutive load adjacent to the 12421 // load provided. 12422 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12423 SDValue Chain = LD->getChain(); 12424 EVT VT = LD->getMemoryVT(); 12425 12426 SmallSet<SDNode *, 16> LoadRoots; 12427 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12428 SmallSet<SDNode *, 16> Visited; 12429 12430 // First, search up the chain, branching to follow all token-factor operands. 12431 // If we find a consecutive load, then we're done, otherwise, record all 12432 // nodes just above the top-level loads and token factors. 12433 while (!Queue.empty()) { 12434 SDNode *ChainNext = Queue.pop_back_val(); 12435 if (!Visited.insert(ChainNext).second) 12436 continue; 12437 12438 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12439 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12440 return true; 12441 12442 if (!Visited.count(ChainLD->getChain().getNode())) 12443 Queue.push_back(ChainLD->getChain().getNode()); 12444 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12445 for (const SDUse &O : ChainNext->ops()) 12446 if (!Visited.count(O.getNode())) 12447 Queue.push_back(O.getNode()); 12448 } else 12449 LoadRoots.insert(ChainNext); 12450 } 12451 12452 // Second, search down the chain, starting from the top-level nodes recorded 12453 // in the first phase. These top-level nodes are the nodes just above all 12454 // loads and token factors. Starting with their uses, recursively look though 12455 // all loads (just the chain uses) and token factors to find a consecutive 12456 // load. 12457 Visited.clear(); 12458 Queue.clear(); 12459 12460 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12461 IE = LoadRoots.end(); I != IE; ++I) { 12462 Queue.push_back(*I); 12463 12464 while (!Queue.empty()) { 12465 SDNode *LoadRoot = Queue.pop_back_val(); 12466 if (!Visited.insert(LoadRoot).second) 12467 continue; 12468 12469 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12470 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12471 return true; 12472 12473 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12474 UE = LoadRoot->use_end(); UI != UE; ++UI) 12475 if (((isa<MemSDNode>(*UI) && 12476 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12477 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12478 Queue.push_back(*UI); 12479 } 12480 } 12481 12482 return false; 12483 } 12484 12485 /// This function is called when we have proved that a SETCC node can be replaced 12486 /// by subtraction (and other supporting instructions) so that the result of 12487 /// comparison is kept in a GPR instead of CR. This function is purely for 12488 /// codegen purposes and has some flags to guide the codegen process. 12489 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12490 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12491 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12492 12493 // Zero extend the operands to the largest legal integer. Originally, they 12494 // must be of a strictly smaller size. 12495 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12496 DAG.getConstant(Size, DL, MVT::i32)); 12497 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12498 DAG.getConstant(Size, DL, MVT::i32)); 12499 12500 // Swap if needed. Depends on the condition code. 12501 if (Swap) 12502 std::swap(Op0, Op1); 12503 12504 // Subtract extended integers. 12505 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12506 12507 // Move the sign bit to the least significant position and zero out the rest. 12508 // Now the least significant bit carries the result of original comparison. 12509 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12510 DAG.getConstant(Size - 1, DL, MVT::i32)); 12511 auto Final = Shifted; 12512 12513 // Complement the result if needed. Based on the condition code. 12514 if (Complement) 12515 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12516 DAG.getConstant(1, DL, MVT::i64)); 12517 12518 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12519 } 12520 12521 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12522 DAGCombinerInfo &DCI) const { 12523 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12524 12525 SelectionDAG &DAG = DCI.DAG; 12526 SDLoc DL(N); 12527 12528 // Size of integers being compared has a critical role in the following 12529 // analysis, so we prefer to do this when all types are legal. 12530 if (!DCI.isAfterLegalizeDAG()) 12531 return SDValue(); 12532 12533 // If all users of SETCC extend its value to a legal integer type 12534 // then we replace SETCC with a subtraction 12535 for (SDNode::use_iterator UI = N->use_begin(), 12536 UE = N->use_end(); UI != UE; ++UI) { 12537 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12538 return SDValue(); 12539 } 12540 12541 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12542 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12543 12544 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12545 12546 if (OpSize < Size) { 12547 switch (CC) { 12548 default: break; 12549 case ISD::SETULT: 12550 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12551 case ISD::SETULE: 12552 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12553 case ISD::SETUGT: 12554 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12555 case ISD::SETUGE: 12556 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12557 } 12558 } 12559 12560 return SDValue(); 12561 } 12562 12563 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12564 DAGCombinerInfo &DCI) const { 12565 SelectionDAG &DAG = DCI.DAG; 12566 SDLoc dl(N); 12567 12568 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12569 // If we're tracking CR bits, we need to be careful that we don't have: 12570 // trunc(binary-ops(zext(x), zext(y))) 12571 // or 12572 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12573 // such that we're unnecessarily moving things into GPRs when it would be 12574 // better to keep them in CR bits. 12575 12576 // Note that trunc here can be an actual i1 trunc, or can be the effective 12577 // truncation that comes from a setcc or select_cc. 12578 if (N->getOpcode() == ISD::TRUNCATE && 12579 N->getValueType(0) != MVT::i1) 12580 return SDValue(); 12581 12582 if (N->getOperand(0).getValueType() != MVT::i32 && 12583 N->getOperand(0).getValueType() != MVT::i64) 12584 return SDValue(); 12585 12586 if (N->getOpcode() == ISD::SETCC || 12587 N->getOpcode() == ISD::SELECT_CC) { 12588 // If we're looking at a comparison, then we need to make sure that the 12589 // high bits (all except for the first) don't matter the result. 12590 ISD::CondCode CC = 12591 cast<CondCodeSDNode>(N->getOperand( 12592 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12593 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12594 12595 if (ISD::isSignedIntSetCC(CC)) { 12596 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12597 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12598 return SDValue(); 12599 } else if (ISD::isUnsignedIntSetCC(CC)) { 12600 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12601 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12602 !DAG.MaskedValueIsZero(N->getOperand(1), 12603 APInt::getHighBitsSet(OpBits, OpBits-1))) 12604 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12605 : SDValue()); 12606 } else { 12607 // This is neither a signed nor an unsigned comparison, just make sure 12608 // that the high bits are equal. 12609 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12610 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12611 12612 // We don't really care about what is known about the first bit (if 12613 // anything), so clear it in all masks prior to comparing them. 12614 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12615 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12616 12617 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12618 return SDValue(); 12619 } 12620 } 12621 12622 // We now know that the higher-order bits are irrelevant, we just need to 12623 // make sure that all of the intermediate operations are bit operations, and 12624 // all inputs are extensions. 12625 if (N->getOperand(0).getOpcode() != ISD::AND && 12626 N->getOperand(0).getOpcode() != ISD::OR && 12627 N->getOperand(0).getOpcode() != ISD::XOR && 12628 N->getOperand(0).getOpcode() != ISD::SELECT && 12629 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12630 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12631 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12632 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12633 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12634 return SDValue(); 12635 12636 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12637 N->getOperand(1).getOpcode() != ISD::AND && 12638 N->getOperand(1).getOpcode() != ISD::OR && 12639 N->getOperand(1).getOpcode() != ISD::XOR && 12640 N->getOperand(1).getOpcode() != ISD::SELECT && 12641 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12642 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12643 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12644 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12645 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12646 return SDValue(); 12647 12648 SmallVector<SDValue, 4> Inputs; 12649 SmallVector<SDValue, 8> BinOps, PromOps; 12650 SmallPtrSet<SDNode *, 16> Visited; 12651 12652 for (unsigned i = 0; i < 2; ++i) { 12653 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12654 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12655 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12656 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12657 isa<ConstantSDNode>(N->getOperand(i))) 12658 Inputs.push_back(N->getOperand(i)); 12659 else 12660 BinOps.push_back(N->getOperand(i)); 12661 12662 if (N->getOpcode() == ISD::TRUNCATE) 12663 break; 12664 } 12665 12666 // Visit all inputs, collect all binary operations (and, or, xor and 12667 // select) that are all fed by extensions. 12668 while (!BinOps.empty()) { 12669 SDValue BinOp = BinOps.back(); 12670 BinOps.pop_back(); 12671 12672 if (!Visited.insert(BinOp.getNode()).second) 12673 continue; 12674 12675 PromOps.push_back(BinOp); 12676 12677 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12678 // The condition of the select is not promoted. 12679 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12680 continue; 12681 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12682 continue; 12683 12684 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12685 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12686 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12687 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12688 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12689 Inputs.push_back(BinOp.getOperand(i)); 12690 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12691 BinOp.getOperand(i).getOpcode() == ISD::OR || 12692 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12693 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12694 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12695 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12696 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12697 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12698 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12699 BinOps.push_back(BinOp.getOperand(i)); 12700 } else { 12701 // We have an input that is not an extension or another binary 12702 // operation; we'll abort this transformation. 12703 return SDValue(); 12704 } 12705 } 12706 } 12707 12708 // Make sure that this is a self-contained cluster of operations (which 12709 // is not quite the same thing as saying that everything has only one 12710 // use). 12711 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12712 if (isa<ConstantSDNode>(Inputs[i])) 12713 continue; 12714 12715 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12716 UE = Inputs[i].getNode()->use_end(); 12717 UI != UE; ++UI) { 12718 SDNode *User = *UI; 12719 if (User != N && !Visited.count(User)) 12720 return SDValue(); 12721 12722 // Make sure that we're not going to promote the non-output-value 12723 // operand(s) or SELECT or SELECT_CC. 12724 // FIXME: Although we could sometimes handle this, and it does occur in 12725 // practice that one of the condition inputs to the select is also one of 12726 // the outputs, we currently can't deal with this. 12727 if (User->getOpcode() == ISD::SELECT) { 12728 if (User->getOperand(0) == Inputs[i]) 12729 return SDValue(); 12730 } else if (User->getOpcode() == ISD::SELECT_CC) { 12731 if (User->getOperand(0) == Inputs[i] || 12732 User->getOperand(1) == Inputs[i]) 12733 return SDValue(); 12734 } 12735 } 12736 } 12737 12738 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12739 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12740 UE = PromOps[i].getNode()->use_end(); 12741 UI != UE; ++UI) { 12742 SDNode *User = *UI; 12743 if (User != N && !Visited.count(User)) 12744 return SDValue(); 12745 12746 // Make sure that we're not going to promote the non-output-value 12747 // operand(s) or SELECT or SELECT_CC. 12748 // FIXME: Although we could sometimes handle this, and it does occur in 12749 // practice that one of the condition inputs to the select is also one of 12750 // the outputs, we currently can't deal with this. 12751 if (User->getOpcode() == ISD::SELECT) { 12752 if (User->getOperand(0) == PromOps[i]) 12753 return SDValue(); 12754 } else if (User->getOpcode() == ISD::SELECT_CC) { 12755 if (User->getOperand(0) == PromOps[i] || 12756 User->getOperand(1) == PromOps[i]) 12757 return SDValue(); 12758 } 12759 } 12760 } 12761 12762 // Replace all inputs with the extension operand. 12763 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12764 // Constants may have users outside the cluster of to-be-promoted nodes, 12765 // and so we need to replace those as we do the promotions. 12766 if (isa<ConstantSDNode>(Inputs[i])) 12767 continue; 12768 else 12769 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12770 } 12771 12772 std::list<HandleSDNode> PromOpHandles; 12773 for (auto &PromOp : PromOps) 12774 PromOpHandles.emplace_back(PromOp); 12775 12776 // Replace all operations (these are all the same, but have a different 12777 // (i1) return type). DAG.getNode will validate that the types of 12778 // a binary operator match, so go through the list in reverse so that 12779 // we've likely promoted both operands first. Any intermediate truncations or 12780 // extensions disappear. 12781 while (!PromOpHandles.empty()) { 12782 SDValue PromOp = PromOpHandles.back().getValue(); 12783 PromOpHandles.pop_back(); 12784 12785 if (PromOp.getOpcode() == ISD::TRUNCATE || 12786 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12787 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12788 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12789 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12790 PromOp.getOperand(0).getValueType() != MVT::i1) { 12791 // The operand is not yet ready (see comment below). 12792 PromOpHandles.emplace_front(PromOp); 12793 continue; 12794 } 12795 12796 SDValue RepValue = PromOp.getOperand(0); 12797 if (isa<ConstantSDNode>(RepValue)) 12798 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12799 12800 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12801 continue; 12802 } 12803 12804 unsigned C; 12805 switch (PromOp.getOpcode()) { 12806 default: C = 0; break; 12807 case ISD::SELECT: C = 1; break; 12808 case ISD::SELECT_CC: C = 2; break; 12809 } 12810 12811 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12812 PromOp.getOperand(C).getValueType() != MVT::i1) || 12813 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12814 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12815 // The to-be-promoted operands of this node have not yet been 12816 // promoted (this should be rare because we're going through the 12817 // list backward, but if one of the operands has several users in 12818 // this cluster of to-be-promoted nodes, it is possible). 12819 PromOpHandles.emplace_front(PromOp); 12820 continue; 12821 } 12822 12823 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12824 PromOp.getNode()->op_end()); 12825 12826 // If there are any constant inputs, make sure they're replaced now. 12827 for (unsigned i = 0; i < 2; ++i) 12828 if (isa<ConstantSDNode>(Ops[C+i])) 12829 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12830 12831 DAG.ReplaceAllUsesOfValueWith(PromOp, 12832 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12833 } 12834 12835 // Now we're left with the initial truncation itself. 12836 if (N->getOpcode() == ISD::TRUNCATE) 12837 return N->getOperand(0); 12838 12839 // Otherwise, this is a comparison. The operands to be compared have just 12840 // changed type (to i1), but everything else is the same. 12841 return SDValue(N, 0); 12842 } 12843 12844 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12845 DAGCombinerInfo &DCI) const { 12846 SelectionDAG &DAG = DCI.DAG; 12847 SDLoc dl(N); 12848 12849 // If we're tracking CR bits, we need to be careful that we don't have: 12850 // zext(binary-ops(trunc(x), trunc(y))) 12851 // or 12852 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12853 // such that we're unnecessarily moving things into CR bits that can more 12854 // efficiently stay in GPRs. Note that if we're not certain that the high 12855 // bits are set as required by the final extension, we still may need to do 12856 // some masking to get the proper behavior. 12857 12858 // This same functionality is important on PPC64 when dealing with 12859 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12860 // the return values of functions. Because it is so similar, it is handled 12861 // here as well. 12862 12863 if (N->getValueType(0) != MVT::i32 && 12864 N->getValueType(0) != MVT::i64) 12865 return SDValue(); 12866 12867 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12868 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12869 return SDValue(); 12870 12871 if (N->getOperand(0).getOpcode() != ISD::AND && 12872 N->getOperand(0).getOpcode() != ISD::OR && 12873 N->getOperand(0).getOpcode() != ISD::XOR && 12874 N->getOperand(0).getOpcode() != ISD::SELECT && 12875 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12876 return SDValue(); 12877 12878 SmallVector<SDValue, 4> Inputs; 12879 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12880 SmallPtrSet<SDNode *, 16> Visited; 12881 12882 // Visit all inputs, collect all binary operations (and, or, xor and 12883 // select) that are all fed by truncations. 12884 while (!BinOps.empty()) { 12885 SDValue BinOp = BinOps.back(); 12886 BinOps.pop_back(); 12887 12888 if (!Visited.insert(BinOp.getNode()).second) 12889 continue; 12890 12891 PromOps.push_back(BinOp); 12892 12893 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12894 // The condition of the select is not promoted. 12895 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12896 continue; 12897 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12898 continue; 12899 12900 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12901 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12902 Inputs.push_back(BinOp.getOperand(i)); 12903 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12904 BinOp.getOperand(i).getOpcode() == ISD::OR || 12905 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12906 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12907 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12908 BinOps.push_back(BinOp.getOperand(i)); 12909 } else { 12910 // We have an input that is not a truncation or another binary 12911 // operation; we'll abort this transformation. 12912 return SDValue(); 12913 } 12914 } 12915 } 12916 12917 // The operands of a select that must be truncated when the select is 12918 // promoted because the operand is actually part of the to-be-promoted set. 12919 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12920 12921 // Make sure that this is a self-contained cluster of operations (which 12922 // is not quite the same thing as saying that everything has only one 12923 // use). 12924 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12925 if (isa<ConstantSDNode>(Inputs[i])) 12926 continue; 12927 12928 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12929 UE = Inputs[i].getNode()->use_end(); 12930 UI != UE; ++UI) { 12931 SDNode *User = *UI; 12932 if (User != N && !Visited.count(User)) 12933 return SDValue(); 12934 12935 // If we're going to promote the non-output-value operand(s) or SELECT or 12936 // SELECT_CC, record them for truncation. 12937 if (User->getOpcode() == ISD::SELECT) { 12938 if (User->getOperand(0) == Inputs[i]) 12939 SelectTruncOp[0].insert(std::make_pair(User, 12940 User->getOperand(0).getValueType())); 12941 } else if (User->getOpcode() == ISD::SELECT_CC) { 12942 if (User->getOperand(0) == Inputs[i]) 12943 SelectTruncOp[0].insert(std::make_pair(User, 12944 User->getOperand(0).getValueType())); 12945 if (User->getOperand(1) == Inputs[i]) 12946 SelectTruncOp[1].insert(std::make_pair(User, 12947 User->getOperand(1).getValueType())); 12948 } 12949 } 12950 } 12951 12952 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12953 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12954 UE = PromOps[i].getNode()->use_end(); 12955 UI != UE; ++UI) { 12956 SDNode *User = *UI; 12957 if (User != N && !Visited.count(User)) 12958 return SDValue(); 12959 12960 // If we're going to promote the non-output-value operand(s) or SELECT or 12961 // SELECT_CC, record them for truncation. 12962 if (User->getOpcode() == ISD::SELECT) { 12963 if (User->getOperand(0) == PromOps[i]) 12964 SelectTruncOp[0].insert(std::make_pair(User, 12965 User->getOperand(0).getValueType())); 12966 } else if (User->getOpcode() == ISD::SELECT_CC) { 12967 if (User->getOperand(0) == PromOps[i]) 12968 SelectTruncOp[0].insert(std::make_pair(User, 12969 User->getOperand(0).getValueType())); 12970 if (User->getOperand(1) == PromOps[i]) 12971 SelectTruncOp[1].insert(std::make_pair(User, 12972 User->getOperand(1).getValueType())); 12973 } 12974 } 12975 } 12976 12977 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12978 bool ReallyNeedsExt = false; 12979 if (N->getOpcode() != ISD::ANY_EXTEND) { 12980 // If all of the inputs are not already sign/zero extended, then 12981 // we'll still need to do that at the end. 12982 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12983 if (isa<ConstantSDNode>(Inputs[i])) 12984 continue; 12985 12986 unsigned OpBits = 12987 Inputs[i].getOperand(0).getValueSizeInBits(); 12988 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12989 12990 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12991 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12992 APInt::getHighBitsSet(OpBits, 12993 OpBits-PromBits))) || 12994 (N->getOpcode() == ISD::SIGN_EXTEND && 12995 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12996 (OpBits-(PromBits-1)))) { 12997 ReallyNeedsExt = true; 12998 break; 12999 } 13000 } 13001 } 13002 13003 // Replace all inputs, either with the truncation operand, or a 13004 // truncation or extension to the final output type. 13005 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13006 // Constant inputs need to be replaced with the to-be-promoted nodes that 13007 // use them because they might have users outside of the cluster of 13008 // promoted nodes. 13009 if (isa<ConstantSDNode>(Inputs[i])) 13010 continue; 13011 13012 SDValue InSrc = Inputs[i].getOperand(0); 13013 if (Inputs[i].getValueType() == N->getValueType(0)) 13014 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13015 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13016 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13017 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 13018 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13019 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13020 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 13021 else 13022 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 13023 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 13024 } 13025 13026 std::list<HandleSDNode> PromOpHandles; 13027 for (auto &PromOp : PromOps) 13028 PromOpHandles.emplace_back(PromOp); 13029 13030 // Replace all operations (these are all the same, but have a different 13031 // (promoted) return type). DAG.getNode will validate that the types of 13032 // a binary operator match, so go through the list in reverse so that 13033 // we've likely promoted both operands first. 13034 while (!PromOpHandles.empty()) { 13035 SDValue PromOp = PromOpHandles.back().getValue(); 13036 PromOpHandles.pop_back(); 13037 13038 unsigned C; 13039 switch (PromOp.getOpcode()) { 13040 default: C = 0; break; 13041 case ISD::SELECT: C = 1; break; 13042 case ISD::SELECT_CC: C = 2; break; 13043 } 13044 13045 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13046 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 13047 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13048 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 13049 // The to-be-promoted operands of this node have not yet been 13050 // promoted (this should be rare because we're going through the 13051 // list backward, but if one of the operands has several users in 13052 // this cluster of to-be-promoted nodes, it is possible). 13053 PromOpHandles.emplace_front(PromOp); 13054 continue; 13055 } 13056 13057 // For SELECT and SELECT_CC nodes, we do a similar check for any 13058 // to-be-promoted comparison inputs. 13059 if (PromOp.getOpcode() == ISD::SELECT || 13060 PromOp.getOpcode() == ISD::SELECT_CC) { 13061 if ((SelectTruncOp[0].count(PromOp.getNode()) && 13062 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 13063 (SelectTruncOp[1].count(PromOp.getNode()) && 13064 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 13065 PromOpHandles.emplace_front(PromOp); 13066 continue; 13067 } 13068 } 13069 13070 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13071 PromOp.getNode()->op_end()); 13072 13073 // If this node has constant inputs, then they'll need to be promoted here. 13074 for (unsigned i = 0; i < 2; ++i) { 13075 if (!isa<ConstantSDNode>(Ops[C+i])) 13076 continue; 13077 if (Ops[C+i].getValueType() == N->getValueType(0)) 13078 continue; 13079 13080 if (N->getOpcode() == ISD::SIGN_EXTEND) 13081 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13082 else if (N->getOpcode() == ISD::ZERO_EXTEND) 13083 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13084 else 13085 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 13086 } 13087 13088 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 13089 // truncate them again to the original value type. 13090 if (PromOp.getOpcode() == ISD::SELECT || 13091 PromOp.getOpcode() == ISD::SELECT_CC) { 13092 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 13093 if (SI0 != SelectTruncOp[0].end()) 13094 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 13095 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 13096 if (SI1 != SelectTruncOp[1].end()) 13097 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 13098 } 13099 13100 DAG.ReplaceAllUsesOfValueWith(PromOp, 13101 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 13102 } 13103 13104 // Now we're left with the initial extension itself. 13105 if (!ReallyNeedsExt) 13106 return N->getOperand(0); 13107 13108 // To zero extend, just mask off everything except for the first bit (in the 13109 // i1 case). 13110 if (N->getOpcode() == ISD::ZERO_EXTEND) 13111 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 13112 DAG.getConstant(APInt::getLowBitsSet( 13113 N->getValueSizeInBits(0), PromBits), 13114 dl, N->getValueType(0))); 13115 13116 assert(N->getOpcode() == ISD::SIGN_EXTEND && 13117 "Invalid extension type"); 13118 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 13119 SDValue ShiftCst = 13120 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 13121 return DAG.getNode( 13122 ISD::SRA, dl, N->getValueType(0), 13123 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 13124 ShiftCst); 13125 } 13126 13127 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 13128 DAGCombinerInfo &DCI) const { 13129 assert(N->getOpcode() == ISD::SETCC && 13130 "Should be called with a SETCC node"); 13131 13132 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13133 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 13134 SDValue LHS = N->getOperand(0); 13135 SDValue RHS = N->getOperand(1); 13136 13137 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 13138 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 13139 LHS.hasOneUse()) 13140 std::swap(LHS, RHS); 13141 13142 // x == 0-y --> x+y == 0 13143 // x != 0-y --> x+y != 0 13144 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 13145 RHS.hasOneUse()) { 13146 SDLoc DL(N); 13147 SelectionDAG &DAG = DCI.DAG; 13148 EVT VT = N->getValueType(0); 13149 EVT OpVT = LHS.getValueType(); 13150 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 13151 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 13152 } 13153 } 13154 13155 return DAGCombineTruncBoolExt(N, DCI); 13156 } 13157 13158 // Is this an extending load from an f32 to an f64? 13159 static bool isFPExtLoad(SDValue Op) { 13160 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 13161 return LD->getExtensionType() == ISD::EXTLOAD && 13162 Op.getValueType() == MVT::f64; 13163 return false; 13164 } 13165 13166 /// Reduces the number of fp-to-int conversion when building a vector. 13167 /// 13168 /// If this vector is built out of floating to integer conversions, 13169 /// transform it to a vector built out of floating point values followed by a 13170 /// single floating to integer conversion of the vector. 13171 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 13172 /// becomes (fptosi (build_vector ($A, $B, ...))) 13173 SDValue PPCTargetLowering:: 13174 combineElementTruncationToVectorTruncation(SDNode *N, 13175 DAGCombinerInfo &DCI) const { 13176 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13177 "Should be called with a BUILD_VECTOR node"); 13178 13179 SelectionDAG &DAG = DCI.DAG; 13180 SDLoc dl(N); 13181 13182 SDValue FirstInput = N->getOperand(0); 13183 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 13184 "The input operand must be an fp-to-int conversion."); 13185 13186 // This combine happens after legalization so the fp_to_[su]i nodes are 13187 // already converted to PPCSISD nodes. 13188 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 13189 if (FirstConversion == PPCISD::FCTIDZ || 13190 FirstConversion == PPCISD::FCTIDUZ || 13191 FirstConversion == PPCISD::FCTIWZ || 13192 FirstConversion == PPCISD::FCTIWUZ) { 13193 bool IsSplat = true; 13194 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 13195 FirstConversion == PPCISD::FCTIWUZ; 13196 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 13197 SmallVector<SDValue, 4> Ops; 13198 EVT TargetVT = N->getValueType(0); 13199 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13200 SDValue NextOp = N->getOperand(i); 13201 if (NextOp.getOpcode() != PPCISD::MFVSR) 13202 return SDValue(); 13203 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 13204 if (NextConversion != FirstConversion) 13205 return SDValue(); 13206 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 13207 // This is not valid if the input was originally double precision. It is 13208 // also not profitable to do unless this is an extending load in which 13209 // case doing this combine will allow us to combine consecutive loads. 13210 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 13211 return SDValue(); 13212 if (N->getOperand(i) != FirstInput) 13213 IsSplat = false; 13214 } 13215 13216 // If this is a splat, we leave it as-is since there will be only a single 13217 // fp-to-int conversion followed by a splat of the integer. This is better 13218 // for 32-bit and smaller ints and neutral for 64-bit ints. 13219 if (IsSplat) 13220 return SDValue(); 13221 13222 // Now that we know we have the right type of node, get its operands 13223 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 13224 SDValue In = N->getOperand(i).getOperand(0); 13225 if (Is32Bit) { 13226 // For 32-bit values, we need to add an FP_ROUND node (if we made it 13227 // here, we know that all inputs are extending loads so this is safe). 13228 if (In.isUndef()) 13229 Ops.push_back(DAG.getUNDEF(SrcVT)); 13230 else { 13231 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 13232 MVT::f32, In.getOperand(0), 13233 DAG.getIntPtrConstant(1, dl)); 13234 Ops.push_back(Trunc); 13235 } 13236 } else 13237 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 13238 } 13239 13240 unsigned Opcode; 13241 if (FirstConversion == PPCISD::FCTIDZ || 13242 FirstConversion == PPCISD::FCTIWZ) 13243 Opcode = ISD::FP_TO_SINT; 13244 else 13245 Opcode = ISD::FP_TO_UINT; 13246 13247 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13248 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13249 return DAG.getNode(Opcode, dl, TargetVT, BV); 13250 } 13251 return SDValue(); 13252 } 13253 13254 /// Reduce the number of loads when building a vector. 13255 /// 13256 /// Building a vector out of multiple loads can be converted to a load 13257 /// of the vector type if the loads are consecutive. If the loads are 13258 /// consecutive but in descending order, a shuffle is added at the end 13259 /// to reorder the vector. 13260 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13261 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13262 "Should be called with a BUILD_VECTOR node"); 13263 13264 SDLoc dl(N); 13265 13266 // Return early for non byte-sized type, as they can't be consecutive. 13267 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13268 return SDValue(); 13269 13270 bool InputsAreConsecutiveLoads = true; 13271 bool InputsAreReverseConsecutive = true; 13272 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13273 SDValue FirstInput = N->getOperand(0); 13274 bool IsRoundOfExtLoad = false; 13275 13276 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13277 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13278 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13279 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13280 } 13281 // Not a build vector of (possibly fp_rounded) loads. 13282 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13283 N->getNumOperands() == 1) 13284 return SDValue(); 13285 13286 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13287 // If any inputs are fp_round(extload), they all must be. 13288 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13289 return SDValue(); 13290 13291 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13292 N->getOperand(i); 13293 if (NextInput.getOpcode() != ISD::LOAD) 13294 return SDValue(); 13295 13296 SDValue PreviousInput = 13297 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13298 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13299 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13300 13301 // If any inputs are fp_round(extload), they all must be. 13302 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13303 return SDValue(); 13304 13305 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13306 InputsAreConsecutiveLoads = false; 13307 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13308 InputsAreReverseConsecutive = false; 13309 13310 // Exit early if the loads are neither consecutive nor reverse consecutive. 13311 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13312 return SDValue(); 13313 } 13314 13315 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13316 "The loads cannot be both consecutive and reverse consecutive."); 13317 13318 SDValue FirstLoadOp = 13319 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13320 SDValue LastLoadOp = 13321 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13322 N->getOperand(N->getNumOperands()-1); 13323 13324 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13325 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13326 if (InputsAreConsecutiveLoads) { 13327 assert(LD1 && "Input needs to be a LoadSDNode."); 13328 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13329 LD1->getBasePtr(), LD1->getPointerInfo(), 13330 LD1->getAlignment()); 13331 } 13332 if (InputsAreReverseConsecutive) { 13333 assert(LDL && "Input needs to be a LoadSDNode."); 13334 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13335 LDL->getBasePtr(), LDL->getPointerInfo(), 13336 LDL->getAlignment()); 13337 SmallVector<int, 16> Ops; 13338 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13339 Ops.push_back(i); 13340 13341 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13342 DAG.getUNDEF(N->getValueType(0)), Ops); 13343 } 13344 return SDValue(); 13345 } 13346 13347 // This function adds the required vector_shuffle needed to get 13348 // the elements of the vector extract in the correct position 13349 // as specified by the CorrectElems encoding. 13350 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13351 SDValue Input, uint64_t Elems, 13352 uint64_t CorrectElems) { 13353 SDLoc dl(N); 13354 13355 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13356 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13357 13358 // Knowing the element indices being extracted from the original 13359 // vector and the order in which they're being inserted, just put 13360 // them at element indices required for the instruction. 13361 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13362 if (DAG.getDataLayout().isLittleEndian()) 13363 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13364 else 13365 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13366 CorrectElems = CorrectElems >> 8; 13367 Elems = Elems >> 8; 13368 } 13369 13370 SDValue Shuffle = 13371 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13372 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13373 13374 EVT VT = N->getValueType(0); 13375 SDValue Conv = DAG.getBitcast(VT, Shuffle); 13376 13377 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 13378 Input.getValueType().getVectorElementType(), 13379 VT.getVectorNumElements()); 13380 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 13381 DAG.getValueType(ExtVT)); 13382 } 13383 13384 // Look for build vector patterns where input operands come from sign 13385 // extended vector_extract elements of specific indices. If the correct indices 13386 // aren't used, add a vector shuffle to fix up the indices and create 13387 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 13388 // during instruction selection. 13389 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13390 // This array encodes the indices that the vector sign extend instructions 13391 // extract from when extending from one type to another for both BE and LE. 13392 // The right nibble of each byte corresponds to the LE incides. 13393 // and the left nibble of each byte corresponds to the BE incides. 13394 // For example: 0x3074B8FC byte->word 13395 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13396 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13397 // For example: 0x000070F8 byte->double word 13398 // For LE: the allowed indices are: 0x0,0x8 13399 // For BE: the allowed indices are: 0x7,0xF 13400 uint64_t TargetElems[] = { 13401 0x3074B8FC, // b->w 13402 0x000070F8, // b->d 13403 0x10325476, // h->w 13404 0x00003074, // h->d 13405 0x00001032, // w->d 13406 }; 13407 13408 uint64_t Elems = 0; 13409 int Index; 13410 SDValue Input; 13411 13412 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13413 if (!Op) 13414 return false; 13415 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13416 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13417 return false; 13418 13419 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13420 // of the right width. 13421 SDValue Extract = Op.getOperand(0); 13422 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13423 Extract = Extract.getOperand(0); 13424 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13425 return false; 13426 13427 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13428 if (!ExtOp) 13429 return false; 13430 13431 Index = ExtOp->getZExtValue(); 13432 if (Input && Input != Extract.getOperand(0)) 13433 return false; 13434 13435 if (!Input) 13436 Input = Extract.getOperand(0); 13437 13438 Elems = Elems << 8; 13439 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13440 Elems |= Index; 13441 13442 return true; 13443 }; 13444 13445 // If the build vector operands aren't sign extended vector extracts, 13446 // of the same input vector, then return. 13447 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13448 if (!isSExtOfVecExtract(N->getOperand(i))) { 13449 return SDValue(); 13450 } 13451 } 13452 13453 // If the vector extract indicies are not correct, add the appropriate 13454 // vector_shuffle. 13455 int TgtElemArrayIdx; 13456 int InputSize = Input.getValueType().getScalarSizeInBits(); 13457 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13458 if (InputSize + OutputSize == 40) 13459 TgtElemArrayIdx = 0; 13460 else if (InputSize + OutputSize == 72) 13461 TgtElemArrayIdx = 1; 13462 else if (InputSize + OutputSize == 48) 13463 TgtElemArrayIdx = 2; 13464 else if (InputSize + OutputSize == 80) 13465 TgtElemArrayIdx = 3; 13466 else if (InputSize + OutputSize == 96) 13467 TgtElemArrayIdx = 4; 13468 else 13469 return SDValue(); 13470 13471 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13472 CorrectElems = DAG.getDataLayout().isLittleEndian() 13473 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13474 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13475 if (Elems != CorrectElems) { 13476 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13477 } 13478 13479 // Regular lowering will catch cases where a shuffle is not needed. 13480 return SDValue(); 13481 } 13482 13483 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13484 DAGCombinerInfo &DCI) const { 13485 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13486 "Should be called with a BUILD_VECTOR node"); 13487 13488 SelectionDAG &DAG = DCI.DAG; 13489 SDLoc dl(N); 13490 13491 if (!Subtarget.hasVSX()) 13492 return SDValue(); 13493 13494 // The target independent DAG combiner will leave a build_vector of 13495 // float-to-int conversions intact. We can generate MUCH better code for 13496 // a float-to-int conversion of a vector of floats. 13497 SDValue FirstInput = N->getOperand(0); 13498 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13499 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13500 if (Reduced) 13501 return Reduced; 13502 } 13503 13504 // If we're building a vector out of consecutive loads, just load that 13505 // vector type. 13506 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13507 if (Reduced) 13508 return Reduced; 13509 13510 // If we're building a vector out of extended elements from another vector 13511 // we have P9 vector integer extend instructions. The code assumes legal 13512 // input types (i.e. it can't handle things like v4i16) so do not run before 13513 // legalization. 13514 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13515 Reduced = combineBVOfVecSExt(N, DAG); 13516 if (Reduced) 13517 return Reduced; 13518 } 13519 13520 13521 if (N->getValueType(0) != MVT::v2f64) 13522 return SDValue(); 13523 13524 // Looking for: 13525 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13526 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13527 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13528 return SDValue(); 13529 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13530 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13531 return SDValue(); 13532 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13533 return SDValue(); 13534 13535 SDValue Ext1 = FirstInput.getOperand(0); 13536 SDValue Ext2 = N->getOperand(1).getOperand(0); 13537 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13538 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13539 return SDValue(); 13540 13541 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13542 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13543 if (!Ext1Op || !Ext2Op) 13544 return SDValue(); 13545 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13546 Ext1.getOperand(0) != Ext2.getOperand(0)) 13547 return SDValue(); 13548 13549 int FirstElem = Ext1Op->getZExtValue(); 13550 int SecondElem = Ext2Op->getZExtValue(); 13551 int SubvecIdx; 13552 if (FirstElem == 0 && SecondElem == 1) 13553 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13554 else if (FirstElem == 2 && SecondElem == 3) 13555 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13556 else 13557 return SDValue(); 13558 13559 SDValue SrcVec = Ext1.getOperand(0); 13560 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13561 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13562 return DAG.getNode(NodeType, dl, MVT::v2f64, 13563 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13564 } 13565 13566 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13567 DAGCombinerInfo &DCI) const { 13568 assert((N->getOpcode() == ISD::SINT_TO_FP || 13569 N->getOpcode() == ISD::UINT_TO_FP) && 13570 "Need an int -> FP conversion node here"); 13571 13572 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13573 return SDValue(); 13574 13575 SelectionDAG &DAG = DCI.DAG; 13576 SDLoc dl(N); 13577 SDValue Op(N, 0); 13578 13579 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13580 // from the hardware. 13581 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13582 return SDValue(); 13583 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13584 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13585 return SDValue(); 13586 13587 SDValue FirstOperand(Op.getOperand(0)); 13588 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13589 (FirstOperand.getValueType() == MVT::i8 || 13590 FirstOperand.getValueType() == MVT::i16); 13591 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13592 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13593 bool DstDouble = Op.getValueType() == MVT::f64; 13594 unsigned ConvOp = Signed ? 13595 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13596 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13597 SDValue WidthConst = 13598 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13599 dl, false); 13600 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13601 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13602 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13603 DAG.getVTList(MVT::f64, MVT::Other), 13604 Ops, MVT::i8, LDN->getMemOperand()); 13605 13606 // For signed conversion, we need to sign-extend the value in the VSR 13607 if (Signed) { 13608 SDValue ExtOps[] = { Ld, WidthConst }; 13609 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13610 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13611 } else 13612 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13613 } 13614 13615 13616 // For i32 intermediate values, unfortunately, the conversion functions 13617 // leave the upper 32 bits of the value are undefined. Within the set of 13618 // scalar instructions, we have no method for zero- or sign-extending the 13619 // value. Thus, we cannot handle i32 intermediate values here. 13620 if (Op.getOperand(0).getValueType() == MVT::i32) 13621 return SDValue(); 13622 13623 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13624 "UINT_TO_FP is supported only with FPCVT"); 13625 13626 // If we have FCFIDS, then use it when converting to single-precision. 13627 // Otherwise, convert to double-precision and then round. 13628 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13629 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13630 : PPCISD::FCFIDS) 13631 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13632 : PPCISD::FCFID); 13633 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13634 ? MVT::f32 13635 : MVT::f64; 13636 13637 // If we're converting from a float, to an int, and back to a float again, 13638 // then we don't need the store/load pair at all. 13639 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13640 Subtarget.hasFPCVT()) || 13641 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13642 SDValue Src = Op.getOperand(0).getOperand(0); 13643 if (Src.getValueType() == MVT::f32) { 13644 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13645 DCI.AddToWorklist(Src.getNode()); 13646 } else if (Src.getValueType() != MVT::f64) { 13647 // Make sure that we don't pick up a ppc_fp128 source value. 13648 return SDValue(); 13649 } 13650 13651 unsigned FCTOp = 13652 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13653 PPCISD::FCTIDUZ; 13654 13655 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13656 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13657 13658 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13659 FP = DAG.getNode(ISD::FP_ROUND, dl, 13660 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13661 DCI.AddToWorklist(FP.getNode()); 13662 } 13663 13664 return FP; 13665 } 13666 13667 return SDValue(); 13668 } 13669 13670 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13671 // builtins) into loads with swaps. 13672 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13673 DAGCombinerInfo &DCI) const { 13674 SelectionDAG &DAG = DCI.DAG; 13675 SDLoc dl(N); 13676 SDValue Chain; 13677 SDValue Base; 13678 MachineMemOperand *MMO; 13679 13680 switch (N->getOpcode()) { 13681 default: 13682 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13683 case ISD::LOAD: { 13684 LoadSDNode *LD = cast<LoadSDNode>(N); 13685 Chain = LD->getChain(); 13686 Base = LD->getBasePtr(); 13687 MMO = LD->getMemOperand(); 13688 // If the MMO suggests this isn't a load of a full vector, leave 13689 // things alone. For a built-in, we have to make the change for 13690 // correctness, so if there is a size problem that will be a bug. 13691 if (MMO->getSize() < 16) 13692 return SDValue(); 13693 break; 13694 } 13695 case ISD::INTRINSIC_W_CHAIN: { 13696 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13697 Chain = Intrin->getChain(); 13698 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13699 // us what we want. Get operand 2 instead. 13700 Base = Intrin->getOperand(2); 13701 MMO = Intrin->getMemOperand(); 13702 break; 13703 } 13704 } 13705 13706 MVT VecTy = N->getValueType(0).getSimpleVT(); 13707 13708 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13709 // aligned and the type is a vector with elements up to 4 bytes 13710 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13711 VecTy.getScalarSizeInBits() <= 32) { 13712 return SDValue(); 13713 } 13714 13715 SDValue LoadOps[] = { Chain, Base }; 13716 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13717 DAG.getVTList(MVT::v2f64, MVT::Other), 13718 LoadOps, MVT::v2f64, MMO); 13719 13720 DCI.AddToWorklist(Load.getNode()); 13721 Chain = Load.getValue(1); 13722 SDValue Swap = DAG.getNode( 13723 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13724 DCI.AddToWorklist(Swap.getNode()); 13725 13726 // Add a bitcast if the resulting load type doesn't match v2f64. 13727 if (VecTy != MVT::v2f64) { 13728 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13729 DCI.AddToWorklist(N.getNode()); 13730 // Package {bitcast value, swap's chain} to match Load's shape. 13731 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13732 N, Swap.getValue(1)); 13733 } 13734 13735 return Swap; 13736 } 13737 13738 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13739 // builtins) into stores with swaps. 13740 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13741 DAGCombinerInfo &DCI) const { 13742 SelectionDAG &DAG = DCI.DAG; 13743 SDLoc dl(N); 13744 SDValue Chain; 13745 SDValue Base; 13746 unsigned SrcOpnd; 13747 MachineMemOperand *MMO; 13748 13749 switch (N->getOpcode()) { 13750 default: 13751 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13752 case ISD::STORE: { 13753 StoreSDNode *ST = cast<StoreSDNode>(N); 13754 Chain = ST->getChain(); 13755 Base = ST->getBasePtr(); 13756 MMO = ST->getMemOperand(); 13757 SrcOpnd = 1; 13758 // If the MMO suggests this isn't a store of a full vector, leave 13759 // things alone. For a built-in, we have to make the change for 13760 // correctness, so if there is a size problem that will be a bug. 13761 if (MMO->getSize() < 16) 13762 return SDValue(); 13763 break; 13764 } 13765 case ISD::INTRINSIC_VOID: { 13766 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13767 Chain = Intrin->getChain(); 13768 // Intrin->getBasePtr() oddly does not get what we want. 13769 Base = Intrin->getOperand(3); 13770 MMO = Intrin->getMemOperand(); 13771 SrcOpnd = 2; 13772 break; 13773 } 13774 } 13775 13776 SDValue Src = N->getOperand(SrcOpnd); 13777 MVT VecTy = Src.getValueType().getSimpleVT(); 13778 13779 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13780 // aligned and the type is a vector with elements up to 4 bytes 13781 if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) && 13782 VecTy.getScalarSizeInBits() <= 32) { 13783 return SDValue(); 13784 } 13785 13786 // All stores are done as v2f64 and possible bit cast. 13787 if (VecTy != MVT::v2f64) { 13788 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13789 DCI.AddToWorklist(Src.getNode()); 13790 } 13791 13792 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13793 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13794 DCI.AddToWorklist(Swap.getNode()); 13795 Chain = Swap.getValue(1); 13796 SDValue StoreOps[] = { Chain, Swap, Base }; 13797 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13798 DAG.getVTList(MVT::Other), 13799 StoreOps, VecTy, MMO); 13800 DCI.AddToWorklist(Store.getNode()); 13801 return Store; 13802 } 13803 13804 // Handle DAG combine for STORE (FP_TO_INT F). 13805 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13806 DAGCombinerInfo &DCI) const { 13807 13808 SelectionDAG &DAG = DCI.DAG; 13809 SDLoc dl(N); 13810 unsigned Opcode = N->getOperand(1).getOpcode(); 13811 13812 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13813 && "Not a FP_TO_INT Instruction!"); 13814 13815 SDValue Val = N->getOperand(1).getOperand(0); 13816 EVT Op1VT = N->getOperand(1).getValueType(); 13817 EVT ResVT = Val.getValueType(); 13818 13819 // Floating point types smaller than 32 bits are not legal on Power. 13820 if (ResVT.getScalarSizeInBits() < 32) 13821 return SDValue(); 13822 13823 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13824 bool ValidTypeForStoreFltAsInt = 13825 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13826 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13827 13828 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 13829 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13830 return SDValue(); 13831 13832 // Extend f32 values to f64 13833 if (ResVT.getScalarSizeInBits() == 32) { 13834 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13835 DCI.AddToWorklist(Val.getNode()); 13836 } 13837 13838 // Set signed or unsigned conversion opcode. 13839 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13840 PPCISD::FP_TO_SINT_IN_VSR : 13841 PPCISD::FP_TO_UINT_IN_VSR; 13842 13843 Val = DAG.getNode(ConvOpcode, 13844 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13845 DCI.AddToWorklist(Val.getNode()); 13846 13847 // Set number of bytes being converted. 13848 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13849 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13850 DAG.getIntPtrConstant(ByteSize, dl, false), 13851 DAG.getValueType(Op1VT) }; 13852 13853 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13854 DAG.getVTList(MVT::Other), Ops, 13855 cast<StoreSDNode>(N)->getMemoryVT(), 13856 cast<StoreSDNode>(N)->getMemOperand()); 13857 13858 DCI.AddToWorklist(Val.getNode()); 13859 return Val; 13860 } 13861 13862 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 13863 // Check that the source of the element keeps flipping 13864 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 13865 bool PrevElemFromFirstVec = Mask[0] < NumElts; 13866 for (int i = 1, e = Mask.size(); i < e; i++) { 13867 if (PrevElemFromFirstVec && Mask[i] < NumElts) 13868 return false; 13869 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 13870 return false; 13871 PrevElemFromFirstVec = !PrevElemFromFirstVec; 13872 } 13873 return true; 13874 } 13875 13876 static bool isSplatBV(SDValue Op) { 13877 if (Op.getOpcode() != ISD::BUILD_VECTOR) 13878 return false; 13879 SDValue FirstOp; 13880 13881 // Find first non-undef input. 13882 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 13883 FirstOp = Op.getOperand(i); 13884 if (!FirstOp.isUndef()) 13885 break; 13886 } 13887 13888 // All inputs are undef or the same as the first non-undef input. 13889 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 13890 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 13891 return false; 13892 return true; 13893 } 13894 13895 static SDValue isScalarToVec(SDValue Op) { 13896 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13897 return Op; 13898 if (Op.getOpcode() != ISD::BITCAST) 13899 return SDValue(); 13900 Op = Op.getOperand(0); 13901 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 13902 return Op; 13903 return SDValue(); 13904 } 13905 13906 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 13907 int LHSMaxIdx, int RHSMinIdx, 13908 int RHSMaxIdx, int HalfVec) { 13909 for (int i = 0, e = ShuffV.size(); i < e; i++) { 13910 int Idx = ShuffV[i]; 13911 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 13912 ShuffV[i] += HalfVec; 13913 } 13914 return; 13915 } 13916 13917 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 13918 // the original is: 13919 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 13920 // In such a case, just change the shuffle mask to extract the element 13921 // from the permuted index. 13922 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) { 13923 SDLoc dl(OrigSToV); 13924 EVT VT = OrigSToV.getValueType(); 13925 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 13926 "Expecting a SCALAR_TO_VECTOR here"); 13927 SDValue Input = OrigSToV.getOperand(0); 13928 13929 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13930 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 13931 SDValue OrigVector = Input.getOperand(0); 13932 13933 // Can't handle non-const element indices or different vector types 13934 // for the input to the extract and the output of the scalar_to_vector. 13935 if (Idx && VT == OrigVector.getValueType()) { 13936 SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1); 13937 NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue(); 13938 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 13939 } 13940 } 13941 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 13942 OrigSToV.getOperand(0)); 13943 } 13944 13945 // On little endian subtargets, combine shuffles such as: 13946 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 13947 // into: 13948 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 13949 // because the latter can be matched to a single instruction merge. 13950 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 13951 // to put the value into element zero. Adjust the shuffle mask so that the 13952 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 13953 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 13954 SelectionDAG &DAG) const { 13955 SDValue LHS = SVN->getOperand(0); 13956 SDValue RHS = SVN->getOperand(1); 13957 auto Mask = SVN->getMask(); 13958 int NumElts = LHS.getValueType().getVectorNumElements(); 13959 SDValue Res(SVN, 0); 13960 SDLoc dl(SVN); 13961 13962 // None of these combines are useful on big endian systems since the ISA 13963 // already has a big endian bias. 13964 if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13965 return Res; 13966 13967 // If this is not a shuffle of a shuffle and the first element comes from 13968 // the second vector, canonicalize to the commuted form. This will make it 13969 // more likely to match one of the single instruction patterns. 13970 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 13971 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 13972 std::swap(LHS, RHS); 13973 Res = DAG.getCommutedVectorShuffle(*SVN); 13974 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 13975 } 13976 13977 // Adjust the shuffle mask if either input vector comes from a 13978 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 13979 // form (to prevent the need for a swap). 13980 SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end()); 13981 SDValue SToVLHS = isScalarToVec(LHS); 13982 SDValue SToVRHS = isScalarToVec(RHS); 13983 if (SToVLHS || SToVRHS) { 13984 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 13985 : SToVRHS.getValueType().getVectorNumElements(); 13986 int NumEltsOut = ShuffV.size(); 13987 13988 // Initially assume that neither input is permuted. These will be adjusted 13989 // accordingly if either input is. 13990 int LHSMaxIdx = -1; 13991 int RHSMinIdx = -1; 13992 int RHSMaxIdx = -1; 13993 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 13994 13995 // Get the permuted scalar to vector nodes for the source(s) that come from 13996 // ISD::SCALAR_TO_VECTOR. 13997 if (SToVLHS) { 13998 // Set up the values for the shuffle vector fixup. 13999 LHSMaxIdx = NumEltsOut / NumEltsIn; 14000 SToVLHS = getSToVPermuted(SToVLHS, DAG); 14001 if (SToVLHS.getValueType() != LHS.getValueType()) 14002 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 14003 LHS = SToVLHS; 14004 } 14005 if (SToVRHS) { 14006 RHSMinIdx = NumEltsOut; 14007 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 14008 SToVRHS = getSToVPermuted(SToVRHS, DAG); 14009 if (SToVRHS.getValueType() != RHS.getValueType()) 14010 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 14011 RHS = SToVRHS; 14012 } 14013 14014 // Fix up the shuffle mask to reflect where the desired element actually is. 14015 // The minimum and maximum indices that correspond to element zero for both 14016 // the LHS and RHS are computed and will control which shuffle mask entries 14017 // are to be changed. For example, if the RHS is permuted, any shuffle mask 14018 // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by 14019 // HalfVec to refer to the corresponding element in the permuted vector. 14020 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 14021 HalfVec); 14022 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14023 14024 // We may have simplified away the shuffle. We won't be able to do anything 14025 // further with it here. 14026 if (!isa<ShuffleVectorSDNode>(Res)) 14027 return Res; 14028 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 14029 } 14030 14031 // The common case after we commuted the shuffle is that the RHS is a splat 14032 // and we have elements coming in from the splat at indices that are not 14033 // conducive to using a merge. 14034 // Example: 14035 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 14036 if (!isSplatBV(RHS)) 14037 return Res; 14038 14039 // We are looking for a mask such that all even elements are from 14040 // one vector and all odd elements from the other. 14041 if (!isAlternatingShuffMask(Mask, NumElts)) 14042 return Res; 14043 14044 // Adjust the mask so we are pulling in the same index from the splat 14045 // as the index from the interesting vector in consecutive elements. 14046 // Example (even elements from first vector): 14047 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 14048 if (Mask[0] < NumElts) 14049 for (int i = 1, e = Mask.size(); i < e; i += 2) 14050 ShuffV[i] = (ShuffV[i - 1] + NumElts); 14051 // Example (odd elements from first vector): 14052 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 14053 else 14054 for (int i = 0, e = Mask.size(); i < e; i += 2) 14055 ShuffV[i] = (ShuffV[i + 1] + NumElts); 14056 14057 // If the RHS has undefs, we need to remove them since we may have created 14058 // a shuffle that adds those instead of the splat value. 14059 SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue(); 14060 RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal); 14061 14062 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 14063 return Res; 14064 } 14065 14066 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 14067 LSBaseSDNode *LSBase, 14068 DAGCombinerInfo &DCI) const { 14069 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 14070 "Not a reverse memop pattern!"); 14071 14072 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 14073 auto Mask = SVN->getMask(); 14074 int i = 0; 14075 auto I = Mask.rbegin(); 14076 auto E = Mask.rend(); 14077 14078 for (; I != E; ++I) { 14079 if (*I != i) 14080 return false; 14081 i++; 14082 } 14083 return true; 14084 }; 14085 14086 SelectionDAG &DAG = DCI.DAG; 14087 EVT VT = SVN->getValueType(0); 14088 14089 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 14090 return SDValue(); 14091 14092 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 14093 // See comment in PPCVSXSwapRemoval.cpp. 14094 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 14095 if (!Subtarget.hasP9Vector()) 14096 return SDValue(); 14097 14098 if(!IsElementReverse(SVN)) 14099 return SDValue(); 14100 14101 if (LSBase->getOpcode() == ISD::LOAD) { 14102 SDLoc dl(SVN); 14103 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 14104 return DAG.getMemIntrinsicNode( 14105 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 14106 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14107 } 14108 14109 if (LSBase->getOpcode() == ISD::STORE) { 14110 SDLoc dl(LSBase); 14111 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 14112 LSBase->getBasePtr()}; 14113 return DAG.getMemIntrinsicNode( 14114 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 14115 LSBase->getMemoryVT(), LSBase->getMemOperand()); 14116 } 14117 14118 llvm_unreachable("Expected a load or store node here"); 14119 } 14120 14121 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 14122 DAGCombinerInfo &DCI) const { 14123 SelectionDAG &DAG = DCI.DAG; 14124 SDLoc dl(N); 14125 switch (N->getOpcode()) { 14126 default: break; 14127 case ISD::ADD: 14128 return combineADD(N, DCI); 14129 case ISD::SHL: 14130 return combineSHL(N, DCI); 14131 case ISD::SRA: 14132 return combineSRA(N, DCI); 14133 case ISD::SRL: 14134 return combineSRL(N, DCI); 14135 case ISD::MUL: 14136 return combineMUL(N, DCI); 14137 case ISD::FMA: 14138 case PPCISD::FNMSUB: 14139 return combineFMALike(N, DCI); 14140 case PPCISD::SHL: 14141 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 14142 return N->getOperand(0); 14143 break; 14144 case PPCISD::SRL: 14145 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 14146 return N->getOperand(0); 14147 break; 14148 case PPCISD::SRA: 14149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 14150 if (C->isNullValue() || // 0 >>s V -> 0. 14151 C->isAllOnesValue()) // -1 >>s V -> -1. 14152 return N->getOperand(0); 14153 } 14154 break; 14155 case ISD::SIGN_EXTEND: 14156 case ISD::ZERO_EXTEND: 14157 case ISD::ANY_EXTEND: 14158 return DAGCombineExtBoolTrunc(N, DCI); 14159 case ISD::TRUNCATE: 14160 return combineTRUNCATE(N, DCI); 14161 case ISD::SETCC: 14162 if (SDValue CSCC = combineSetCC(N, DCI)) 14163 return CSCC; 14164 LLVM_FALLTHROUGH; 14165 case ISD::SELECT_CC: 14166 return DAGCombineTruncBoolExt(N, DCI); 14167 case ISD::SINT_TO_FP: 14168 case ISD::UINT_TO_FP: 14169 return combineFPToIntToFP(N, DCI); 14170 case ISD::VECTOR_SHUFFLE: 14171 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 14172 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 14173 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 14174 } 14175 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 14176 case ISD::STORE: { 14177 14178 EVT Op1VT = N->getOperand(1).getValueType(); 14179 unsigned Opcode = N->getOperand(1).getOpcode(); 14180 14181 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 14182 SDValue Val= combineStoreFPToInt(N, DCI); 14183 if (Val) 14184 return Val; 14185 } 14186 14187 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 14188 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 14189 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 14190 if (Val) 14191 return Val; 14192 } 14193 14194 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 14195 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 14196 N->getOperand(1).getNode()->hasOneUse() && 14197 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 14198 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 14199 14200 // STBRX can only handle simple types and it makes no sense to store less 14201 // two bytes in byte-reversed order. 14202 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 14203 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 14204 break; 14205 14206 SDValue BSwapOp = N->getOperand(1).getOperand(0); 14207 // Do an any-extend to 32-bits if this is a half-word input. 14208 if (BSwapOp.getValueType() == MVT::i16) 14209 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 14210 14211 // If the type of BSWAP operand is wider than stored memory width 14212 // it need to be shifted to the right side before STBRX. 14213 if (Op1VT.bitsGT(mVT)) { 14214 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 14215 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 14216 DAG.getConstant(Shift, dl, MVT::i32)); 14217 // Need to truncate if this is a bswap of i64 stored as i32/i16. 14218 if (Op1VT == MVT::i64) 14219 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 14220 } 14221 14222 SDValue Ops[] = { 14223 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 14224 }; 14225 return 14226 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 14227 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 14228 cast<StoreSDNode>(N)->getMemOperand()); 14229 } 14230 14231 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 14232 // So it can increase the chance of CSE constant construction. 14233 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 14234 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 14235 // Need to sign-extended to 64-bits to handle negative values. 14236 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 14237 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 14238 MemVT.getSizeInBits()); 14239 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 14240 14241 // DAG.getTruncStore() can't be used here because it doesn't accept 14242 // the general (base + offset) addressing mode. 14243 // So we use UpdateNodeOperands and setTruncatingStore instead. 14244 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 14245 N->getOperand(3)); 14246 cast<StoreSDNode>(N)->setTruncatingStore(true); 14247 return SDValue(N, 0); 14248 } 14249 14250 // For little endian, VSX stores require generating xxswapd/lxvd2x. 14251 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14252 if (Op1VT.isSimple()) { 14253 MVT StoreVT = Op1VT.getSimpleVT(); 14254 if (Subtarget.needsSwapsForVSXMemOps() && 14255 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 14256 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 14257 return expandVSXStoreForLE(N, DCI); 14258 } 14259 break; 14260 } 14261 case ISD::LOAD: { 14262 LoadSDNode *LD = cast<LoadSDNode>(N); 14263 EVT VT = LD->getValueType(0); 14264 14265 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14266 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14267 if (VT.isSimple()) { 14268 MVT LoadVT = VT.getSimpleVT(); 14269 if (Subtarget.needsSwapsForVSXMemOps() && 14270 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 14271 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 14272 return expandVSXLoadForLE(N, DCI); 14273 } 14274 14275 // We sometimes end up with a 64-bit integer load, from which we extract 14276 // two single-precision floating-point numbers. This happens with 14277 // std::complex<float>, and other similar structures, because of the way we 14278 // canonicalize structure copies. However, if we lack direct moves, 14279 // then the final bitcasts from the extracted integer values to the 14280 // floating-point numbers turn into store/load pairs. Even with direct moves, 14281 // just loading the two floating-point numbers is likely better. 14282 auto ReplaceTwoFloatLoad = [&]() { 14283 if (VT != MVT::i64) 14284 return false; 14285 14286 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 14287 LD->isVolatile()) 14288 return false; 14289 14290 // We're looking for a sequence like this: 14291 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 14292 // t16: i64 = srl t13, Constant:i32<32> 14293 // t17: i32 = truncate t16 14294 // t18: f32 = bitcast t17 14295 // t19: i32 = truncate t13 14296 // t20: f32 = bitcast t19 14297 14298 if (!LD->hasNUsesOfValue(2, 0)) 14299 return false; 14300 14301 auto UI = LD->use_begin(); 14302 while (UI.getUse().getResNo() != 0) ++UI; 14303 SDNode *Trunc = *UI++; 14304 while (UI.getUse().getResNo() != 0) ++UI; 14305 SDNode *RightShift = *UI; 14306 if (Trunc->getOpcode() != ISD::TRUNCATE) 14307 std::swap(Trunc, RightShift); 14308 14309 if (Trunc->getOpcode() != ISD::TRUNCATE || 14310 Trunc->getValueType(0) != MVT::i32 || 14311 !Trunc->hasOneUse()) 14312 return false; 14313 if (RightShift->getOpcode() != ISD::SRL || 14314 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 14315 RightShift->getConstantOperandVal(1) != 32 || 14316 !RightShift->hasOneUse()) 14317 return false; 14318 14319 SDNode *Trunc2 = *RightShift->use_begin(); 14320 if (Trunc2->getOpcode() != ISD::TRUNCATE || 14321 Trunc2->getValueType(0) != MVT::i32 || 14322 !Trunc2->hasOneUse()) 14323 return false; 14324 14325 SDNode *Bitcast = *Trunc->use_begin(); 14326 SDNode *Bitcast2 = *Trunc2->use_begin(); 14327 14328 if (Bitcast->getOpcode() != ISD::BITCAST || 14329 Bitcast->getValueType(0) != MVT::f32) 14330 return false; 14331 if (Bitcast2->getOpcode() != ISD::BITCAST || 14332 Bitcast2->getValueType(0) != MVT::f32) 14333 return false; 14334 14335 if (Subtarget.isLittleEndian()) 14336 std::swap(Bitcast, Bitcast2); 14337 14338 // Bitcast has the second float (in memory-layout order) and Bitcast2 14339 // has the first one. 14340 14341 SDValue BasePtr = LD->getBasePtr(); 14342 if (LD->isIndexed()) { 14343 assert(LD->getAddressingMode() == ISD::PRE_INC && 14344 "Non-pre-inc AM on PPC?"); 14345 BasePtr = 14346 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 14347 LD->getOffset()); 14348 } 14349 14350 auto MMOFlags = 14351 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 14352 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 14353 LD->getPointerInfo(), LD->getAlignment(), 14354 MMOFlags, LD->getAAInfo()); 14355 SDValue AddPtr = 14356 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 14357 BasePtr, DAG.getIntPtrConstant(4, dl)); 14358 SDValue FloatLoad2 = DAG.getLoad( 14359 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 14360 LD->getPointerInfo().getWithOffset(4), 14361 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 14362 14363 if (LD->isIndexed()) { 14364 // Note that DAGCombine should re-form any pre-increment load(s) from 14365 // what is produced here if that makes sense. 14366 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 14367 } 14368 14369 DCI.CombineTo(Bitcast2, FloatLoad); 14370 DCI.CombineTo(Bitcast, FloatLoad2); 14371 14372 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 14373 SDValue(FloatLoad2.getNode(), 1)); 14374 return true; 14375 }; 14376 14377 if (ReplaceTwoFloatLoad()) 14378 return SDValue(N, 0); 14379 14380 EVT MemVT = LD->getMemoryVT(); 14381 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 14382 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 14383 if (LD->isUnindexed() && VT.isVector() && 14384 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 14385 // P8 and later hardware should just use LOAD. 14386 !Subtarget.hasP8Vector() && 14387 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 14388 VT == MVT::v4f32))) && 14389 LD->getAlign() < ABIAlignment) { 14390 // This is a type-legal unaligned Altivec load. 14391 SDValue Chain = LD->getChain(); 14392 SDValue Ptr = LD->getBasePtr(); 14393 bool isLittleEndian = Subtarget.isLittleEndian(); 14394 14395 // This implements the loading of unaligned vectors as described in 14396 // the venerable Apple Velocity Engine overview. Specifically: 14397 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 14398 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 14399 // 14400 // The general idea is to expand a sequence of one or more unaligned 14401 // loads into an alignment-based permutation-control instruction (lvsl 14402 // or lvsr), a series of regular vector loads (which always truncate 14403 // their input address to an aligned address), and a series of 14404 // permutations. The results of these permutations are the requested 14405 // loaded values. The trick is that the last "extra" load is not taken 14406 // from the address you might suspect (sizeof(vector) bytes after the 14407 // last requested load), but rather sizeof(vector) - 1 bytes after the 14408 // last requested vector. The point of this is to avoid a page fault if 14409 // the base address happened to be aligned. This works because if the 14410 // base address is aligned, then adding less than a full vector length 14411 // will cause the last vector in the sequence to be (re)loaded. 14412 // Otherwise, the next vector will be fetched as you might suspect was 14413 // necessary. 14414 14415 // We might be able to reuse the permutation generation from 14416 // a different base address offset from this one by an aligned amount. 14417 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 14418 // optimization later. 14419 Intrinsic::ID Intr, IntrLD, IntrPerm; 14420 MVT PermCntlTy, PermTy, LDTy; 14421 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14422 : Intrinsic::ppc_altivec_lvsl; 14423 IntrLD = Intrinsic::ppc_altivec_lvx; 14424 IntrPerm = Intrinsic::ppc_altivec_vperm; 14425 PermCntlTy = MVT::v16i8; 14426 PermTy = MVT::v4i32; 14427 LDTy = MVT::v4i32; 14428 14429 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 14430 14431 // Create the new MMO for the new base load. It is like the original MMO, 14432 // but represents an area in memory almost twice the vector size centered 14433 // on the original address. If the address is unaligned, we might start 14434 // reading up to (sizeof(vector)-1) bytes below the address of the 14435 // original unaligned load. 14436 MachineFunction &MF = DAG.getMachineFunction(); 14437 MachineMemOperand *BaseMMO = 14438 MF.getMachineMemOperand(LD->getMemOperand(), 14439 -(long)MemVT.getStoreSize()+1, 14440 2*MemVT.getStoreSize()-1); 14441 14442 // Create the new base load. 14443 SDValue LDXIntID = 14444 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14445 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14446 SDValue BaseLoad = 14447 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14448 DAG.getVTList(PermTy, MVT::Other), 14449 BaseLoadOps, LDTy, BaseMMO); 14450 14451 // Note that the value of IncOffset (which is provided to the next 14452 // load's pointer info offset value, and thus used to calculate the 14453 // alignment), and the value of IncValue (which is actually used to 14454 // increment the pointer value) are different! This is because we 14455 // require the next load to appear to be aligned, even though it 14456 // is actually offset from the base pointer by a lesser amount. 14457 int IncOffset = VT.getSizeInBits() / 8; 14458 int IncValue = IncOffset; 14459 14460 // Walk (both up and down) the chain looking for another load at the real 14461 // (aligned) offset (the alignment of the other load does not matter in 14462 // this case). If found, then do not use the offset reduction trick, as 14463 // that will prevent the loads from being later combined (as they would 14464 // otherwise be duplicates). 14465 if (!findConsecutiveLoad(LD, DAG)) 14466 --IncValue; 14467 14468 SDValue Increment = 14469 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14470 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14471 14472 MachineMemOperand *ExtraMMO = 14473 MF.getMachineMemOperand(LD->getMemOperand(), 14474 1, 2*MemVT.getStoreSize()-1); 14475 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14476 SDValue ExtraLoad = 14477 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14478 DAG.getVTList(PermTy, MVT::Other), 14479 ExtraLoadOps, LDTy, ExtraMMO); 14480 14481 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14482 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14483 14484 // Because vperm has a big-endian bias, we must reverse the order 14485 // of the input vectors and complement the permute control vector 14486 // when generating little endian code. We have already handled the 14487 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14488 // and ExtraLoad here. 14489 SDValue Perm; 14490 if (isLittleEndian) 14491 Perm = BuildIntrinsicOp(IntrPerm, 14492 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14493 else 14494 Perm = BuildIntrinsicOp(IntrPerm, 14495 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14496 14497 if (VT != PermTy) 14498 Perm = Subtarget.hasAltivec() 14499 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 14500 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 14501 DAG.getTargetConstant(1, dl, MVT::i64)); 14502 // second argument is 1 because this rounding 14503 // is always exact. 14504 14505 // The output of the permutation is our loaded result, the TokenFactor is 14506 // our new chain. 14507 DCI.CombineTo(N, Perm, TF); 14508 return SDValue(N, 0); 14509 } 14510 } 14511 break; 14512 case ISD::INTRINSIC_WO_CHAIN: { 14513 bool isLittleEndian = Subtarget.isLittleEndian(); 14514 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14515 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14516 : Intrinsic::ppc_altivec_lvsl); 14517 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 14518 SDValue Add = N->getOperand(1); 14519 14520 int Bits = 4 /* 16 byte alignment */; 14521 14522 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14523 APInt::getAllOnesValue(Bits /* alignment */) 14524 .zext(Add.getScalarValueSizeInBits()))) { 14525 SDNode *BasePtr = Add->getOperand(0).getNode(); 14526 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14527 UE = BasePtr->use_end(); 14528 UI != UE; ++UI) { 14529 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14530 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == 14531 IID) { 14532 // We've found another LVSL/LVSR, and this address is an aligned 14533 // multiple of that one. The results will be the same, so use the 14534 // one we've just found instead. 14535 14536 return SDValue(*UI, 0); 14537 } 14538 } 14539 } 14540 14541 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14542 SDNode *BasePtr = Add->getOperand(0).getNode(); 14543 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14544 UE = BasePtr->use_end(); UI != UE; ++UI) { 14545 if (UI->getOpcode() == ISD::ADD && 14546 isa<ConstantSDNode>(UI->getOperand(1)) && 14547 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14548 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14549 (1ULL << Bits) == 0) { 14550 SDNode *OtherAdd = *UI; 14551 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14552 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14553 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14554 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14555 return SDValue(*VI, 0); 14556 } 14557 } 14558 } 14559 } 14560 } 14561 } 14562 14563 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14564 // Expose the vabsduw/h/b opportunity for down stream 14565 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14566 (IID == Intrinsic::ppc_altivec_vmaxsw || 14567 IID == Intrinsic::ppc_altivec_vmaxsh || 14568 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14569 SDValue V1 = N->getOperand(1); 14570 SDValue V2 = N->getOperand(2); 14571 if ((V1.getSimpleValueType() == MVT::v4i32 || 14572 V1.getSimpleValueType() == MVT::v8i16 || 14573 V1.getSimpleValueType() == MVT::v16i8) && 14574 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14575 // (0-a, a) 14576 if (V1.getOpcode() == ISD::SUB && 14577 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14578 V1.getOperand(1) == V2) { 14579 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14580 } 14581 // (a, 0-a) 14582 if (V2.getOpcode() == ISD::SUB && 14583 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14584 V2.getOperand(1) == V1) { 14585 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14586 } 14587 // (x-y, y-x) 14588 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14589 V1.getOperand(0) == V2.getOperand(1) && 14590 V1.getOperand(1) == V2.getOperand(0)) { 14591 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14592 } 14593 } 14594 } 14595 } 14596 14597 break; 14598 case ISD::INTRINSIC_W_CHAIN: 14599 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14600 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14601 if (Subtarget.needsSwapsForVSXMemOps()) { 14602 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14603 default: 14604 break; 14605 case Intrinsic::ppc_vsx_lxvw4x: 14606 case Intrinsic::ppc_vsx_lxvd2x: 14607 return expandVSXLoadForLE(N, DCI); 14608 } 14609 } 14610 break; 14611 case ISD::INTRINSIC_VOID: 14612 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14613 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14614 if (Subtarget.needsSwapsForVSXMemOps()) { 14615 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14616 default: 14617 break; 14618 case Intrinsic::ppc_vsx_stxvw4x: 14619 case Intrinsic::ppc_vsx_stxvd2x: 14620 return expandVSXStoreForLE(N, DCI); 14621 } 14622 } 14623 break; 14624 case ISD::BSWAP: 14625 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14626 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14627 N->getOperand(0).hasOneUse() && 14628 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14629 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14630 N->getValueType(0) == MVT::i64))) { 14631 SDValue Load = N->getOperand(0); 14632 LoadSDNode *LD = cast<LoadSDNode>(Load); 14633 // Create the byte-swapping load. 14634 SDValue Ops[] = { 14635 LD->getChain(), // Chain 14636 LD->getBasePtr(), // Ptr 14637 DAG.getValueType(N->getValueType(0)) // VT 14638 }; 14639 SDValue BSLoad = 14640 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14641 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14642 MVT::i64 : MVT::i32, MVT::Other), 14643 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14644 14645 // If this is an i16 load, insert the truncate. 14646 SDValue ResVal = BSLoad; 14647 if (N->getValueType(0) == MVT::i16) 14648 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14649 14650 // First, combine the bswap away. This makes the value produced by the 14651 // load dead. 14652 DCI.CombineTo(N, ResVal); 14653 14654 // Next, combine the load away, we give it a bogus result value but a real 14655 // chain result. The result value is dead because the bswap is dead. 14656 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14657 14658 // Return N so it doesn't get rechecked! 14659 return SDValue(N, 0); 14660 } 14661 break; 14662 case PPCISD::VCMP: 14663 // If a VCMPo node already exists with exactly the same operands as this 14664 // node, use its result instead of this node (VCMPo computes both a CR6 and 14665 // a normal output). 14666 // 14667 if (!N->getOperand(0).hasOneUse() && 14668 !N->getOperand(1).hasOneUse() && 14669 !N->getOperand(2).hasOneUse()) { 14670 14671 // Scan all of the users of the LHS, looking for VCMPo's that match. 14672 SDNode *VCMPoNode = nullptr; 14673 14674 SDNode *LHSN = N->getOperand(0).getNode(); 14675 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14676 UI != E; ++UI) 14677 if (UI->getOpcode() == PPCISD::VCMPo && 14678 UI->getOperand(1) == N->getOperand(1) && 14679 UI->getOperand(2) == N->getOperand(2) && 14680 UI->getOperand(0) == N->getOperand(0)) { 14681 VCMPoNode = *UI; 14682 break; 14683 } 14684 14685 // If there is no VCMPo node, or if the flag value has a single use, don't 14686 // transform this. 14687 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14688 break; 14689 14690 // Look at the (necessarily single) use of the flag value. If it has a 14691 // chain, this transformation is more complex. Note that multiple things 14692 // could use the value result, which we should ignore. 14693 SDNode *FlagUser = nullptr; 14694 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14695 FlagUser == nullptr; ++UI) { 14696 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14697 SDNode *User = *UI; 14698 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14699 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14700 FlagUser = User; 14701 break; 14702 } 14703 } 14704 } 14705 14706 // If the user is a MFOCRF instruction, we know this is safe. 14707 // Otherwise we give up for right now. 14708 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14709 return SDValue(VCMPoNode, 0); 14710 } 14711 break; 14712 case ISD::BRCOND: { 14713 SDValue Cond = N->getOperand(1); 14714 SDValue Target = N->getOperand(2); 14715 14716 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14717 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14718 Intrinsic::loop_decrement) { 14719 14720 // We now need to make the intrinsic dead (it cannot be instruction 14721 // selected). 14722 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14723 assert(Cond.getNode()->hasOneUse() && 14724 "Counter decrement has more than one use"); 14725 14726 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14727 N->getOperand(0), Target); 14728 } 14729 } 14730 break; 14731 case ISD::BR_CC: { 14732 // If this is a branch on an altivec predicate comparison, lower this so 14733 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14734 // lowering is done pre-legalize, because the legalizer lowers the predicate 14735 // compare down to code that is difficult to reassemble. 14736 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14737 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14738 14739 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14740 // value. If so, pass-through the AND to get to the intrinsic. 14741 if (LHS.getOpcode() == ISD::AND && 14742 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14743 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14744 Intrinsic::loop_decrement && 14745 isa<ConstantSDNode>(LHS.getOperand(1)) && 14746 !isNullConstant(LHS.getOperand(1))) 14747 LHS = LHS.getOperand(0); 14748 14749 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14750 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14751 Intrinsic::loop_decrement && 14752 isa<ConstantSDNode>(RHS)) { 14753 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14754 "Counter decrement comparison is not EQ or NE"); 14755 14756 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14757 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14758 (CC == ISD::SETNE && !Val); 14759 14760 // We now need to make the intrinsic dead (it cannot be instruction 14761 // selected). 14762 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14763 assert(LHS.getNode()->hasOneUse() && 14764 "Counter decrement has more than one use"); 14765 14766 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14767 N->getOperand(0), N->getOperand(4)); 14768 } 14769 14770 int CompareOpc; 14771 bool isDot; 14772 14773 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14774 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14775 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14776 assert(isDot && "Can't compare against a vector result!"); 14777 14778 // If this is a comparison against something other than 0/1, then we know 14779 // that the condition is never/always true. 14780 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14781 if (Val != 0 && Val != 1) { 14782 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14783 return N->getOperand(0); 14784 // Always !=, turn it into an unconditional branch. 14785 return DAG.getNode(ISD::BR, dl, MVT::Other, 14786 N->getOperand(0), N->getOperand(4)); 14787 } 14788 14789 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14790 14791 // Create the PPCISD altivec 'dot' comparison node. 14792 SDValue Ops[] = { 14793 LHS.getOperand(2), // LHS of compare 14794 LHS.getOperand(3), // RHS of compare 14795 DAG.getConstant(CompareOpc, dl, MVT::i32) 14796 }; 14797 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14798 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14799 14800 // Unpack the result based on how the target uses it. 14801 PPC::Predicate CompOpc; 14802 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14803 default: // Can't happen, don't crash on invalid number though. 14804 case 0: // Branch on the value of the EQ bit of CR6. 14805 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14806 break; 14807 case 1: // Branch on the inverted value of the EQ bit of CR6. 14808 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14809 break; 14810 case 2: // Branch on the value of the LT bit of CR6. 14811 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14812 break; 14813 case 3: // Branch on the inverted value of the LT bit of CR6. 14814 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14815 break; 14816 } 14817 14818 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14819 DAG.getConstant(CompOpc, dl, MVT::i32), 14820 DAG.getRegister(PPC::CR6, MVT::i32), 14821 N->getOperand(4), CompNode.getValue(1)); 14822 } 14823 break; 14824 } 14825 case ISD::BUILD_VECTOR: 14826 return DAGCombineBuildVector(N, DCI); 14827 case ISD::ABS: 14828 return combineABS(N, DCI); 14829 case ISD::VSELECT: 14830 return combineVSelect(N, DCI); 14831 } 14832 14833 return SDValue(); 14834 } 14835 14836 SDValue 14837 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14838 SelectionDAG &DAG, 14839 SmallVectorImpl<SDNode *> &Created) const { 14840 // fold (sdiv X, pow2) 14841 EVT VT = N->getValueType(0); 14842 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14843 return SDValue(); 14844 if ((VT != MVT::i32 && VT != MVT::i64) || 14845 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14846 return SDValue(); 14847 14848 SDLoc DL(N); 14849 SDValue N0 = N->getOperand(0); 14850 14851 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14852 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14853 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14854 14855 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14856 Created.push_back(Op.getNode()); 14857 14858 if (IsNegPow2) { 14859 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14860 Created.push_back(Op.getNode()); 14861 } 14862 14863 return Op; 14864 } 14865 14866 //===----------------------------------------------------------------------===// 14867 // Inline Assembly Support 14868 //===----------------------------------------------------------------------===// 14869 14870 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14871 KnownBits &Known, 14872 const APInt &DemandedElts, 14873 const SelectionDAG &DAG, 14874 unsigned Depth) const { 14875 Known.resetAll(); 14876 switch (Op.getOpcode()) { 14877 default: break; 14878 case PPCISD::LBRX: { 14879 // lhbrx is known to have the top bits cleared out. 14880 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14881 Known.Zero = 0xFFFF0000; 14882 break; 14883 } 14884 case ISD::INTRINSIC_WO_CHAIN: { 14885 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14886 default: break; 14887 case Intrinsic::ppc_altivec_vcmpbfp_p: 14888 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14889 case Intrinsic::ppc_altivec_vcmpequb_p: 14890 case Intrinsic::ppc_altivec_vcmpequh_p: 14891 case Intrinsic::ppc_altivec_vcmpequw_p: 14892 case Intrinsic::ppc_altivec_vcmpequd_p: 14893 case Intrinsic::ppc_altivec_vcmpgefp_p: 14894 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14895 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14896 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14897 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14898 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14899 case Intrinsic::ppc_altivec_vcmpgtub_p: 14900 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14901 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14902 case Intrinsic::ppc_altivec_vcmpgtud_p: 14903 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14904 break; 14905 } 14906 } 14907 } 14908 } 14909 14910 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14911 switch (Subtarget.getCPUDirective()) { 14912 default: break; 14913 case PPC::DIR_970: 14914 case PPC::DIR_PWR4: 14915 case PPC::DIR_PWR5: 14916 case PPC::DIR_PWR5X: 14917 case PPC::DIR_PWR6: 14918 case PPC::DIR_PWR6X: 14919 case PPC::DIR_PWR7: 14920 case PPC::DIR_PWR8: 14921 case PPC::DIR_PWR9: 14922 case PPC::DIR_PWR10: 14923 case PPC::DIR_PWR_FUTURE: { 14924 if (!ML) 14925 break; 14926 14927 if (!DisableInnermostLoopAlign32) { 14928 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14929 // so that we can decrease cache misses and branch-prediction misses. 14930 // Actual alignment of the loop will depend on the hotness check and other 14931 // logic in alignBlocks. 14932 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14933 return Align(32); 14934 } 14935 14936 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14937 14938 // For small loops (between 5 and 8 instructions), align to a 32-byte 14939 // boundary so that the entire loop fits in one instruction-cache line. 14940 uint64_t LoopSize = 0; 14941 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14942 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14943 LoopSize += TII->getInstSizeInBytes(*J); 14944 if (LoopSize > 32) 14945 break; 14946 } 14947 14948 if (LoopSize > 16 && LoopSize <= 32) 14949 return Align(32); 14950 14951 break; 14952 } 14953 } 14954 14955 return TargetLowering::getPrefLoopAlignment(ML); 14956 } 14957 14958 /// getConstraintType - Given a constraint, return the type of 14959 /// constraint it is for this target. 14960 PPCTargetLowering::ConstraintType 14961 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14962 if (Constraint.size() == 1) { 14963 switch (Constraint[0]) { 14964 default: break; 14965 case 'b': 14966 case 'r': 14967 case 'f': 14968 case 'd': 14969 case 'v': 14970 case 'y': 14971 return C_RegisterClass; 14972 case 'Z': 14973 // FIXME: While Z does indicate a memory constraint, it specifically 14974 // indicates an r+r address (used in conjunction with the 'y' modifier 14975 // in the replacement string). Currently, we're forcing the base 14976 // register to be r0 in the asm printer (which is interpreted as zero) 14977 // and forming the complete address in the second register. This is 14978 // suboptimal. 14979 return C_Memory; 14980 } 14981 } else if (Constraint == "wc") { // individual CR bits. 14982 return C_RegisterClass; 14983 } else if (Constraint == "wa" || Constraint == "wd" || 14984 Constraint == "wf" || Constraint == "ws" || 14985 Constraint == "wi" || Constraint == "ww") { 14986 return C_RegisterClass; // VSX registers. 14987 } 14988 return TargetLowering::getConstraintType(Constraint); 14989 } 14990 14991 /// Examine constraint type and operand type and determine a weight value. 14992 /// This object must already have been set up with the operand type 14993 /// and the current alternative constraint selected. 14994 TargetLowering::ConstraintWeight 14995 PPCTargetLowering::getSingleConstraintMatchWeight( 14996 AsmOperandInfo &info, const char *constraint) const { 14997 ConstraintWeight weight = CW_Invalid; 14998 Value *CallOperandVal = info.CallOperandVal; 14999 // If we don't have a value, we can't do a match, 15000 // but allow it at the lowest weight. 15001 if (!CallOperandVal) 15002 return CW_Default; 15003 Type *type = CallOperandVal->getType(); 15004 15005 // Look at the constraint type. 15006 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 15007 return CW_Register; // an individual CR bit. 15008 else if ((StringRef(constraint) == "wa" || 15009 StringRef(constraint) == "wd" || 15010 StringRef(constraint) == "wf") && 15011 type->isVectorTy()) 15012 return CW_Register; 15013 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 15014 return CW_Register; // just hold 64-bit integers data. 15015 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 15016 return CW_Register; 15017 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 15018 return CW_Register; 15019 15020 switch (*constraint) { 15021 default: 15022 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15023 break; 15024 case 'b': 15025 if (type->isIntegerTy()) 15026 weight = CW_Register; 15027 break; 15028 case 'f': 15029 if (type->isFloatTy()) 15030 weight = CW_Register; 15031 break; 15032 case 'd': 15033 if (type->isDoubleTy()) 15034 weight = CW_Register; 15035 break; 15036 case 'v': 15037 if (type->isVectorTy()) 15038 weight = CW_Register; 15039 break; 15040 case 'y': 15041 weight = CW_Register; 15042 break; 15043 case 'Z': 15044 weight = CW_Memory; 15045 break; 15046 } 15047 return weight; 15048 } 15049 15050 std::pair<unsigned, const TargetRegisterClass *> 15051 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 15052 StringRef Constraint, 15053 MVT VT) const { 15054 if (Constraint.size() == 1) { 15055 // GCC RS6000 Constraint Letters 15056 switch (Constraint[0]) { 15057 case 'b': // R1-R31 15058 if (VT == MVT::i64 && Subtarget.isPPC64()) 15059 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 15060 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 15061 case 'r': // R0-R31 15062 if (VT == MVT::i64 && Subtarget.isPPC64()) 15063 return std::make_pair(0U, &PPC::G8RCRegClass); 15064 return std::make_pair(0U, &PPC::GPRCRegClass); 15065 // 'd' and 'f' constraints are both defined to be "the floating point 15066 // registers", where one is for 32-bit and the other for 64-bit. We don't 15067 // really care overly much here so just give them all the same reg classes. 15068 case 'd': 15069 case 'f': 15070 if (Subtarget.hasSPE()) { 15071 if (VT == MVT::f32 || VT == MVT::i32) 15072 return std::make_pair(0U, &PPC::GPRCRegClass); 15073 if (VT == MVT::f64 || VT == MVT::i64) 15074 return std::make_pair(0U, &PPC::SPERCRegClass); 15075 } else { 15076 if (VT == MVT::f32 || VT == MVT::i32) 15077 return std::make_pair(0U, &PPC::F4RCRegClass); 15078 if (VT == MVT::f64 || VT == MVT::i64) 15079 return std::make_pair(0U, &PPC::F8RCRegClass); 15080 } 15081 break; 15082 case 'v': 15083 if (Subtarget.hasAltivec()) 15084 return std::make_pair(0U, &PPC::VRRCRegClass); 15085 break; 15086 case 'y': // crrc 15087 return std::make_pair(0U, &PPC::CRRCRegClass); 15088 } 15089 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 15090 // An individual CR bit. 15091 return std::make_pair(0U, &PPC::CRBITRCRegClass); 15092 } else if ((Constraint == "wa" || Constraint == "wd" || 15093 Constraint == "wf" || Constraint == "wi") && 15094 Subtarget.hasVSX()) { 15095 return std::make_pair(0U, &PPC::VSRCRegClass); 15096 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 15097 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 15098 return std::make_pair(0U, &PPC::VSSRCRegClass); 15099 else 15100 return std::make_pair(0U, &PPC::VSFRCRegClass); 15101 } 15102 15103 // If we name a VSX register, we can't defer to the base class because it 15104 // will not recognize the correct register (their names will be VSL{0-31} 15105 // and V{0-31} so they won't match). So we match them here. 15106 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 15107 int VSNum = atoi(Constraint.data() + 3); 15108 assert(VSNum >= 0 && VSNum <= 63 && 15109 "Attempted to access a vsr out of range"); 15110 if (VSNum < 32) 15111 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 15112 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 15113 } 15114 std::pair<unsigned, const TargetRegisterClass *> R = 15115 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 15116 15117 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 15118 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 15119 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 15120 // register. 15121 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 15122 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 15123 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 15124 PPC::GPRCRegClass.contains(R.first)) 15125 return std::make_pair(TRI->getMatchingSuperReg(R.first, 15126 PPC::sub_32, &PPC::G8RCRegClass), 15127 &PPC::G8RCRegClass); 15128 15129 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 15130 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 15131 R.first = PPC::CR0; 15132 R.second = &PPC::CRRCRegClass; 15133 } 15134 15135 return R; 15136 } 15137 15138 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15139 /// vector. If it is invalid, don't add anything to Ops. 15140 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15141 std::string &Constraint, 15142 std::vector<SDValue>&Ops, 15143 SelectionDAG &DAG) const { 15144 SDValue Result; 15145 15146 // Only support length 1 constraints. 15147 if (Constraint.length() > 1) return; 15148 15149 char Letter = Constraint[0]; 15150 switch (Letter) { 15151 default: break; 15152 case 'I': 15153 case 'J': 15154 case 'K': 15155 case 'L': 15156 case 'M': 15157 case 'N': 15158 case 'O': 15159 case 'P': { 15160 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 15161 if (!CST) return; // Must be an immediate to match. 15162 SDLoc dl(Op); 15163 int64_t Value = CST->getSExtValue(); 15164 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 15165 // numbers are printed as such. 15166 switch (Letter) { 15167 default: llvm_unreachable("Unknown constraint letter!"); 15168 case 'I': // "I" is a signed 16-bit constant. 15169 if (isInt<16>(Value)) 15170 Result = DAG.getTargetConstant(Value, dl, TCVT); 15171 break; 15172 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 15173 if (isShiftedUInt<16, 16>(Value)) 15174 Result = DAG.getTargetConstant(Value, dl, TCVT); 15175 break; 15176 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 15177 if (isShiftedInt<16, 16>(Value)) 15178 Result = DAG.getTargetConstant(Value, dl, TCVT); 15179 break; 15180 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 15181 if (isUInt<16>(Value)) 15182 Result = DAG.getTargetConstant(Value, dl, TCVT); 15183 break; 15184 case 'M': // "M" is a constant that is greater than 31. 15185 if (Value > 31) 15186 Result = DAG.getTargetConstant(Value, dl, TCVT); 15187 break; 15188 case 'N': // "N" is a positive constant that is an exact power of two. 15189 if (Value > 0 && isPowerOf2_64(Value)) 15190 Result = DAG.getTargetConstant(Value, dl, TCVT); 15191 break; 15192 case 'O': // "O" is the constant zero. 15193 if (Value == 0) 15194 Result = DAG.getTargetConstant(Value, dl, TCVT); 15195 break; 15196 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 15197 if (isInt<16>(-Value)) 15198 Result = DAG.getTargetConstant(Value, dl, TCVT); 15199 break; 15200 } 15201 break; 15202 } 15203 } 15204 15205 if (Result.getNode()) { 15206 Ops.push_back(Result); 15207 return; 15208 } 15209 15210 // Handle standard constraint letters. 15211 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15212 } 15213 15214 // isLegalAddressingMode - Return true if the addressing mode represented 15215 // by AM is legal for this target, for a load/store of the specified type. 15216 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 15217 const AddrMode &AM, Type *Ty, 15218 unsigned AS, 15219 Instruction *I) const { 15220 // Vector type r+i form is supported since power9 as DQ form. We don't check 15221 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 15222 // imm form is preferred and the offset can be adjusted to use imm form later 15223 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 15224 // max offset to check legal addressing mode, we should be a little aggressive 15225 // to contain other offsets for that LSRUse. 15226 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 15227 return false; 15228 15229 // PPC allows a sign-extended 16-bit immediate field. 15230 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 15231 return false; 15232 15233 // No global is ever allowed as a base. 15234 if (AM.BaseGV) 15235 return false; 15236 15237 // PPC only support r+r, 15238 switch (AM.Scale) { 15239 case 0: // "r+i" or just "i", depending on HasBaseReg. 15240 break; 15241 case 1: 15242 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 15243 return false; 15244 // Otherwise we have r+r or r+i. 15245 break; 15246 case 2: 15247 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 15248 return false; 15249 // Allow 2*r as r+r. 15250 break; 15251 default: 15252 // No other scales are supported. 15253 return false; 15254 } 15255 15256 return true; 15257 } 15258 15259 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 15260 SelectionDAG &DAG) const { 15261 MachineFunction &MF = DAG.getMachineFunction(); 15262 MachineFrameInfo &MFI = MF.getFrameInfo(); 15263 MFI.setReturnAddressIsTaken(true); 15264 15265 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 15266 return SDValue(); 15267 15268 SDLoc dl(Op); 15269 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15270 15271 // Make sure the function does not optimize away the store of the RA to 15272 // the stack. 15273 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 15274 FuncInfo->setLRStoreRequired(); 15275 bool isPPC64 = Subtarget.isPPC64(); 15276 auto PtrVT = getPointerTy(MF.getDataLayout()); 15277 15278 if (Depth > 0) { 15279 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 15280 SDValue Offset = 15281 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 15282 isPPC64 ? MVT::i64 : MVT::i32); 15283 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 15284 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 15285 MachinePointerInfo()); 15286 } 15287 15288 // Just load the return address off the stack. 15289 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 15290 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 15291 MachinePointerInfo()); 15292 } 15293 15294 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 15295 SelectionDAG &DAG) const { 15296 SDLoc dl(Op); 15297 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15298 15299 MachineFunction &MF = DAG.getMachineFunction(); 15300 MachineFrameInfo &MFI = MF.getFrameInfo(); 15301 MFI.setFrameAddressIsTaken(true); 15302 15303 EVT PtrVT = getPointerTy(MF.getDataLayout()); 15304 bool isPPC64 = PtrVT == MVT::i64; 15305 15306 // Naked functions never have a frame pointer, and so we use r1. For all 15307 // other functions, this decision must be delayed until during PEI. 15308 unsigned FrameReg; 15309 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 15310 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 15311 else 15312 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 15313 15314 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 15315 PtrVT); 15316 while (Depth--) 15317 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 15318 FrameAddr, MachinePointerInfo()); 15319 return FrameAddr; 15320 } 15321 15322 // FIXME? Maybe this could be a TableGen attribute on some registers and 15323 // this table could be generated automatically from RegInfo. 15324 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 15325 const MachineFunction &MF) const { 15326 bool isPPC64 = Subtarget.isPPC64(); 15327 15328 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 15329 if (!is64Bit && VT != LLT::scalar(32)) 15330 report_fatal_error("Invalid register global variable type"); 15331 15332 Register Reg = StringSwitch<Register>(RegName) 15333 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 15334 .Case("r2", isPPC64 ? Register() : PPC::R2) 15335 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 15336 .Default(Register()); 15337 15338 if (Reg) 15339 return Reg; 15340 report_fatal_error("Invalid register name global variable"); 15341 } 15342 15343 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 15344 // 32-bit SVR4 ABI access everything as got-indirect. 15345 if (Subtarget.is32BitELFABI()) 15346 return true; 15347 15348 // AIX accesses everything indirectly through the TOC, which is similar to 15349 // the GOT. 15350 if (Subtarget.isAIXABI()) 15351 return true; 15352 15353 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 15354 // If it is small or large code model, module locals are accessed 15355 // indirectly by loading their address from .toc/.got. 15356 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 15357 return true; 15358 15359 // JumpTable and BlockAddress are accessed as got-indirect. 15360 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 15361 return true; 15362 15363 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 15364 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 15365 15366 return false; 15367 } 15368 15369 bool 15370 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 15371 // The PowerPC target isn't yet aware of offsets. 15372 return false; 15373 } 15374 15375 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 15376 const CallInst &I, 15377 MachineFunction &MF, 15378 unsigned Intrinsic) const { 15379 switch (Intrinsic) { 15380 case Intrinsic::ppc_altivec_lvx: 15381 case Intrinsic::ppc_altivec_lvxl: 15382 case Intrinsic::ppc_altivec_lvebx: 15383 case Intrinsic::ppc_altivec_lvehx: 15384 case Intrinsic::ppc_altivec_lvewx: 15385 case Intrinsic::ppc_vsx_lxvd2x: 15386 case Intrinsic::ppc_vsx_lxvw4x: { 15387 EVT VT; 15388 switch (Intrinsic) { 15389 case Intrinsic::ppc_altivec_lvebx: 15390 VT = MVT::i8; 15391 break; 15392 case Intrinsic::ppc_altivec_lvehx: 15393 VT = MVT::i16; 15394 break; 15395 case Intrinsic::ppc_altivec_lvewx: 15396 VT = MVT::i32; 15397 break; 15398 case Intrinsic::ppc_vsx_lxvd2x: 15399 VT = MVT::v2f64; 15400 break; 15401 default: 15402 VT = MVT::v4i32; 15403 break; 15404 } 15405 15406 Info.opc = ISD::INTRINSIC_W_CHAIN; 15407 Info.memVT = VT; 15408 Info.ptrVal = I.getArgOperand(0); 15409 Info.offset = -VT.getStoreSize()+1; 15410 Info.size = 2*VT.getStoreSize()-1; 15411 Info.align = Align(1); 15412 Info.flags = MachineMemOperand::MOLoad; 15413 return true; 15414 } 15415 case Intrinsic::ppc_altivec_stvx: 15416 case Intrinsic::ppc_altivec_stvxl: 15417 case Intrinsic::ppc_altivec_stvebx: 15418 case Intrinsic::ppc_altivec_stvehx: 15419 case Intrinsic::ppc_altivec_stvewx: 15420 case Intrinsic::ppc_vsx_stxvd2x: 15421 case Intrinsic::ppc_vsx_stxvw4x: { 15422 EVT VT; 15423 switch (Intrinsic) { 15424 case Intrinsic::ppc_altivec_stvebx: 15425 VT = MVT::i8; 15426 break; 15427 case Intrinsic::ppc_altivec_stvehx: 15428 VT = MVT::i16; 15429 break; 15430 case Intrinsic::ppc_altivec_stvewx: 15431 VT = MVT::i32; 15432 break; 15433 case Intrinsic::ppc_vsx_stxvd2x: 15434 VT = MVT::v2f64; 15435 break; 15436 default: 15437 VT = MVT::v4i32; 15438 break; 15439 } 15440 15441 Info.opc = ISD::INTRINSIC_VOID; 15442 Info.memVT = VT; 15443 Info.ptrVal = I.getArgOperand(1); 15444 Info.offset = -VT.getStoreSize()+1; 15445 Info.size = 2*VT.getStoreSize()-1; 15446 Info.align = Align(1); 15447 Info.flags = MachineMemOperand::MOStore; 15448 return true; 15449 } 15450 default: 15451 break; 15452 } 15453 15454 return false; 15455 } 15456 15457 /// It returns EVT::Other if the type should be determined using generic 15458 /// target-independent logic. 15459 EVT PPCTargetLowering::getOptimalMemOpType( 15460 const MemOp &Op, const AttributeList &FuncAttributes) const { 15461 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15462 // We should use Altivec/VSX loads and stores when available. For unaligned 15463 // addresses, unaligned VSX loads are only fast starting with the P8. 15464 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15465 (Op.isAligned(Align(16)) || 15466 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15467 return MVT::v4i32; 15468 } 15469 15470 if (Subtarget.isPPC64()) { 15471 return MVT::i64; 15472 } 15473 15474 return MVT::i32; 15475 } 15476 15477 /// Returns true if it is beneficial to convert a load of a constant 15478 /// to just the constant itself. 15479 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15480 Type *Ty) const { 15481 assert(Ty->isIntegerTy()); 15482 15483 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15484 return !(BitSize == 0 || BitSize > 64); 15485 } 15486 15487 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15488 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15489 return false; 15490 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15491 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15492 return NumBits1 == 64 && NumBits2 == 32; 15493 } 15494 15495 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15496 if (!VT1.isInteger() || !VT2.isInteger()) 15497 return false; 15498 unsigned NumBits1 = VT1.getSizeInBits(); 15499 unsigned NumBits2 = VT2.getSizeInBits(); 15500 return NumBits1 == 64 && NumBits2 == 32; 15501 } 15502 15503 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15504 // Generally speaking, zexts are not free, but they are free when they can be 15505 // folded with other operations. 15506 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15507 EVT MemVT = LD->getMemoryVT(); 15508 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15509 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15510 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15511 LD->getExtensionType() == ISD::ZEXTLOAD)) 15512 return true; 15513 } 15514 15515 // FIXME: Add other cases... 15516 // - 32-bit shifts with a zext to i64 15517 // - zext after ctlz, bswap, etc. 15518 // - zext after and by a constant mask 15519 15520 return TargetLowering::isZExtFree(Val, VT2); 15521 } 15522 15523 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15524 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15525 "invalid fpext types"); 15526 // Extending to float128 is not free. 15527 if (DestVT == MVT::f128) 15528 return false; 15529 return true; 15530 } 15531 15532 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15533 return isInt<16>(Imm) || isUInt<16>(Imm); 15534 } 15535 15536 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15537 return isInt<16>(Imm) || isUInt<16>(Imm); 15538 } 15539 15540 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15541 unsigned, 15542 unsigned, 15543 MachineMemOperand::Flags, 15544 bool *Fast) const { 15545 if (DisablePPCUnaligned) 15546 return false; 15547 15548 // PowerPC supports unaligned memory access for simple non-vector types. 15549 // Although accessing unaligned addresses is not as efficient as accessing 15550 // aligned addresses, it is generally more efficient than manual expansion, 15551 // and generally only traps for software emulation when crossing page 15552 // boundaries. 15553 15554 if (!VT.isSimple()) 15555 return false; 15556 15557 if (VT.isFloatingPoint() && !VT.isVector() && 15558 !Subtarget.allowsUnalignedFPAccess()) 15559 return false; 15560 15561 if (VT.getSimpleVT().isVector()) { 15562 if (Subtarget.hasVSX()) { 15563 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15564 VT != MVT::v4f32 && VT != MVT::v4i32) 15565 return false; 15566 } else { 15567 return false; 15568 } 15569 } 15570 15571 if (VT == MVT::ppcf128) 15572 return false; 15573 15574 if (Fast) 15575 *Fast = true; 15576 15577 return true; 15578 } 15579 15580 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15581 EVT VT) const { 15582 return isFMAFasterThanFMulAndFAdd( 15583 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 15584 } 15585 15586 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 15587 Type *Ty) const { 15588 switch (Ty->getScalarType()->getTypeID()) { 15589 case Type::FloatTyID: 15590 case Type::DoubleTyID: 15591 return true; 15592 case Type::FP128TyID: 15593 return Subtarget.hasP9Vector(); 15594 default: 15595 return false; 15596 } 15597 } 15598 15599 // FIXME: add more patterns which are not profitable to hoist. 15600 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 15601 if (!I->hasOneUse()) 15602 return true; 15603 15604 Instruction *User = I->user_back(); 15605 assert(User && "A single use instruction with no uses."); 15606 15607 switch (I->getOpcode()) { 15608 case Instruction::FMul: { 15609 // Don't break FMA, PowerPC prefers FMA. 15610 if (User->getOpcode() != Instruction::FSub && 15611 User->getOpcode() != Instruction::FAdd) 15612 return true; 15613 15614 const TargetOptions &Options = getTargetMachine().Options; 15615 const Function *F = I->getFunction(); 15616 const DataLayout &DL = F->getParent()->getDataLayout(); 15617 Type *Ty = User->getOperand(0)->getType(); 15618 15619 return !( 15620 isFMAFasterThanFMulAndFAdd(*F, Ty) && 15621 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 15622 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 15623 } 15624 case Instruction::Load: { 15625 // Don't break "store (load float*)" pattern, this pattern will be combined 15626 // to "store (load int32)" in later InstCombine pass. See function 15627 // combineLoadToOperationType. On PowerPC, loading a float point takes more 15628 // cycles than loading a 32 bit integer. 15629 LoadInst *LI = cast<LoadInst>(I); 15630 // For the loads that combineLoadToOperationType does nothing, like 15631 // ordered load, it should be profitable to hoist them. 15632 // For swifterror load, it can only be used for pointer to pointer type, so 15633 // later type check should get rid of this case. 15634 if (!LI->isUnordered()) 15635 return true; 15636 15637 if (User->getOpcode() != Instruction::Store) 15638 return true; 15639 15640 if (I->getType()->getTypeID() != Type::FloatTyID) 15641 return true; 15642 15643 return false; 15644 } 15645 default: 15646 return true; 15647 } 15648 return true; 15649 } 15650 15651 const MCPhysReg * 15652 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15653 // LR is a callee-save register, but we must treat it as clobbered by any call 15654 // site. Hence we include LR in the scratch registers, which are in turn added 15655 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15656 // to CTR, which is used by any indirect call. 15657 static const MCPhysReg ScratchRegs[] = { 15658 PPC::X12, PPC::LR8, PPC::CTR8, 0 15659 }; 15660 15661 return ScratchRegs; 15662 } 15663 15664 Register PPCTargetLowering::getExceptionPointerRegister( 15665 const Constant *PersonalityFn) const { 15666 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15667 } 15668 15669 Register PPCTargetLowering::getExceptionSelectorRegister( 15670 const Constant *PersonalityFn) const { 15671 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15672 } 15673 15674 bool 15675 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15676 EVT VT , unsigned DefinedValues) const { 15677 if (VT == MVT::v2i64) 15678 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15679 15680 if (Subtarget.hasVSX()) 15681 return true; 15682 15683 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15684 } 15685 15686 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15687 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15688 return TargetLowering::getSchedulingPreference(N); 15689 15690 return Sched::ILP; 15691 } 15692 15693 // Create a fast isel object. 15694 FastISel * 15695 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15696 const TargetLibraryInfo *LibInfo) const { 15697 return PPC::createFastISel(FuncInfo, LibInfo); 15698 } 15699 15700 // 'Inverted' means the FMA opcode after negating one multiplicand. 15701 // For example, (fma -a b c) = (fnmsub a b c) 15702 static unsigned invertFMAOpcode(unsigned Opc) { 15703 switch (Opc) { 15704 default: 15705 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 15706 case ISD::FMA: 15707 return PPCISD::FNMSUB; 15708 case PPCISD::FNMSUB: 15709 return ISD::FMA; 15710 } 15711 } 15712 15713 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 15714 bool LegalOps, bool OptForSize, 15715 NegatibleCost &Cost, 15716 unsigned Depth) const { 15717 if (Depth > SelectionDAG::MaxRecursionDepth) 15718 return SDValue(); 15719 15720 unsigned Opc = Op.getOpcode(); 15721 EVT VT = Op.getValueType(); 15722 SDNodeFlags Flags = Op.getNode()->getFlags(); 15723 15724 switch (Opc) { 15725 case PPCISD::FNMSUB: 15726 if (!Op.hasOneUse() || !isTypeLegal(VT)) 15727 break; 15728 15729 const TargetOptions &Options = getTargetMachine().Options; 15730 SDValue N0 = Op.getOperand(0); 15731 SDValue N1 = Op.getOperand(1); 15732 SDValue N2 = Op.getOperand(2); 15733 SDLoc Loc(Op); 15734 15735 NegatibleCost N2Cost = NegatibleCost::Expensive; 15736 SDValue NegN2 = 15737 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 15738 15739 if (!NegN2) 15740 return SDValue(); 15741 15742 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 15743 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 15744 // These transformations may change sign of zeroes. For example, 15745 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 15746 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 15747 // Try and choose the cheaper one to negate. 15748 NegatibleCost N0Cost = NegatibleCost::Expensive; 15749 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 15750 N0Cost, Depth + 1); 15751 15752 NegatibleCost N1Cost = NegatibleCost::Expensive; 15753 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 15754 N1Cost, Depth + 1); 15755 15756 if (NegN0 && N0Cost <= N1Cost) { 15757 Cost = std::min(N0Cost, N2Cost); 15758 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 15759 } else if (NegN1) { 15760 Cost = std::min(N1Cost, N2Cost); 15761 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 15762 } 15763 } 15764 15765 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 15766 if (isOperationLegal(ISD::FMA, VT)) { 15767 Cost = N2Cost; 15768 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 15769 } 15770 15771 break; 15772 } 15773 15774 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 15775 Cost, Depth); 15776 } 15777 15778 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15779 bool PPCTargetLowering::useLoadStackGuardNode() const { 15780 if (!Subtarget.isTargetLinux()) 15781 return TargetLowering::useLoadStackGuardNode(); 15782 return true; 15783 } 15784 15785 // Override to disable global variable loading on Linux. 15786 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15787 if (!Subtarget.isTargetLinux()) 15788 return TargetLowering::insertSSPDeclarations(M); 15789 } 15790 15791 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15792 bool ForCodeSize) const { 15793 if (!VT.isSimple() || !Subtarget.hasVSX()) 15794 return false; 15795 15796 switch(VT.getSimpleVT().SimpleTy) { 15797 default: 15798 // For FP types that are currently not supported by PPC backend, return 15799 // false. Examples: f16, f80. 15800 return false; 15801 case MVT::f32: 15802 case MVT::f64: 15803 if (Subtarget.hasPrefixInstrs()) { 15804 // With prefixed instructions, we can materialize anything that can be 15805 // represented with a 32-bit immediate, not just positive zero. 15806 APFloat APFloatOfImm = Imm; 15807 return convertToNonDenormSingle(APFloatOfImm); 15808 } 15809 LLVM_FALLTHROUGH; 15810 case MVT::ppcf128: 15811 return Imm.isPosZero(); 15812 } 15813 } 15814 15815 // For vector shift operation op, fold 15816 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15817 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15818 SelectionDAG &DAG) { 15819 SDValue N0 = N->getOperand(0); 15820 SDValue N1 = N->getOperand(1); 15821 EVT VT = N0.getValueType(); 15822 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15823 unsigned Opcode = N->getOpcode(); 15824 unsigned TargetOpcode; 15825 15826 switch (Opcode) { 15827 default: 15828 llvm_unreachable("Unexpected shift operation"); 15829 case ISD::SHL: 15830 TargetOpcode = PPCISD::SHL; 15831 break; 15832 case ISD::SRL: 15833 TargetOpcode = PPCISD::SRL; 15834 break; 15835 case ISD::SRA: 15836 TargetOpcode = PPCISD::SRA; 15837 break; 15838 } 15839 15840 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15841 N1->getOpcode() == ISD::AND) 15842 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15843 if (Mask->getZExtValue() == OpSizeInBits - 1) 15844 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15845 15846 return SDValue(); 15847 } 15848 15849 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15850 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15851 return Value; 15852 15853 SDValue N0 = N->getOperand(0); 15854 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15855 if (!Subtarget.isISA3_0() || 15856 N0.getOpcode() != ISD::SIGN_EXTEND || 15857 N0.getOperand(0).getValueType() != MVT::i32 || 15858 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15859 return SDValue(); 15860 15861 // We can't save an operation here if the value is already extended, and 15862 // the existing shift is easier to combine. 15863 SDValue ExtsSrc = N0.getOperand(0); 15864 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15865 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15866 return SDValue(); 15867 15868 SDLoc DL(N0); 15869 SDValue ShiftBy = SDValue(CN1, 0); 15870 // We want the shift amount to be i32 on the extswli, but the shift could 15871 // have an i64. 15872 if (ShiftBy.getValueType() == MVT::i64) 15873 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15874 15875 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15876 ShiftBy); 15877 } 15878 15879 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15880 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15881 return Value; 15882 15883 return SDValue(); 15884 } 15885 15886 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15887 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15888 return Value; 15889 15890 return SDValue(); 15891 } 15892 15893 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15894 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15895 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15896 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15897 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15898 const PPCSubtarget &Subtarget) { 15899 if (!Subtarget.isPPC64()) 15900 return SDValue(); 15901 15902 SDValue LHS = N->getOperand(0); 15903 SDValue RHS = N->getOperand(1); 15904 15905 auto isZextOfCompareWithConstant = [](SDValue Op) { 15906 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15907 Op.getValueType() != MVT::i64) 15908 return false; 15909 15910 SDValue Cmp = Op.getOperand(0); 15911 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15912 Cmp.getOperand(0).getValueType() != MVT::i64) 15913 return false; 15914 15915 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15916 int64_t NegConstant = 0 - Constant->getSExtValue(); 15917 // Due to the limitations of the addi instruction, 15918 // -C is required to be [-32768, 32767]. 15919 return isInt<16>(NegConstant); 15920 } 15921 15922 return false; 15923 }; 15924 15925 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15926 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15927 15928 // If there is a pattern, canonicalize a zext operand to the RHS. 15929 if (LHSHasPattern && !RHSHasPattern) 15930 std::swap(LHS, RHS); 15931 else if (!LHSHasPattern && !RHSHasPattern) 15932 return SDValue(); 15933 15934 SDLoc DL(N); 15935 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15936 SDValue Cmp = RHS.getOperand(0); 15937 SDValue Z = Cmp.getOperand(0); 15938 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15939 15940 assert(Constant && "Constant Should not be a null pointer."); 15941 int64_t NegConstant = 0 - Constant->getSExtValue(); 15942 15943 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15944 default: break; 15945 case ISD::SETNE: { 15946 // when C == 0 15947 // --> addze X, (addic Z, -1).carry 15948 // / 15949 // add X, (zext(setne Z, C))-- 15950 // \ when -32768 <= -C <= 32767 && C != 0 15951 // --> addze X, (addic (addi Z, -C), -1).carry 15952 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15953 DAG.getConstant(NegConstant, DL, MVT::i64)); 15954 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15955 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15956 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15957 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15958 SDValue(Addc.getNode(), 1)); 15959 } 15960 case ISD::SETEQ: { 15961 // when C == 0 15962 // --> addze X, (subfic Z, 0).carry 15963 // / 15964 // add X, (zext(sete Z, C))-- 15965 // \ when -32768 <= -C <= 32767 && C != 0 15966 // --> addze X, (subfic (addi Z, -C), 0).carry 15967 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15968 DAG.getConstant(NegConstant, DL, MVT::i64)); 15969 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15970 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15971 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15972 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15973 SDValue(Subc.getNode(), 1)); 15974 } 15975 } 15976 15977 return SDValue(); 15978 } 15979 15980 // Transform 15981 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 15982 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 15983 // In this case both C1 and C2 must be known constants. 15984 // C1+C2 must fit into a 34 bit signed integer. 15985 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 15986 const PPCSubtarget &Subtarget) { 15987 if (!Subtarget.isUsingPCRelativeCalls()) 15988 return SDValue(); 15989 15990 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 15991 // If we find that node try to cast the Global Address and the Constant. 15992 SDValue LHS = N->getOperand(0); 15993 SDValue RHS = N->getOperand(1); 15994 15995 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15996 std::swap(LHS, RHS); 15997 15998 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 15999 return SDValue(); 16000 16001 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 16002 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 16003 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 16004 16005 // Check that both casts succeeded. 16006 if (!GSDN || !ConstNode) 16007 return SDValue(); 16008 16009 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 16010 SDLoc DL(GSDN); 16011 16012 // The signed int offset needs to fit in 34 bits. 16013 if (!isInt<34>(NewOffset)) 16014 return SDValue(); 16015 16016 // The new global address is a copy of the old global address except 16017 // that it has the updated Offset. 16018 SDValue GA = 16019 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 16020 NewOffset, GSDN->getTargetFlags()); 16021 SDValue MatPCRel = 16022 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 16023 return MatPCRel; 16024 } 16025 16026 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 16027 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 16028 return Value; 16029 16030 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 16031 return Value; 16032 16033 return SDValue(); 16034 } 16035 16036 // Detect TRUNCATE operations on bitcasts of float128 values. 16037 // What we are looking for here is the situtation where we extract a subset 16038 // of bits from a 128 bit float. 16039 // This can be of two forms: 16040 // 1) BITCAST of f128 feeding TRUNCATE 16041 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 16042 // The reason this is required is because we do not have a legal i128 type 16043 // and so we want to prevent having to store the f128 and then reload part 16044 // of it. 16045 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 16046 DAGCombinerInfo &DCI) const { 16047 // If we are using CRBits then try that first. 16048 if (Subtarget.useCRBits()) { 16049 // Check if CRBits did anything and return that if it did. 16050 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 16051 return CRTruncValue; 16052 } 16053 16054 SDLoc dl(N); 16055 SDValue Op0 = N->getOperand(0); 16056 16057 // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b) 16058 if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) { 16059 EVT VT = N->getValueType(0); 16060 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16061 return SDValue(); 16062 SDValue Sub = Op0.getOperand(0); 16063 if (Sub.getOpcode() == ISD::SUB) { 16064 SDValue SubOp0 = Sub.getOperand(0); 16065 SDValue SubOp1 = Sub.getOperand(1); 16066 if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) && 16067 (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) { 16068 return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0), 16069 SubOp1.getOperand(0), 16070 DCI.DAG.getTargetConstant(0, dl, MVT::i32)); 16071 } 16072 } 16073 } 16074 16075 // Looking for a truncate of i128 to i64. 16076 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 16077 return SDValue(); 16078 16079 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 16080 16081 // SRL feeding TRUNCATE. 16082 if (Op0.getOpcode() == ISD::SRL) { 16083 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 16084 // The right shift has to be by 64 bits. 16085 if (!ConstNode || ConstNode->getZExtValue() != 64) 16086 return SDValue(); 16087 16088 // Switch the element number to extract. 16089 EltToExtract = EltToExtract ? 0 : 1; 16090 // Update Op0 past the SRL. 16091 Op0 = Op0.getOperand(0); 16092 } 16093 16094 // BITCAST feeding a TRUNCATE possibly via SRL. 16095 if (Op0.getOpcode() == ISD::BITCAST && 16096 Op0.getValueType() == MVT::i128 && 16097 Op0.getOperand(0).getValueType() == MVT::f128) { 16098 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 16099 return DCI.DAG.getNode( 16100 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 16101 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 16102 } 16103 return SDValue(); 16104 } 16105 16106 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 16107 SelectionDAG &DAG = DCI.DAG; 16108 16109 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 16110 if (!ConstOpOrElement) 16111 return SDValue(); 16112 16113 // An imul is usually smaller than the alternative sequence for legal type. 16114 if (DAG.getMachineFunction().getFunction().hasMinSize() && 16115 isOperationLegal(ISD::MUL, N->getValueType(0))) 16116 return SDValue(); 16117 16118 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 16119 switch (this->Subtarget.getCPUDirective()) { 16120 default: 16121 // TODO: enhance the condition for subtarget before pwr8 16122 return false; 16123 case PPC::DIR_PWR8: 16124 // type mul add shl 16125 // scalar 4 1 1 16126 // vector 7 2 2 16127 return true; 16128 case PPC::DIR_PWR9: 16129 case PPC::DIR_PWR10: 16130 case PPC::DIR_PWR_FUTURE: 16131 // type mul add shl 16132 // scalar 5 2 2 16133 // vector 7 2 2 16134 16135 // The cycle RATIO of related operations are showed as a table above. 16136 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 16137 // scalar and vector type. For 2 instrs patterns, add/sub + shl 16138 // are 4, it is always profitable; but for 3 instrs patterns 16139 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 16140 // So we should only do it for vector type. 16141 return IsAddOne && IsNeg ? VT.isVector() : true; 16142 } 16143 }; 16144 16145 EVT VT = N->getValueType(0); 16146 SDLoc DL(N); 16147 16148 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 16149 bool IsNeg = MulAmt.isNegative(); 16150 APInt MulAmtAbs = MulAmt.abs(); 16151 16152 if ((MulAmtAbs - 1).isPowerOf2()) { 16153 // (mul x, 2^N + 1) => (add (shl x, N), x) 16154 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 16155 16156 if (!IsProfitable(IsNeg, true, VT)) 16157 return SDValue(); 16158 16159 SDValue Op0 = N->getOperand(0); 16160 SDValue Op1 = 16161 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16162 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 16163 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 16164 16165 if (!IsNeg) 16166 return Res; 16167 16168 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 16169 } else if ((MulAmtAbs + 1).isPowerOf2()) { 16170 // (mul x, 2^N - 1) => (sub (shl x, N), x) 16171 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 16172 16173 if (!IsProfitable(IsNeg, false, VT)) 16174 return SDValue(); 16175 16176 SDValue Op0 = N->getOperand(0); 16177 SDValue Op1 = 16178 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16179 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 16180 16181 if (!IsNeg) 16182 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 16183 else 16184 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 16185 16186 } else { 16187 return SDValue(); 16188 } 16189 } 16190 16191 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 16192 // in combiner since we need to check SD flags and other subtarget features. 16193 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 16194 DAGCombinerInfo &DCI) const { 16195 SDValue N0 = N->getOperand(0); 16196 SDValue N1 = N->getOperand(1); 16197 SDValue N2 = N->getOperand(2); 16198 SDNodeFlags Flags = N->getFlags(); 16199 EVT VT = N->getValueType(0); 16200 SelectionDAG &DAG = DCI.DAG; 16201 const TargetOptions &Options = getTargetMachine().Options; 16202 unsigned Opc = N->getOpcode(); 16203 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 16204 bool LegalOps = !DCI.isBeforeLegalizeOps(); 16205 SDLoc Loc(N); 16206 16207 if (!isOperationLegal(ISD::FMA, VT)) 16208 return SDValue(); 16209 16210 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 16211 // since (fnmsub a b c)=-0 while c-ab=+0. 16212 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 16213 return SDValue(); 16214 16215 // (fma (fneg a) b c) => (fnmsub a b c) 16216 // (fnmsub (fneg a) b c) => (fma a b c) 16217 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 16218 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 16219 16220 // (fma a (fneg b) c) => (fnmsub a b c) 16221 // (fnmsub a (fneg b) c) => (fma a b c) 16222 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 16223 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 16224 16225 return SDValue(); 16226 } 16227 16228 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 16229 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 16230 if (!Subtarget.is64BitELFABI()) 16231 return false; 16232 16233 // If not a tail call then no need to proceed. 16234 if (!CI->isTailCall()) 16235 return false; 16236 16237 // If sibling calls have been disabled and tail-calls aren't guaranteed 16238 // there is no reason to duplicate. 16239 auto &TM = getTargetMachine(); 16240 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 16241 return false; 16242 16243 // Can't tail call a function called indirectly, or if it has variadic args. 16244 const Function *Callee = CI->getCalledFunction(); 16245 if (!Callee || Callee->isVarArg()) 16246 return false; 16247 16248 // Make sure the callee and caller calling conventions are eligible for tco. 16249 const Function *Caller = CI->getParent()->getParent(); 16250 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 16251 CI->getCallingConv())) 16252 return false; 16253 16254 // If the function is local then we have a good chance at tail-calling it 16255 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 16256 } 16257 16258 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 16259 if (!Subtarget.hasVSX()) 16260 return false; 16261 if (Subtarget.hasP9Vector() && VT == MVT::f128) 16262 return true; 16263 return VT == MVT::f32 || VT == MVT::f64 || 16264 VT == MVT::v4f32 || VT == MVT::v2f64; 16265 } 16266 16267 bool PPCTargetLowering:: 16268 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 16269 const Value *Mask = AndI.getOperand(1); 16270 // If the mask is suitable for andi. or andis. we should sink the and. 16271 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 16272 // Can't handle constants wider than 64-bits. 16273 if (CI->getBitWidth() > 64) 16274 return false; 16275 int64_t ConstVal = CI->getZExtValue(); 16276 return isUInt<16>(ConstVal) || 16277 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 16278 } 16279 16280 // For non-constant masks, we can always use the record-form and. 16281 return true; 16282 } 16283 16284 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 16285 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 16286 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 16287 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 16288 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 16289 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 16290 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 16291 assert(Subtarget.hasP9Altivec() && 16292 "Only combine this when P9 altivec supported!"); 16293 EVT VT = N->getValueType(0); 16294 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16295 return SDValue(); 16296 16297 SelectionDAG &DAG = DCI.DAG; 16298 SDLoc dl(N); 16299 if (N->getOperand(0).getOpcode() == ISD::SUB) { 16300 // Even for signed integers, if it's known to be positive (as signed 16301 // integer) due to zero-extended inputs. 16302 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 16303 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 16304 if ((SubOpcd0 == ISD::ZERO_EXTEND || 16305 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 16306 (SubOpcd1 == ISD::ZERO_EXTEND || 16307 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 16308 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16309 N->getOperand(0)->getOperand(0), 16310 N->getOperand(0)->getOperand(1), 16311 DAG.getTargetConstant(0, dl, MVT::i32)); 16312 } 16313 16314 // For type v4i32, it can be optimized with xvnegsp + vabsduw 16315 if (N->getOperand(0).getValueType() == MVT::v4i32 && 16316 N->getOperand(0).hasOneUse()) { 16317 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 16318 N->getOperand(0)->getOperand(0), 16319 N->getOperand(0)->getOperand(1), 16320 DAG.getTargetConstant(1, dl, MVT::i32)); 16321 } 16322 } 16323 16324 return SDValue(); 16325 } 16326 16327 // For type v4i32/v8ii16/v16i8, transform 16328 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 16329 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 16330 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 16331 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 16332 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 16333 DAGCombinerInfo &DCI) const { 16334 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 16335 assert(Subtarget.hasP9Altivec() && 16336 "Only combine this when P9 altivec supported!"); 16337 16338 SelectionDAG &DAG = DCI.DAG; 16339 SDLoc dl(N); 16340 SDValue Cond = N->getOperand(0); 16341 SDValue TrueOpnd = N->getOperand(1); 16342 SDValue FalseOpnd = N->getOperand(2); 16343 EVT VT = N->getOperand(1).getValueType(); 16344 16345 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 16346 FalseOpnd.getOpcode() != ISD::SUB) 16347 return SDValue(); 16348 16349 // ABSD only available for type v4i32/v8i16/v16i8 16350 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 16351 return SDValue(); 16352 16353 // At least to save one more dependent computation 16354 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 16355 return SDValue(); 16356 16357 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16358 16359 // Can only handle unsigned comparison here 16360 switch (CC) { 16361 default: 16362 return SDValue(); 16363 case ISD::SETUGT: 16364 case ISD::SETUGE: 16365 break; 16366 case ISD::SETULT: 16367 case ISD::SETULE: 16368 std::swap(TrueOpnd, FalseOpnd); 16369 break; 16370 } 16371 16372 SDValue CmpOpnd1 = Cond.getOperand(0); 16373 SDValue CmpOpnd2 = Cond.getOperand(1); 16374 16375 // SETCC CmpOpnd1 CmpOpnd2 cond 16376 // TrueOpnd = CmpOpnd1 - CmpOpnd2 16377 // FalseOpnd = CmpOpnd2 - CmpOpnd1 16378 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 16379 TrueOpnd.getOperand(1) == CmpOpnd2 && 16380 FalseOpnd.getOperand(0) == CmpOpnd2 && 16381 FalseOpnd.getOperand(1) == CmpOpnd1) { 16382 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 16383 CmpOpnd1, CmpOpnd2, 16384 DAG.getTargetConstant(0, dl, MVT::i32)); 16385 } 16386 16387 return SDValue(); 16388 } 16389