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/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetLowering.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/CallSite.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/Constant.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DerivedTypes.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/Intrinsics.h" 68 #include "llvm/IR/Module.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/MC/MCExpr.h" 73 #include "llvm/MC/MCRegisterInfo.h" 74 #include "llvm/Support/AtomicOrdering.h" 75 #include "llvm/Support/BranchProbability.h" 76 #include "llvm/Support/Casting.h" 77 #include "llvm/Support/CodeGen.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Compiler.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/ErrorHandling.h" 82 #include "llvm/Support/Format.h" 83 #include "llvm/Support/KnownBits.h" 84 #include "llvm/Support/MachineValueType.h" 85 #include "llvm/Support/MathExtras.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstdint> 92 #include <iterator> 93 #include <list> 94 #include <utility> 95 #include <vector> 96 97 using namespace llvm; 98 99 #define DEBUG_TYPE "ppc-lowering" 100 101 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 102 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 103 104 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 105 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 108 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisableSCO("disable-ppc-sco", 111 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 112 113 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 114 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 115 116 STATISTIC(NumTailCalls, "Number of tail calls"); 117 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 118 119 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 120 121 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 122 123 // FIXME: Remove this once the bug has been fixed! 124 extern cl::opt<bool> ANDIGlueBug; 125 126 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 127 const PPCSubtarget &STI) 128 : TargetLowering(TM), Subtarget(STI) { 129 // Use _setjmp/_longjmp instead of setjmp/longjmp. 130 setUseUnderscoreSetJmp(true); 131 setUseUnderscoreLongJmp(true); 132 133 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 134 // arguments are at least 4/8 bytes aligned. 135 bool isPPC64 = Subtarget.isPPC64(); 136 setMinStackArgumentAlignment(isPPC64 ? 8:4); 137 138 // Set up the register classes. 139 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 140 if (!useSoftFloat()) { 141 if (hasSPE()) { 142 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 143 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 144 } else { 145 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 146 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 147 } 148 } 149 150 // Match BITREVERSE to customized fast code sequence in the td file. 151 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 152 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 153 154 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 155 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 156 157 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 158 for (MVT VT : MVT::integer_valuetypes()) { 159 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 160 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 161 } 162 163 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 164 165 // PowerPC has pre-inc load and store's. 166 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 167 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 168 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 169 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 170 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 171 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 172 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 173 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 174 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 175 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 176 if (!Subtarget.hasSPE()) { 177 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 178 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 181 } 182 183 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 184 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 185 for (MVT VT : ScalarIntVTs) { 186 setOperationAction(ISD::ADDC, VT, Legal); 187 setOperationAction(ISD::ADDE, VT, Legal); 188 setOperationAction(ISD::SUBC, VT, Legal); 189 setOperationAction(ISD::SUBE, VT, Legal); 190 } 191 192 if (Subtarget.useCRBits()) { 193 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 194 195 if (isPPC64 || Subtarget.hasFPCVT()) { 196 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 197 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 198 isPPC64 ? MVT::i64 : MVT::i32); 199 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 200 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 201 isPPC64 ? MVT::i64 : MVT::i32); 202 } else { 203 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 204 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 205 } 206 207 // PowerPC does not support direct load/store of condition registers. 208 setOperationAction(ISD::LOAD, MVT::i1, Custom); 209 setOperationAction(ISD::STORE, MVT::i1, Custom); 210 211 // FIXME: Remove this once the ANDI glue bug is fixed: 212 if (ANDIGlueBug) 213 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 214 215 for (MVT VT : MVT::integer_valuetypes()) { 216 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 217 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 218 setTruncStoreAction(VT, MVT::i1, Expand); 219 } 220 221 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 222 } 223 224 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 225 // PPC (the libcall is not available). 226 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 227 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 228 229 // We do not currently implement these libm ops for PowerPC. 230 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 231 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 232 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 233 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 234 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 235 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 236 237 // PowerPC has no SREM/UREM instructions unless we are on P9 238 // On P9 we may use a hardware instruction to compute the remainder. 239 // The instructions are not legalized directly because in the cases where the 240 // result of both the remainder and the division is required it is more 241 // efficient to compute the remainder from the result of the division rather 242 // than use the remainder instruction. 243 if (Subtarget.isISA3_0()) { 244 setOperationAction(ISD::SREM, MVT::i32, Custom); 245 setOperationAction(ISD::UREM, MVT::i32, Custom); 246 setOperationAction(ISD::SREM, MVT::i64, Custom); 247 setOperationAction(ISD::UREM, MVT::i64, Custom); 248 } else { 249 setOperationAction(ISD::SREM, MVT::i32, Expand); 250 setOperationAction(ISD::UREM, MVT::i32, Expand); 251 setOperationAction(ISD::SREM, MVT::i64, Expand); 252 setOperationAction(ISD::UREM, MVT::i64, Expand); 253 } 254 255 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 256 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 257 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 258 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 259 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 260 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 261 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 262 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 263 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 264 265 // We don't support sin/cos/sqrt/fmod/pow 266 setOperationAction(ISD::FSIN , MVT::f64, Expand); 267 setOperationAction(ISD::FCOS , MVT::f64, Expand); 268 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 269 setOperationAction(ISD::FREM , MVT::f64, Expand); 270 setOperationAction(ISD::FPOW , MVT::f64, Expand); 271 setOperationAction(ISD::FSIN , MVT::f32, Expand); 272 setOperationAction(ISD::FCOS , MVT::f32, Expand); 273 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 274 setOperationAction(ISD::FREM , MVT::f32, Expand); 275 setOperationAction(ISD::FPOW , MVT::f32, Expand); 276 if (Subtarget.hasSPE()) { 277 setOperationAction(ISD::FMA , MVT::f64, Expand); 278 setOperationAction(ISD::FMA , MVT::f32, Expand); 279 } else { 280 setOperationAction(ISD::FMA , MVT::f64, Legal); 281 setOperationAction(ISD::FMA , MVT::f32, Legal); 282 } 283 284 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 285 286 // If we're enabling GP optimizations, use hardware square root 287 if (!Subtarget.hasFSQRT() && 288 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 289 Subtarget.hasFRE())) 290 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 291 292 if (!Subtarget.hasFSQRT() && 293 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 294 Subtarget.hasFRES())) 295 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 296 297 if (Subtarget.hasFCPSGN()) { 298 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 299 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 300 } else { 301 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 302 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 303 } 304 305 if (Subtarget.hasFPRND()) { 306 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 307 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 308 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 309 setOperationAction(ISD::FROUND, MVT::f64, Legal); 310 311 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 312 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 313 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 314 setOperationAction(ISD::FROUND, MVT::f32, Legal); 315 } 316 317 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 318 // to speed up scalar BSWAP64. 319 // CTPOP or CTTZ were introduced in P8/P9 respectively 320 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 321 if (Subtarget.hasP9Vector()) 322 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 323 else 324 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 325 if (Subtarget.isISA3_0()) { 326 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 327 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 328 } else { 329 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 330 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 331 } 332 333 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 334 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 335 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 336 } else { 337 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 338 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 339 } 340 341 // PowerPC does not have ROTR 342 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 343 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 344 345 if (!Subtarget.useCRBits()) { 346 // PowerPC does not have Select 347 setOperationAction(ISD::SELECT, MVT::i32, Expand); 348 setOperationAction(ISD::SELECT, MVT::i64, Expand); 349 setOperationAction(ISD::SELECT, MVT::f32, Expand); 350 setOperationAction(ISD::SELECT, MVT::f64, Expand); 351 } 352 353 // PowerPC wants to turn select_cc of FP into fsel when possible. 354 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 355 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 356 357 // PowerPC wants to optimize integer setcc a bit 358 if (!Subtarget.useCRBits()) 359 setOperationAction(ISD::SETCC, MVT::i32, Custom); 360 361 // PowerPC does not have BRCOND which requires SetCC 362 if (!Subtarget.useCRBits()) 363 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 364 365 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 366 367 if (Subtarget.hasSPE()) { 368 // SPE has built-in conversions 369 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 370 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 371 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 372 } else { 373 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 374 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 375 376 // PowerPC does not have [U|S]INT_TO_FP 377 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 378 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 379 } 380 381 if (Subtarget.hasDirectMove() && isPPC64) { 382 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 383 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 384 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 385 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 386 } else { 387 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 388 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 389 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 390 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 391 } 392 393 // We cannot sextinreg(i1). Expand to shifts. 394 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 395 396 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 397 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 398 // support continuation, user-level threading, and etc.. As a result, no 399 // other SjLj exception interfaces are implemented and please don't build 400 // your own exception handling based on them. 401 // LLVM/Clang supports zero-cost DWARF exception handling. 402 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 403 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 404 405 // We want to legalize GlobalAddress and ConstantPool nodes into the 406 // appropriate instructions to materialize the address. 407 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 408 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 409 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 410 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 411 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 412 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 413 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 414 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 415 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 416 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 417 418 // TRAP is legal. 419 setOperationAction(ISD::TRAP, MVT::Other, Legal); 420 421 // TRAMPOLINE is custom lowered. 422 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 423 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 424 425 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 426 setOperationAction(ISD::VASTART , MVT::Other, Custom); 427 428 if (Subtarget.isSVR4ABI()) { 429 if (isPPC64) { 430 // VAARG always uses double-word chunks, so promote anything smaller. 431 setOperationAction(ISD::VAARG, MVT::i1, Promote); 432 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 433 setOperationAction(ISD::VAARG, MVT::i8, Promote); 434 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 435 setOperationAction(ISD::VAARG, MVT::i16, Promote); 436 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 437 setOperationAction(ISD::VAARG, MVT::i32, Promote); 438 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 439 setOperationAction(ISD::VAARG, MVT::Other, Expand); 440 } else { 441 // VAARG is custom lowered with the 32-bit SVR4 ABI. 442 setOperationAction(ISD::VAARG, MVT::Other, Custom); 443 setOperationAction(ISD::VAARG, MVT::i64, Custom); 444 } 445 } else 446 setOperationAction(ISD::VAARG, MVT::Other, Expand); 447 448 if (Subtarget.isSVR4ABI() && !isPPC64) 449 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 450 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 451 else 452 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 453 454 // Use the default implementation. 455 setOperationAction(ISD::VAEND , MVT::Other, Expand); 456 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 457 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 458 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 459 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 460 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 461 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 462 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 463 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 464 465 // We want to custom lower some of our intrinsics. 466 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 467 468 // To handle counter-based loop conditions. 469 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 470 471 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 472 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 473 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 474 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 475 476 // Comparisons that require checking two conditions. 477 if (Subtarget.hasSPE()) { 478 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 479 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 480 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 481 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 482 } 483 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 484 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 485 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 486 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 487 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 488 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 489 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 495 496 if (Subtarget.has64BitSupport()) { 497 // They also have instructions for converting between i64 and fp. 498 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 499 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 500 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 501 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 502 // This is just the low 32 bits of a (signed) fp->i64 conversion. 503 // We cannot do this with Promote because i64 is not a legal type. 504 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 505 506 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 507 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 508 } else { 509 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 510 if (Subtarget.hasSPE()) 511 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 512 else 513 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 514 } 515 516 // With the instructions enabled under FPCVT, we can do everything. 517 if (Subtarget.hasFPCVT()) { 518 if (Subtarget.has64BitSupport()) { 519 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 520 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 521 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 522 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 523 } 524 525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 526 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 527 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 528 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 529 } 530 531 if (Subtarget.use64BitRegs()) { 532 // 64-bit PowerPC implementations can support i64 types directly 533 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 534 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 535 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 536 // 64-bit PowerPC wants to expand i128 shifts itself. 537 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 538 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 539 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 540 } else { 541 // 32-bit PowerPC wants to expand i64 shifts itself. 542 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 543 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 544 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 545 } 546 547 if (Subtarget.hasAltivec()) { 548 // First set operation action for all vector types to expand. Then we 549 // will selectively turn on ones that can be effectively codegen'd. 550 for (MVT VT : MVT::vector_valuetypes()) { 551 // add/sub are legal for all supported vector VT's. 552 setOperationAction(ISD::ADD, VT, Legal); 553 setOperationAction(ISD::SUB, VT, Legal); 554 555 // Vector instructions introduced in P8 556 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 557 setOperationAction(ISD::CTPOP, VT, Legal); 558 setOperationAction(ISD::CTLZ, VT, Legal); 559 } 560 else { 561 setOperationAction(ISD::CTPOP, VT, Expand); 562 setOperationAction(ISD::CTLZ, VT, Expand); 563 } 564 565 // Vector instructions introduced in P9 566 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 567 setOperationAction(ISD::CTTZ, VT, Legal); 568 else 569 setOperationAction(ISD::CTTZ, VT, Expand); 570 571 // We promote all shuffles to v16i8. 572 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 573 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 574 575 // We promote all non-typed operations to v4i32. 576 setOperationAction(ISD::AND , VT, Promote); 577 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 578 setOperationAction(ISD::OR , VT, Promote); 579 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 580 setOperationAction(ISD::XOR , VT, Promote); 581 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 582 setOperationAction(ISD::LOAD , VT, Promote); 583 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 584 setOperationAction(ISD::SELECT, VT, Promote); 585 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 586 setOperationAction(ISD::VSELECT, VT, Legal); 587 setOperationAction(ISD::SELECT_CC, VT, Promote); 588 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 589 setOperationAction(ISD::STORE, VT, Promote); 590 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 591 592 // No other operations are legal. 593 setOperationAction(ISD::MUL , VT, Expand); 594 setOperationAction(ISD::SDIV, VT, Expand); 595 setOperationAction(ISD::SREM, VT, Expand); 596 setOperationAction(ISD::UDIV, VT, Expand); 597 setOperationAction(ISD::UREM, VT, Expand); 598 setOperationAction(ISD::FDIV, VT, Expand); 599 setOperationAction(ISD::FREM, VT, Expand); 600 setOperationAction(ISD::FNEG, VT, Expand); 601 setOperationAction(ISD::FSQRT, VT, Expand); 602 setOperationAction(ISD::FLOG, VT, Expand); 603 setOperationAction(ISD::FLOG10, VT, Expand); 604 setOperationAction(ISD::FLOG2, VT, Expand); 605 setOperationAction(ISD::FEXP, VT, Expand); 606 setOperationAction(ISD::FEXP2, VT, Expand); 607 setOperationAction(ISD::FSIN, VT, Expand); 608 setOperationAction(ISD::FCOS, VT, Expand); 609 setOperationAction(ISD::FABS, VT, Expand); 610 setOperationAction(ISD::FFLOOR, VT, Expand); 611 setOperationAction(ISD::FCEIL, VT, Expand); 612 setOperationAction(ISD::FTRUNC, VT, Expand); 613 setOperationAction(ISD::FRINT, VT, Expand); 614 setOperationAction(ISD::FNEARBYINT, VT, Expand); 615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 616 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 617 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 618 setOperationAction(ISD::MULHU, VT, Expand); 619 setOperationAction(ISD::MULHS, VT, Expand); 620 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 621 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 622 setOperationAction(ISD::UDIVREM, VT, Expand); 623 setOperationAction(ISD::SDIVREM, VT, Expand); 624 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 625 setOperationAction(ISD::FPOW, VT, Expand); 626 setOperationAction(ISD::BSWAP, VT, Expand); 627 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 628 setOperationAction(ISD::ROTL, VT, Expand); 629 setOperationAction(ISD::ROTR, VT, Expand); 630 631 for (MVT InnerVT : MVT::vector_valuetypes()) { 632 setTruncStoreAction(VT, InnerVT, Expand); 633 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 634 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 635 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 636 } 637 } 638 639 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 640 setOperationAction(ISD::ABS, VT, Custom); 641 642 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 643 // with merges, splats, etc. 644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 645 646 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 647 // are cheap, so handle them before they get expanded to scalar. 648 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 649 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 650 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 651 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 652 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 653 654 setOperationAction(ISD::AND , MVT::v4i32, Legal); 655 setOperationAction(ISD::OR , MVT::v4i32, Legal); 656 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 657 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 658 setOperationAction(ISD::SELECT, MVT::v4i32, 659 Subtarget.useCRBits() ? Legal : Expand); 660 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 661 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 662 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 663 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 664 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 665 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 666 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 667 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 668 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 669 670 // Without hasP8Altivec set, v2i64 SMAX isn't available. 671 // But ABS custom lowering requires SMAX support. 672 if (!Subtarget.hasP8Altivec()) 673 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 674 675 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 676 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 677 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 678 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 679 680 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 681 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 682 683 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 684 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 685 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 686 } 687 688 if (Subtarget.hasP8Altivec()) 689 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 690 else 691 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 692 693 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 694 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 695 696 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 697 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 698 699 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 700 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 701 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 702 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 703 704 // Altivec does not contain unordered floating-point compare instructions 705 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 706 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 707 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 708 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 709 710 if (Subtarget.hasVSX()) { 711 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 713 if (Subtarget.hasP8Vector()) { 714 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 716 } 717 if (Subtarget.hasDirectMove() && isPPC64) { 718 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 719 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 720 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 722 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 724 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 725 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 726 } 727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 728 729 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 730 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 731 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 732 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 733 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 734 735 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 736 737 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 738 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 739 740 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 741 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 742 743 // Share the Altivec comparison restrictions. 744 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 745 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 746 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 747 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 748 749 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 750 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 751 752 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 753 754 if (Subtarget.hasP8Vector()) 755 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 756 757 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 758 759 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 760 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 761 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 762 763 if (Subtarget.hasP8Altivec()) { 764 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 765 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 766 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 767 768 // 128 bit shifts can be accomplished via 3 instructions for SHL and 769 // SRL, but not for SRA because of the instructions available: 770 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 771 // doing 772 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 773 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 774 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 775 776 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 777 } 778 else { 779 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 780 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 781 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 782 783 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 784 785 // VSX v2i64 only supports non-arithmetic operations. 786 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 787 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 788 } 789 790 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 791 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 792 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 793 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 794 795 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 796 797 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 798 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 799 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 800 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 801 802 // Custom handling for partial vectors of integers converted to 803 // floating point. We already have optimal handling for v2i32 through 804 // the DAG combine, so those aren't necessary. 805 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 806 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 807 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 808 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 809 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 810 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 811 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 812 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 813 814 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 815 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 816 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 817 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 818 819 if (Subtarget.hasDirectMove()) 820 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 821 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 822 823 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 824 } 825 826 if (Subtarget.hasP8Altivec()) { 827 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 828 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 829 } 830 831 if (Subtarget.hasP9Vector()) { 832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 834 835 // 128 bit shifts can be accomplished via 3 instructions for SHL and 836 // SRL, but not for SRA because of the instructions available: 837 // VS{RL} and VS{RL}O. 838 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 839 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 840 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 841 842 if (EnableQuadPrecision) { 843 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 844 setOperationAction(ISD::FADD, MVT::f128, Legal); 845 setOperationAction(ISD::FSUB, MVT::f128, Legal); 846 setOperationAction(ISD::FDIV, MVT::f128, Legal); 847 setOperationAction(ISD::FMUL, MVT::f128, Legal); 848 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 849 // No extending loads to f128 on PPC. 850 for (MVT FPT : MVT::fp_valuetypes()) 851 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 852 setOperationAction(ISD::FMA, MVT::f128, Legal); 853 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 854 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 855 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 856 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 857 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 858 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 859 860 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 861 setOperationAction(ISD::FRINT, MVT::f128, Legal); 862 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 863 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 864 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 865 setOperationAction(ISD::FROUND, MVT::f128, Legal); 866 867 setOperationAction(ISD::SELECT, MVT::f128, Expand); 868 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 869 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 870 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 871 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 872 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 873 // No implementation for these ops for PowerPC. 874 setOperationAction(ISD::FSIN , MVT::f128, Expand); 875 setOperationAction(ISD::FCOS , MVT::f128, Expand); 876 setOperationAction(ISD::FPOW, MVT::f128, Expand); 877 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 878 setOperationAction(ISD::FREM, MVT::f128, Expand); 879 } 880 881 } 882 883 if (Subtarget.hasP9Altivec()) { 884 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 885 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 886 } 887 } 888 889 if (Subtarget.hasQPX()) { 890 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 891 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 892 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 893 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 894 895 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 896 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 897 898 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 899 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 900 901 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 902 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 903 904 if (!Subtarget.useCRBits()) 905 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 906 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 907 908 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 909 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 910 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 911 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 912 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 914 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 915 916 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 917 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 918 919 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 920 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 921 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 922 923 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 924 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 925 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 926 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 927 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 928 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 929 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 930 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 931 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 932 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 933 934 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 935 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 936 937 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 938 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 939 940 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 941 942 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 945 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 946 947 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 948 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 949 950 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 951 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 952 953 if (!Subtarget.useCRBits()) 954 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 955 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 956 957 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 958 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 959 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 960 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 961 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 963 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 964 965 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 966 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 967 968 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 969 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 970 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 971 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 972 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 973 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 974 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 975 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 976 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 977 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 978 979 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 980 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 981 982 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 983 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 984 985 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 986 987 setOperationAction(ISD::AND , MVT::v4i1, Legal); 988 setOperationAction(ISD::OR , MVT::v4i1, Legal); 989 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 990 991 if (!Subtarget.useCRBits()) 992 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 993 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 994 995 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 996 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 997 998 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 999 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1000 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1001 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1002 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1003 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1004 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1005 1006 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1007 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1008 1009 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1010 1011 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1012 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1013 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1014 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1015 1016 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1017 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1018 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1020 1021 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1022 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1023 1024 // These need to set FE_INEXACT, and so cannot be vectorized here. 1025 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1026 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1027 1028 if (TM.Options.UnsafeFPMath) { 1029 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1030 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1031 1032 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1033 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1034 } else { 1035 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1036 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1037 1038 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1039 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1040 } 1041 } 1042 1043 if (Subtarget.has64BitSupport()) 1044 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1045 1046 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1047 1048 if (!isPPC64) { 1049 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1050 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1051 } 1052 1053 setBooleanContents(ZeroOrOneBooleanContent); 1054 1055 if (Subtarget.hasAltivec()) { 1056 // Altivec instructions set fields to all zeros or all ones. 1057 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1058 } 1059 1060 if (!isPPC64) { 1061 // These libcalls are not available in 32-bit. 1062 setLibcallName(RTLIB::SHL_I128, nullptr); 1063 setLibcallName(RTLIB::SRL_I128, nullptr); 1064 setLibcallName(RTLIB::SRA_I128, nullptr); 1065 } 1066 1067 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1068 1069 // We have target-specific dag combine patterns for the following nodes: 1070 setTargetDAGCombine(ISD::ADD); 1071 setTargetDAGCombine(ISD::SHL); 1072 setTargetDAGCombine(ISD::SRA); 1073 setTargetDAGCombine(ISD::SRL); 1074 setTargetDAGCombine(ISD::MUL); 1075 setTargetDAGCombine(ISD::SINT_TO_FP); 1076 setTargetDAGCombine(ISD::BUILD_VECTOR); 1077 if (Subtarget.hasFPCVT()) 1078 setTargetDAGCombine(ISD::UINT_TO_FP); 1079 setTargetDAGCombine(ISD::LOAD); 1080 setTargetDAGCombine(ISD::STORE); 1081 setTargetDAGCombine(ISD::BR_CC); 1082 if (Subtarget.useCRBits()) 1083 setTargetDAGCombine(ISD::BRCOND); 1084 setTargetDAGCombine(ISD::BSWAP); 1085 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1086 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1087 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1088 1089 setTargetDAGCombine(ISD::SIGN_EXTEND); 1090 setTargetDAGCombine(ISD::ZERO_EXTEND); 1091 setTargetDAGCombine(ISD::ANY_EXTEND); 1092 1093 setTargetDAGCombine(ISD::TRUNCATE); 1094 1095 if (Subtarget.useCRBits()) { 1096 setTargetDAGCombine(ISD::TRUNCATE); 1097 setTargetDAGCombine(ISD::SETCC); 1098 setTargetDAGCombine(ISD::SELECT_CC); 1099 } 1100 1101 // Use reciprocal estimates. 1102 if (TM.Options.UnsafeFPMath) { 1103 setTargetDAGCombine(ISD::FDIV); 1104 setTargetDAGCombine(ISD::FSQRT); 1105 } 1106 1107 if (Subtarget.hasP9Altivec()) { 1108 setTargetDAGCombine(ISD::ABS); 1109 setTargetDAGCombine(ISD::VSELECT); 1110 } 1111 1112 // Darwin long double math library functions have $LDBL128 appended. 1113 if (Subtarget.isDarwin()) { 1114 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1115 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1116 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1117 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1118 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1119 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1120 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1121 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1122 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1123 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1124 } 1125 1126 if (EnableQuadPrecision) { 1127 setLibcallName(RTLIB::LOG_F128, "logf128"); 1128 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1129 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1130 setLibcallName(RTLIB::EXP_F128, "expf128"); 1131 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1132 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1133 setLibcallName(RTLIB::COS_F128, "cosf128"); 1134 setLibcallName(RTLIB::POW_F128, "powf128"); 1135 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1136 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1137 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1138 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1139 } 1140 1141 // With 32 condition bits, we don't need to sink (and duplicate) compares 1142 // aggressively in CodeGenPrep. 1143 if (Subtarget.useCRBits()) { 1144 setHasMultipleConditionRegisters(); 1145 setJumpIsExpensive(); 1146 } 1147 1148 setMinFunctionAlignment(2); 1149 if (Subtarget.isDarwin()) 1150 setPrefFunctionAlignment(4); 1151 1152 switch (Subtarget.getDarwinDirective()) { 1153 default: break; 1154 case PPC::DIR_970: 1155 case PPC::DIR_A2: 1156 case PPC::DIR_E500: 1157 case PPC::DIR_E500mc: 1158 case PPC::DIR_E5500: 1159 case PPC::DIR_PWR4: 1160 case PPC::DIR_PWR5: 1161 case PPC::DIR_PWR5X: 1162 case PPC::DIR_PWR6: 1163 case PPC::DIR_PWR6X: 1164 case PPC::DIR_PWR7: 1165 case PPC::DIR_PWR8: 1166 case PPC::DIR_PWR9: 1167 setPrefFunctionAlignment(4); 1168 setPrefLoopAlignment(4); 1169 break; 1170 } 1171 1172 if (Subtarget.enableMachineScheduler()) 1173 setSchedulingPreference(Sched::Source); 1174 else 1175 setSchedulingPreference(Sched::Hybrid); 1176 1177 computeRegisterProperties(STI.getRegisterInfo()); 1178 1179 // The Freescale cores do better with aggressive inlining of memcpy and 1180 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1181 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1182 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1183 MaxStoresPerMemset = 32; 1184 MaxStoresPerMemsetOptSize = 16; 1185 MaxStoresPerMemcpy = 32; 1186 MaxStoresPerMemcpyOptSize = 8; 1187 MaxStoresPerMemmove = 32; 1188 MaxStoresPerMemmoveOptSize = 8; 1189 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1190 // The A2 also benefits from (very) aggressive inlining of memcpy and 1191 // friends. The overhead of a the function call, even when warm, can be 1192 // over one hundred cycles. 1193 MaxStoresPerMemset = 128; 1194 MaxStoresPerMemcpy = 128; 1195 MaxStoresPerMemmove = 128; 1196 MaxLoadsPerMemcmp = 128; 1197 } else { 1198 MaxLoadsPerMemcmp = 8; 1199 MaxLoadsPerMemcmpOptSize = 4; 1200 } 1201 } 1202 1203 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1204 /// the desired ByVal argument alignment. 1205 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1206 unsigned MaxMaxAlign) { 1207 if (MaxAlign == MaxMaxAlign) 1208 return; 1209 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1210 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1211 MaxAlign = 32; 1212 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1213 MaxAlign = 16; 1214 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1215 unsigned EltAlign = 0; 1216 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1217 if (EltAlign > MaxAlign) 1218 MaxAlign = EltAlign; 1219 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1220 for (auto *EltTy : STy->elements()) { 1221 unsigned EltAlign = 0; 1222 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1223 if (EltAlign > MaxAlign) 1224 MaxAlign = EltAlign; 1225 if (MaxAlign == MaxMaxAlign) 1226 break; 1227 } 1228 } 1229 } 1230 1231 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1232 /// function arguments in the caller parameter area. 1233 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1234 const DataLayout &DL) const { 1235 // Darwin passes everything on 4 byte boundary. 1236 if (Subtarget.isDarwin()) 1237 return 4; 1238 1239 // 16byte and wider vectors are passed on 16byte boundary. 1240 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1241 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1242 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1243 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1244 return Align; 1245 } 1246 1247 unsigned PPCTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1248 CallingConv:: ID CC, 1249 EVT VT) const { 1250 if (Subtarget.hasSPE() && VT == MVT::f64) 1251 return 2; 1252 return PPCTargetLowering::getNumRegisters(Context, VT); 1253 } 1254 1255 MVT PPCTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1256 CallingConv:: ID CC, 1257 EVT VT) const { 1258 if (Subtarget.hasSPE() && VT == MVT::f64) 1259 return MVT::i32; 1260 return PPCTargetLowering::getRegisterType(Context, VT); 1261 } 1262 1263 bool PPCTargetLowering::useSoftFloat() const { 1264 return Subtarget.useSoftFloat(); 1265 } 1266 1267 bool PPCTargetLowering::hasSPE() const { 1268 return Subtarget.hasSPE(); 1269 } 1270 1271 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1272 switch ((PPCISD::NodeType)Opcode) { 1273 case PPCISD::FIRST_NUMBER: break; 1274 case PPCISD::FSEL: return "PPCISD::FSEL"; 1275 case PPCISD::FCFID: return "PPCISD::FCFID"; 1276 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1277 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1278 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1279 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1280 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1281 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1282 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1283 case PPCISD::FP_TO_UINT_IN_VSR: 1284 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1285 case PPCISD::FP_TO_SINT_IN_VSR: 1286 return "PPCISD::FP_TO_SINT_IN_VSR"; 1287 case PPCISD::FRE: return "PPCISD::FRE"; 1288 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1289 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1290 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1291 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1292 case PPCISD::VPERM: return "PPCISD::VPERM"; 1293 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1294 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1295 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1296 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1297 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1298 case PPCISD::CMPB: return "PPCISD::CMPB"; 1299 case PPCISD::Hi: return "PPCISD::Hi"; 1300 case PPCISD::Lo: return "PPCISD::Lo"; 1301 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1302 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1303 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1304 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1305 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1306 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1307 case PPCISD::SRL: return "PPCISD::SRL"; 1308 case PPCISD::SRA: return "PPCISD::SRA"; 1309 case PPCISD::SHL: return "PPCISD::SHL"; 1310 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1311 case PPCISD::CALL: return "PPCISD::CALL"; 1312 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1313 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1314 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1315 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1316 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1317 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1318 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1319 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1320 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1321 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1322 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1323 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1324 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1325 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1326 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1327 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1328 case PPCISD::VCMP: return "PPCISD::VCMP"; 1329 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1330 case PPCISD::LBRX: return "PPCISD::LBRX"; 1331 case PPCISD::STBRX: return "PPCISD::STBRX"; 1332 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1333 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1334 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1335 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1336 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1337 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1338 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1339 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1340 case PPCISD::ST_VSR_SCAL_INT: 1341 return "PPCISD::ST_VSR_SCAL_INT"; 1342 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1343 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1344 case PPCISD::BDZ: return "PPCISD::BDZ"; 1345 case PPCISD::MFFS: return "PPCISD::MFFS"; 1346 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1347 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1348 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1349 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1350 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1351 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1352 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1353 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1354 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1355 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1356 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1357 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1358 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1359 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1360 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1361 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1362 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1363 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1364 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1365 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1366 case PPCISD::SC: return "PPCISD::SC"; 1367 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1368 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1369 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1370 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1371 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1372 case PPCISD::VABSD: return "PPCISD::VABSD"; 1373 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1374 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1375 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1376 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1377 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1378 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1379 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1380 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1381 } 1382 return nullptr; 1383 } 1384 1385 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1386 EVT VT) const { 1387 if (!VT.isVector()) 1388 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1389 1390 if (Subtarget.hasQPX()) 1391 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1392 1393 return VT.changeVectorElementTypeToInteger(); 1394 } 1395 1396 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1397 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1398 return true; 1399 } 1400 1401 //===----------------------------------------------------------------------===// 1402 // Node matching predicates, for use by the tblgen matching code. 1403 //===----------------------------------------------------------------------===// 1404 1405 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1406 static bool isFloatingPointZero(SDValue Op) { 1407 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1408 return CFP->getValueAPF().isZero(); 1409 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1410 // Maybe this has already been legalized into the constant pool? 1411 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1412 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1413 return CFP->getValueAPF().isZero(); 1414 } 1415 return false; 1416 } 1417 1418 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1419 /// true if Op is undef or if it matches the specified value. 1420 static bool isConstantOrUndef(int Op, int Val) { 1421 return Op < 0 || Op == Val; 1422 } 1423 1424 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1425 /// VPKUHUM instruction. 1426 /// The ShuffleKind distinguishes between big-endian operations with 1427 /// two different inputs (0), either-endian operations with two identical 1428 /// inputs (1), and little-endian operations with two different inputs (2). 1429 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1430 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1431 SelectionDAG &DAG) { 1432 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1433 if (ShuffleKind == 0) { 1434 if (IsLE) 1435 return false; 1436 for (unsigned i = 0; i != 16; ++i) 1437 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1438 return false; 1439 } else if (ShuffleKind == 2) { 1440 if (!IsLE) 1441 return false; 1442 for (unsigned i = 0; i != 16; ++i) 1443 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1444 return false; 1445 } else if (ShuffleKind == 1) { 1446 unsigned j = IsLE ? 0 : 1; 1447 for (unsigned i = 0; i != 8; ++i) 1448 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1449 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1450 return false; 1451 } 1452 return true; 1453 } 1454 1455 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1456 /// VPKUWUM instruction. 1457 /// The ShuffleKind distinguishes between big-endian operations with 1458 /// two different inputs (0), either-endian operations with two identical 1459 /// inputs (1), and little-endian operations with two different inputs (2). 1460 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1461 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1462 SelectionDAG &DAG) { 1463 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1464 if (ShuffleKind == 0) { 1465 if (IsLE) 1466 return false; 1467 for (unsigned i = 0; i != 16; i += 2) 1468 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1469 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1470 return false; 1471 } else if (ShuffleKind == 2) { 1472 if (!IsLE) 1473 return false; 1474 for (unsigned i = 0; i != 16; i += 2) 1475 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1476 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1477 return false; 1478 } else if (ShuffleKind == 1) { 1479 unsigned j = IsLE ? 0 : 2; 1480 for (unsigned i = 0; i != 8; i += 2) 1481 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1482 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1483 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1484 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1485 return false; 1486 } 1487 return true; 1488 } 1489 1490 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1491 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1492 /// current subtarget. 1493 /// 1494 /// The ShuffleKind distinguishes between big-endian operations with 1495 /// two different inputs (0), either-endian operations with two identical 1496 /// inputs (1), and little-endian operations with two different inputs (2). 1497 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1498 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1499 SelectionDAG &DAG) { 1500 const PPCSubtarget& Subtarget = 1501 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1502 if (!Subtarget.hasP8Vector()) 1503 return false; 1504 1505 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1506 if (ShuffleKind == 0) { 1507 if (IsLE) 1508 return false; 1509 for (unsigned i = 0; i != 16; i += 4) 1510 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1511 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1512 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1513 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1514 return false; 1515 } else if (ShuffleKind == 2) { 1516 if (!IsLE) 1517 return false; 1518 for (unsigned i = 0; i != 16; i += 4) 1519 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1520 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1521 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1522 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1523 return false; 1524 } else if (ShuffleKind == 1) { 1525 unsigned j = IsLE ? 0 : 4; 1526 for (unsigned i = 0; i != 8; i += 4) 1527 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1528 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1529 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1530 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1531 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1532 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1533 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1534 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1535 return false; 1536 } 1537 return true; 1538 } 1539 1540 /// isVMerge - Common function, used to match vmrg* shuffles. 1541 /// 1542 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1543 unsigned LHSStart, unsigned RHSStart) { 1544 if (N->getValueType(0) != MVT::v16i8) 1545 return false; 1546 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1547 "Unsupported merge size!"); 1548 1549 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1550 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1551 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1552 LHSStart+j+i*UnitSize) || 1553 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1554 RHSStart+j+i*UnitSize)) 1555 return false; 1556 } 1557 return true; 1558 } 1559 1560 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1561 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1562 /// The ShuffleKind distinguishes between big-endian merges with two 1563 /// different inputs (0), either-endian merges with two identical inputs (1), 1564 /// and little-endian merges with two different inputs (2). For the latter, 1565 /// the input operands are swapped (see PPCInstrAltivec.td). 1566 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1567 unsigned ShuffleKind, SelectionDAG &DAG) { 1568 if (DAG.getDataLayout().isLittleEndian()) { 1569 if (ShuffleKind == 1) // unary 1570 return isVMerge(N, UnitSize, 0, 0); 1571 else if (ShuffleKind == 2) // swapped 1572 return isVMerge(N, UnitSize, 0, 16); 1573 else 1574 return false; 1575 } else { 1576 if (ShuffleKind == 1) // unary 1577 return isVMerge(N, UnitSize, 8, 8); 1578 else if (ShuffleKind == 0) // normal 1579 return isVMerge(N, UnitSize, 8, 24); 1580 else 1581 return false; 1582 } 1583 } 1584 1585 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1586 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1587 /// The ShuffleKind distinguishes between big-endian merges with two 1588 /// different inputs (0), either-endian merges with two identical inputs (1), 1589 /// and little-endian merges with two different inputs (2). For the latter, 1590 /// the input operands are swapped (see PPCInstrAltivec.td). 1591 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1592 unsigned ShuffleKind, SelectionDAG &DAG) { 1593 if (DAG.getDataLayout().isLittleEndian()) { 1594 if (ShuffleKind == 1) // unary 1595 return isVMerge(N, UnitSize, 8, 8); 1596 else if (ShuffleKind == 2) // swapped 1597 return isVMerge(N, UnitSize, 8, 24); 1598 else 1599 return false; 1600 } else { 1601 if (ShuffleKind == 1) // unary 1602 return isVMerge(N, UnitSize, 0, 0); 1603 else if (ShuffleKind == 0) // normal 1604 return isVMerge(N, UnitSize, 0, 16); 1605 else 1606 return false; 1607 } 1608 } 1609 1610 /** 1611 * Common function used to match vmrgew and vmrgow shuffles 1612 * 1613 * The indexOffset determines whether to look for even or odd words in 1614 * the shuffle mask. This is based on the of the endianness of the target 1615 * machine. 1616 * - Little Endian: 1617 * - Use offset of 0 to check for odd elements 1618 * - Use offset of 4 to check for even elements 1619 * - Big Endian: 1620 * - Use offset of 0 to check for even elements 1621 * - Use offset of 4 to check for odd elements 1622 * A detailed description of the vector element ordering for little endian and 1623 * big endian can be found at 1624 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1625 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1626 * compiler differences mean to you 1627 * 1628 * The mask to the shuffle vector instruction specifies the indices of the 1629 * elements from the two input vectors to place in the result. The elements are 1630 * numbered in array-access order, starting with the first vector. These vectors 1631 * are always of type v16i8, thus each vector will contain 16 elements of size 1632 * 8. More info on the shuffle vector can be found in the 1633 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1634 * Language Reference. 1635 * 1636 * The RHSStartValue indicates whether the same input vectors are used (unary) 1637 * or two different input vectors are used, based on the following: 1638 * - If the instruction uses the same vector for both inputs, the range of the 1639 * indices will be 0 to 15. In this case, the RHSStart value passed should 1640 * be 0. 1641 * - If the instruction has two different vectors then the range of the 1642 * indices will be 0 to 31. In this case, the RHSStart value passed should 1643 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1644 * to 31 specify elements in the second vector). 1645 * 1646 * \param[in] N The shuffle vector SD Node to analyze 1647 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1648 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1649 * vector to the shuffle_vector instruction 1650 * \return true iff this shuffle vector represents an even or odd word merge 1651 */ 1652 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1653 unsigned RHSStartValue) { 1654 if (N->getValueType(0) != MVT::v16i8) 1655 return false; 1656 1657 for (unsigned i = 0; i < 2; ++i) 1658 for (unsigned j = 0; j < 4; ++j) 1659 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1660 i*RHSStartValue+j+IndexOffset) || 1661 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1662 i*RHSStartValue+j+IndexOffset+8)) 1663 return false; 1664 return true; 1665 } 1666 1667 /** 1668 * Determine if the specified shuffle mask is suitable for the vmrgew or 1669 * vmrgow instructions. 1670 * 1671 * \param[in] N The shuffle vector SD Node to analyze 1672 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1673 * \param[in] ShuffleKind Identify the type of merge: 1674 * - 0 = big-endian merge with two different inputs; 1675 * - 1 = either-endian merge with two identical inputs; 1676 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1677 * little-endian merges). 1678 * \param[in] DAG The current SelectionDAG 1679 * \return true iff this shuffle mask 1680 */ 1681 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1682 unsigned ShuffleKind, SelectionDAG &DAG) { 1683 if (DAG.getDataLayout().isLittleEndian()) { 1684 unsigned indexOffset = CheckEven ? 4 : 0; 1685 if (ShuffleKind == 1) // Unary 1686 return isVMerge(N, indexOffset, 0); 1687 else if (ShuffleKind == 2) // swapped 1688 return isVMerge(N, indexOffset, 16); 1689 else 1690 return false; 1691 } 1692 else { 1693 unsigned indexOffset = CheckEven ? 0 : 4; 1694 if (ShuffleKind == 1) // Unary 1695 return isVMerge(N, indexOffset, 0); 1696 else if (ShuffleKind == 0) // Normal 1697 return isVMerge(N, indexOffset, 16); 1698 else 1699 return false; 1700 } 1701 return false; 1702 } 1703 1704 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1705 /// amount, otherwise return -1. 1706 /// The ShuffleKind distinguishes between big-endian operations with two 1707 /// different inputs (0), either-endian operations with two identical inputs 1708 /// (1), and little-endian operations with two different inputs (2). For the 1709 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1710 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1711 SelectionDAG &DAG) { 1712 if (N->getValueType(0) != MVT::v16i8) 1713 return -1; 1714 1715 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1716 1717 // Find the first non-undef value in the shuffle mask. 1718 unsigned i; 1719 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1720 /*search*/; 1721 1722 if (i == 16) return -1; // all undef. 1723 1724 // Otherwise, check to see if the rest of the elements are consecutively 1725 // numbered from this value. 1726 unsigned ShiftAmt = SVOp->getMaskElt(i); 1727 if (ShiftAmt < i) return -1; 1728 1729 ShiftAmt -= i; 1730 bool isLE = DAG.getDataLayout().isLittleEndian(); 1731 1732 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1733 // Check the rest of the elements to see if they are consecutive. 1734 for (++i; i != 16; ++i) 1735 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1736 return -1; 1737 } else if (ShuffleKind == 1) { 1738 // Check the rest of the elements to see if they are consecutive. 1739 for (++i; i != 16; ++i) 1740 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1741 return -1; 1742 } else 1743 return -1; 1744 1745 if (isLE) 1746 ShiftAmt = 16 - ShiftAmt; 1747 1748 return ShiftAmt; 1749 } 1750 1751 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1752 /// specifies a splat of a single element that is suitable for input to 1753 /// VSPLTB/VSPLTH/VSPLTW. 1754 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1755 assert(N->getValueType(0) == MVT::v16i8 && 1756 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1757 1758 // The consecutive indices need to specify an element, not part of two 1759 // different elements. So abandon ship early if this isn't the case. 1760 if (N->getMaskElt(0) % EltSize != 0) 1761 return false; 1762 1763 // This is a splat operation if each element of the permute is the same, and 1764 // if the value doesn't reference the second vector. 1765 unsigned ElementBase = N->getMaskElt(0); 1766 1767 // FIXME: Handle UNDEF elements too! 1768 if (ElementBase >= 16) 1769 return false; 1770 1771 // Check that the indices are consecutive, in the case of a multi-byte element 1772 // splatted with a v16i8 mask. 1773 for (unsigned i = 1; i != EltSize; ++i) 1774 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1775 return false; 1776 1777 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1778 if (N->getMaskElt(i) < 0) continue; 1779 for (unsigned j = 0; j != EltSize; ++j) 1780 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1781 return false; 1782 } 1783 return true; 1784 } 1785 1786 /// Check that the mask is shuffling N byte elements. Within each N byte 1787 /// element of the mask, the indices could be either in increasing or 1788 /// decreasing order as long as they are consecutive. 1789 /// \param[in] N the shuffle vector SD Node to analyze 1790 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1791 /// Word/DoubleWord/QuadWord). 1792 /// \param[in] StepLen the delta indices number among the N byte element, if 1793 /// the mask is in increasing/decreasing order then it is 1/-1. 1794 /// \return true iff the mask is shuffling N byte elements. 1795 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1796 int StepLen) { 1797 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1798 "Unexpected element width."); 1799 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1800 1801 unsigned NumOfElem = 16 / Width; 1802 unsigned MaskVal[16]; // Width is never greater than 16 1803 for (unsigned i = 0; i < NumOfElem; ++i) { 1804 MaskVal[0] = N->getMaskElt(i * Width); 1805 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1806 return false; 1807 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1808 return false; 1809 } 1810 1811 for (unsigned int j = 1; j < Width; ++j) { 1812 MaskVal[j] = N->getMaskElt(i * Width + j); 1813 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1814 return false; 1815 } 1816 } 1817 } 1818 1819 return true; 1820 } 1821 1822 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1823 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1824 if (!isNByteElemShuffleMask(N, 4, 1)) 1825 return false; 1826 1827 // Now we look at mask elements 0,4,8,12 1828 unsigned M0 = N->getMaskElt(0) / 4; 1829 unsigned M1 = N->getMaskElt(4) / 4; 1830 unsigned M2 = N->getMaskElt(8) / 4; 1831 unsigned M3 = N->getMaskElt(12) / 4; 1832 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1833 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1834 1835 // Below, let H and L be arbitrary elements of the shuffle mask 1836 // where H is in the range [4,7] and L is in the range [0,3]. 1837 // H, 1, 2, 3 or L, 5, 6, 7 1838 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1839 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1840 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1841 InsertAtByte = IsLE ? 12 : 0; 1842 Swap = M0 < 4; 1843 return true; 1844 } 1845 // 0, H, 2, 3 or 4, L, 6, 7 1846 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1847 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1848 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1849 InsertAtByte = IsLE ? 8 : 4; 1850 Swap = M1 < 4; 1851 return true; 1852 } 1853 // 0, 1, H, 3 or 4, 5, L, 7 1854 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1855 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1856 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1857 InsertAtByte = IsLE ? 4 : 8; 1858 Swap = M2 < 4; 1859 return true; 1860 } 1861 // 0, 1, 2, H or 4, 5, 6, L 1862 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1863 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1864 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1865 InsertAtByte = IsLE ? 0 : 12; 1866 Swap = M3 < 4; 1867 return true; 1868 } 1869 1870 // If both vector operands for the shuffle are the same vector, the mask will 1871 // contain only elements from the first one and the second one will be undef. 1872 if (N->getOperand(1).isUndef()) { 1873 ShiftElts = 0; 1874 Swap = true; 1875 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1876 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1877 InsertAtByte = IsLE ? 12 : 0; 1878 return true; 1879 } 1880 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1881 InsertAtByte = IsLE ? 8 : 4; 1882 return true; 1883 } 1884 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1885 InsertAtByte = IsLE ? 4 : 8; 1886 return true; 1887 } 1888 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1889 InsertAtByte = IsLE ? 0 : 12; 1890 return true; 1891 } 1892 } 1893 1894 return false; 1895 } 1896 1897 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1898 bool &Swap, bool IsLE) { 1899 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1900 // Ensure each byte index of the word is consecutive. 1901 if (!isNByteElemShuffleMask(N, 4, 1)) 1902 return false; 1903 1904 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1905 unsigned M0 = N->getMaskElt(0) / 4; 1906 unsigned M1 = N->getMaskElt(4) / 4; 1907 unsigned M2 = N->getMaskElt(8) / 4; 1908 unsigned M3 = N->getMaskElt(12) / 4; 1909 1910 // If both vector operands for the shuffle are the same vector, the mask will 1911 // contain only elements from the first one and the second one will be undef. 1912 if (N->getOperand(1).isUndef()) { 1913 assert(M0 < 4 && "Indexing into an undef vector?"); 1914 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1915 return false; 1916 1917 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1918 Swap = false; 1919 return true; 1920 } 1921 1922 // Ensure each word index of the ShuffleVector Mask is consecutive. 1923 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1924 return false; 1925 1926 if (IsLE) { 1927 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1928 // Input vectors don't need to be swapped if the leading element 1929 // of the result is one of the 3 left elements of the second vector 1930 // (or if there is no shift to be done at all). 1931 Swap = false; 1932 ShiftElts = (8 - M0) % 8; 1933 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1934 // Input vectors need to be swapped if the leading element 1935 // of the result is one of the 3 left elements of the first vector 1936 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1937 Swap = true; 1938 ShiftElts = (4 - M0) % 4; 1939 } 1940 1941 return true; 1942 } else { // BE 1943 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1944 // Input vectors don't need to be swapped if the leading element 1945 // of the result is one of the 4 elements of the first vector. 1946 Swap = false; 1947 ShiftElts = M0; 1948 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1949 // Input vectors need to be swapped if the leading element 1950 // of the result is one of the 4 elements of the right vector. 1951 Swap = true; 1952 ShiftElts = M0 - 4; 1953 } 1954 1955 return true; 1956 } 1957 } 1958 1959 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1960 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1961 1962 if (!isNByteElemShuffleMask(N, Width, -1)) 1963 return false; 1964 1965 for (int i = 0; i < 16; i += Width) 1966 if (N->getMaskElt(i) != i + Width - 1) 1967 return false; 1968 1969 return true; 1970 } 1971 1972 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1973 return isXXBRShuffleMaskHelper(N, 2); 1974 } 1975 1976 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1977 return isXXBRShuffleMaskHelper(N, 4); 1978 } 1979 1980 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1981 return isXXBRShuffleMaskHelper(N, 8); 1982 } 1983 1984 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1985 return isXXBRShuffleMaskHelper(N, 16); 1986 } 1987 1988 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1989 /// if the inputs to the instruction should be swapped and set \p DM to the 1990 /// value for the immediate. 1991 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1992 /// AND element 0 of the result comes from the first input (LE) or second input 1993 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1994 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1995 /// mask. 1996 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1997 bool &Swap, bool IsLE) { 1998 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1999 2000 // Ensure each byte index of the double word is consecutive. 2001 if (!isNByteElemShuffleMask(N, 8, 1)) 2002 return false; 2003 2004 unsigned M0 = N->getMaskElt(0) / 8; 2005 unsigned M1 = N->getMaskElt(8) / 8; 2006 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2007 2008 // If both vector operands for the shuffle are the same vector, the mask will 2009 // contain only elements from the first one and the second one will be undef. 2010 if (N->getOperand(1).isUndef()) { 2011 if ((M0 | M1) < 2) { 2012 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2013 Swap = false; 2014 return true; 2015 } else 2016 return false; 2017 } 2018 2019 if (IsLE) { 2020 if (M0 > 1 && M1 < 2) { 2021 Swap = false; 2022 } else if (M0 < 2 && M1 > 1) { 2023 M0 = (M0 + 2) % 4; 2024 M1 = (M1 + 2) % 4; 2025 Swap = true; 2026 } else 2027 return false; 2028 2029 // Note: if control flow comes here that means Swap is already set above 2030 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2031 return true; 2032 } else { // BE 2033 if (M0 < 2 && M1 > 1) { 2034 Swap = false; 2035 } else if (M0 > 1 && M1 < 2) { 2036 M0 = (M0 + 2) % 4; 2037 M1 = (M1 + 2) % 4; 2038 Swap = true; 2039 } else 2040 return false; 2041 2042 // Note: if control flow comes here that means Swap is already set above 2043 DM = (M0 << 1) + (M1 & 1); 2044 return true; 2045 } 2046 } 2047 2048 2049 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2050 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2051 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2052 SelectionDAG &DAG) { 2053 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2054 assert(isSplatShuffleMask(SVOp, EltSize)); 2055 if (DAG.getDataLayout().isLittleEndian()) 2056 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2057 else 2058 return SVOp->getMaskElt(0) / EltSize; 2059 } 2060 2061 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2062 /// by using a vspltis[bhw] instruction of the specified element size, return 2063 /// the constant being splatted. The ByteSize field indicates the number of 2064 /// bytes of each element [124] -> [bhw]. 2065 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2066 SDValue OpVal(nullptr, 0); 2067 2068 // If ByteSize of the splat is bigger than the element size of the 2069 // build_vector, then we have a case where we are checking for a splat where 2070 // multiple elements of the buildvector are folded together into a single 2071 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2072 unsigned EltSize = 16/N->getNumOperands(); 2073 if (EltSize < ByteSize) { 2074 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2075 SDValue UniquedVals[4]; 2076 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2077 2078 // See if all of the elements in the buildvector agree across. 2079 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2080 if (N->getOperand(i).isUndef()) continue; 2081 // If the element isn't a constant, bail fully out. 2082 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2083 2084 if (!UniquedVals[i&(Multiple-1)].getNode()) 2085 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2086 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2087 return SDValue(); // no match. 2088 } 2089 2090 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2091 // either constant or undef values that are identical for each chunk. See 2092 // if these chunks can form into a larger vspltis*. 2093 2094 // Check to see if all of the leading entries are either 0 or -1. If 2095 // neither, then this won't fit into the immediate field. 2096 bool LeadingZero = true; 2097 bool LeadingOnes = true; 2098 for (unsigned i = 0; i != Multiple-1; ++i) { 2099 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2100 2101 LeadingZero &= isNullConstant(UniquedVals[i]); 2102 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2103 } 2104 // Finally, check the least significant entry. 2105 if (LeadingZero) { 2106 if (!UniquedVals[Multiple-1].getNode()) 2107 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2108 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2109 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2110 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2111 } 2112 if (LeadingOnes) { 2113 if (!UniquedVals[Multiple-1].getNode()) 2114 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2115 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2116 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2117 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2118 } 2119 2120 return SDValue(); 2121 } 2122 2123 // Check to see if this buildvec has a single non-undef value in its elements. 2124 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2125 if (N->getOperand(i).isUndef()) continue; 2126 if (!OpVal.getNode()) 2127 OpVal = N->getOperand(i); 2128 else if (OpVal != N->getOperand(i)) 2129 return SDValue(); 2130 } 2131 2132 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2133 2134 unsigned ValSizeInBytes = EltSize; 2135 uint64_t Value = 0; 2136 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2137 Value = CN->getZExtValue(); 2138 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2139 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2140 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2141 } 2142 2143 // If the splat value is larger than the element value, then we can never do 2144 // this splat. The only case that we could fit the replicated bits into our 2145 // immediate field for would be zero, and we prefer to use vxor for it. 2146 if (ValSizeInBytes < ByteSize) return SDValue(); 2147 2148 // If the element value is larger than the splat value, check if it consists 2149 // of a repeated bit pattern of size ByteSize. 2150 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2151 return SDValue(); 2152 2153 // Properly sign extend the value. 2154 int MaskVal = SignExtend32(Value, ByteSize * 8); 2155 2156 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2157 if (MaskVal == 0) return SDValue(); 2158 2159 // Finally, if this value fits in a 5 bit sext field, return it 2160 if (SignExtend32<5>(MaskVal) == MaskVal) 2161 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2162 return SDValue(); 2163 } 2164 2165 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2166 /// amount, otherwise return -1. 2167 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2168 EVT VT = N->getValueType(0); 2169 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2170 return -1; 2171 2172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2173 2174 // Find the first non-undef value in the shuffle mask. 2175 unsigned i; 2176 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2177 /*search*/; 2178 2179 if (i == 4) return -1; // all undef. 2180 2181 // Otherwise, check to see if the rest of the elements are consecutively 2182 // numbered from this value. 2183 unsigned ShiftAmt = SVOp->getMaskElt(i); 2184 if (ShiftAmt < i) return -1; 2185 ShiftAmt -= i; 2186 2187 // Check the rest of the elements to see if they are consecutive. 2188 for (++i; i != 4; ++i) 2189 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2190 return -1; 2191 2192 return ShiftAmt; 2193 } 2194 2195 //===----------------------------------------------------------------------===// 2196 // Addressing Mode Selection 2197 //===----------------------------------------------------------------------===// 2198 2199 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2200 /// or 64-bit immediate, and if the value can be accurately represented as a 2201 /// sign extension from a 16-bit value. If so, this returns true and the 2202 /// immediate. 2203 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2204 if (!isa<ConstantSDNode>(N)) 2205 return false; 2206 2207 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2208 if (N->getValueType(0) == MVT::i32) 2209 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2210 else 2211 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2212 } 2213 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2214 return isIntS16Immediate(Op.getNode(), Imm); 2215 } 2216 2217 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2218 /// can be represented as an indexed [r+r] operation. Returns false if it 2219 /// can be more efficiently represented with [r+imm]. 2220 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2221 SDValue &Index, 2222 SelectionDAG &DAG) const { 2223 int16_t imm = 0; 2224 if (N.getOpcode() == ISD::ADD) { 2225 if (isIntS16Immediate(N.getOperand(1), imm)) 2226 return false; // r+i 2227 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2228 return false; // r+i 2229 2230 Base = N.getOperand(0); 2231 Index = N.getOperand(1); 2232 return true; 2233 } else if (N.getOpcode() == ISD::OR) { 2234 if (isIntS16Immediate(N.getOperand(1), imm)) 2235 return false; // r+i can fold it if we can. 2236 2237 // If this is an or of disjoint bitfields, we can codegen this as an add 2238 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2239 // disjoint. 2240 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2241 2242 if (LHSKnown.Zero.getBoolValue()) { 2243 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2244 // If all of the bits are known zero on the LHS or RHS, the add won't 2245 // carry. 2246 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2247 Base = N.getOperand(0); 2248 Index = N.getOperand(1); 2249 return true; 2250 } 2251 } 2252 } 2253 2254 return false; 2255 } 2256 2257 // If we happen to be doing an i64 load or store into a stack slot that has 2258 // less than a 4-byte alignment, then the frame-index elimination may need to 2259 // use an indexed load or store instruction (because the offset may not be a 2260 // multiple of 4). The extra register needed to hold the offset comes from the 2261 // register scavenger, and it is possible that the scavenger will need to use 2262 // an emergency spill slot. As a result, we need to make sure that a spill slot 2263 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2264 // stack slot. 2265 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2266 // FIXME: This does not handle the LWA case. 2267 if (VT != MVT::i64) 2268 return; 2269 2270 // NOTE: We'll exclude negative FIs here, which come from argument 2271 // lowering, because there are no known test cases triggering this problem 2272 // using packed structures (or similar). We can remove this exclusion if 2273 // we find such a test case. The reason why this is so test-case driven is 2274 // because this entire 'fixup' is only to prevent crashes (from the 2275 // register scavenger) on not-really-valid inputs. For example, if we have: 2276 // %a = alloca i1 2277 // %b = bitcast i1* %a to i64* 2278 // store i64* a, i64 b 2279 // then the store should really be marked as 'align 1', but is not. If it 2280 // were marked as 'align 1' then the indexed form would have been 2281 // instruction-selected initially, and the problem this 'fixup' is preventing 2282 // won't happen regardless. 2283 if (FrameIdx < 0) 2284 return; 2285 2286 MachineFunction &MF = DAG.getMachineFunction(); 2287 MachineFrameInfo &MFI = MF.getFrameInfo(); 2288 2289 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2290 if (Align >= 4) 2291 return; 2292 2293 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2294 FuncInfo->setHasNonRISpills(); 2295 } 2296 2297 /// Returns true if the address N can be represented by a base register plus 2298 /// a signed 16-bit displacement [r+imm], and if it is not better 2299 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2300 /// displacements that are multiples of that value. 2301 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2302 SDValue &Base, 2303 SelectionDAG &DAG, 2304 unsigned Alignment) const { 2305 // FIXME dl should come from parent load or store, not from address 2306 SDLoc dl(N); 2307 // If this can be more profitably realized as r+r, fail. 2308 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2309 return false; 2310 2311 if (N.getOpcode() == ISD::ADD) { 2312 int16_t imm = 0; 2313 if (isIntS16Immediate(N.getOperand(1), imm) && 2314 (!Alignment || (imm % Alignment) == 0)) { 2315 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2316 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2317 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2318 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2319 } else { 2320 Base = N.getOperand(0); 2321 } 2322 return true; // [r+i] 2323 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2324 // Match LOAD (ADD (X, Lo(G))). 2325 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2326 && "Cannot handle constant offsets yet!"); 2327 Disp = N.getOperand(1).getOperand(0); // The global address. 2328 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2329 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2330 Disp.getOpcode() == ISD::TargetConstantPool || 2331 Disp.getOpcode() == ISD::TargetJumpTable); 2332 Base = N.getOperand(0); 2333 return true; // [&g+r] 2334 } 2335 } else if (N.getOpcode() == ISD::OR) { 2336 int16_t imm = 0; 2337 if (isIntS16Immediate(N.getOperand(1), imm) && 2338 (!Alignment || (imm % Alignment) == 0)) { 2339 // If this is an or of disjoint bitfields, we can codegen this as an add 2340 // (for better address arithmetic) if the LHS and RHS of the OR are 2341 // provably disjoint. 2342 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2343 2344 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2345 // If all of the bits are known zero on the LHS or RHS, the add won't 2346 // carry. 2347 if (FrameIndexSDNode *FI = 2348 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2349 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2350 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2351 } else { 2352 Base = N.getOperand(0); 2353 } 2354 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2355 return true; 2356 } 2357 } 2358 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2359 // Loading from a constant address. 2360 2361 // If this address fits entirely in a 16-bit sext immediate field, codegen 2362 // this as "d, 0" 2363 int16_t Imm; 2364 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2365 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2366 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2367 CN->getValueType(0)); 2368 return true; 2369 } 2370 2371 // Handle 32-bit sext immediates with LIS + addr mode. 2372 if ((CN->getValueType(0) == MVT::i32 || 2373 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2374 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2375 int Addr = (int)CN->getZExtValue(); 2376 2377 // Otherwise, break this down into an LIS + disp. 2378 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2379 2380 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2381 MVT::i32); 2382 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2383 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2384 return true; 2385 } 2386 } 2387 2388 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2389 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2390 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2391 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2392 } else 2393 Base = N; 2394 return true; // [r+0] 2395 } 2396 2397 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2398 /// represented as an indexed [r+r] operation. 2399 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2400 SDValue &Index, 2401 SelectionDAG &DAG) const { 2402 // Check to see if we can easily represent this as an [r+r] address. This 2403 // will fail if it thinks that the address is more profitably represented as 2404 // reg+imm, e.g. where imm = 0. 2405 if (SelectAddressRegReg(N, Base, Index, DAG)) 2406 return true; 2407 2408 // If the address is the result of an add, we will utilize the fact that the 2409 // address calculation includes an implicit add. However, we can reduce 2410 // register pressure if we do not materialize a constant just for use as the 2411 // index register. We only get rid of the add if it is not an add of a 2412 // value and a 16-bit signed constant and both have a single use. 2413 int16_t imm = 0; 2414 if (N.getOpcode() == ISD::ADD && 2415 (!isIntS16Immediate(N.getOperand(1), imm) || 2416 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2417 Base = N.getOperand(0); 2418 Index = N.getOperand(1); 2419 return true; 2420 } 2421 2422 // Otherwise, do it the hard way, using R0 as the base register. 2423 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2424 N.getValueType()); 2425 Index = N; 2426 return true; 2427 } 2428 2429 /// Returns true if we should use a direct load into vector instruction 2430 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2431 static bool usePartialVectorLoads(SDNode *N) { 2432 if (!N->hasOneUse()) 2433 return false; 2434 2435 // If there are any other uses other than scalar to vector, then we should 2436 // keep it as a scalar load -> direct move pattern to prevent multiple 2437 // loads. Currently, only check for i64 since we have lxsd/lfd to do this 2438 // efficiently, but no update equivalent. 2439 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2440 EVT MemVT = LD->getMemoryVT(); 2441 if (MemVT.isSimple() && MemVT.getSimpleVT().SimpleTy == MVT::i64) { 2442 SDNode *User = *(LD->use_begin()); 2443 if (User->getOpcode() == ISD::SCALAR_TO_VECTOR) 2444 return true; 2445 } 2446 } 2447 2448 return false; 2449 } 2450 2451 /// getPreIndexedAddressParts - returns true by value, base pointer and 2452 /// offset pointer and addressing mode by reference if the node's address 2453 /// can be legally represented as pre-indexed load / store address. 2454 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2455 SDValue &Offset, 2456 ISD::MemIndexedMode &AM, 2457 SelectionDAG &DAG) const { 2458 if (DisablePPCPreinc) return false; 2459 2460 bool isLoad = true; 2461 SDValue Ptr; 2462 EVT VT; 2463 unsigned Alignment; 2464 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2465 Ptr = LD->getBasePtr(); 2466 VT = LD->getMemoryVT(); 2467 Alignment = LD->getAlignment(); 2468 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2469 Ptr = ST->getBasePtr(); 2470 VT = ST->getMemoryVT(); 2471 Alignment = ST->getAlignment(); 2472 isLoad = false; 2473 } else 2474 return false; 2475 2476 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2477 // instructions because we can fold these into a more efficient instruction 2478 // instead, (such as LXSD). 2479 if (isLoad && usePartialVectorLoads(N)) { 2480 return false; 2481 } 2482 2483 // PowerPC doesn't have preinc load/store instructions for vectors (except 2484 // for QPX, which does have preinc r+r forms). 2485 if (VT.isVector()) { 2486 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2487 return false; 2488 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2489 AM = ISD::PRE_INC; 2490 return true; 2491 } 2492 } 2493 2494 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2495 // Common code will reject creating a pre-inc form if the base pointer 2496 // is a frame index, or if N is a store and the base pointer is either 2497 // the same as or a predecessor of the value being stored. Check for 2498 // those situations here, and try with swapped Base/Offset instead. 2499 bool Swap = false; 2500 2501 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2502 Swap = true; 2503 else if (!isLoad) { 2504 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2505 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2506 Swap = true; 2507 } 2508 2509 if (Swap) 2510 std::swap(Base, Offset); 2511 2512 AM = ISD::PRE_INC; 2513 return true; 2514 } 2515 2516 // LDU/STU can only handle immediates that are a multiple of 4. 2517 if (VT != MVT::i64) { 2518 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2519 return false; 2520 } else { 2521 // LDU/STU need an address with at least 4-byte alignment. 2522 if (Alignment < 4) 2523 return false; 2524 2525 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2526 return false; 2527 } 2528 2529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2530 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2531 // sext i32 to i64 when addr mode is r+i. 2532 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2533 LD->getExtensionType() == ISD::SEXTLOAD && 2534 isa<ConstantSDNode>(Offset)) 2535 return false; 2536 } 2537 2538 AM = ISD::PRE_INC; 2539 return true; 2540 } 2541 2542 //===----------------------------------------------------------------------===// 2543 // LowerOperation implementation 2544 //===----------------------------------------------------------------------===// 2545 2546 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2547 /// and LoOpFlags to the target MO flags. 2548 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2549 unsigned &HiOpFlags, unsigned &LoOpFlags, 2550 const GlobalValue *GV = nullptr) { 2551 HiOpFlags = PPCII::MO_HA; 2552 LoOpFlags = PPCII::MO_LO; 2553 2554 // Don't use the pic base if not in PIC relocation model. 2555 if (IsPIC) { 2556 HiOpFlags |= PPCII::MO_PIC_FLAG; 2557 LoOpFlags |= PPCII::MO_PIC_FLAG; 2558 } 2559 2560 // If this is a reference to a global value that requires a non-lazy-ptr, make 2561 // sure that instruction lowering adds it. 2562 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2563 HiOpFlags |= PPCII::MO_NLP_FLAG; 2564 LoOpFlags |= PPCII::MO_NLP_FLAG; 2565 2566 if (GV->hasHiddenVisibility()) { 2567 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2568 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2569 } 2570 } 2571 } 2572 2573 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2574 SelectionDAG &DAG) { 2575 SDLoc DL(HiPart); 2576 EVT PtrVT = HiPart.getValueType(); 2577 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2578 2579 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2580 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2581 2582 // With PIC, the first instruction is actually "GR+hi(&G)". 2583 if (isPIC) 2584 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2585 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2586 2587 // Generate non-pic code that has direct accesses to the constant pool. 2588 // The address of the global is just (hi(&g)+lo(&g)). 2589 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2590 } 2591 2592 static void setUsesTOCBasePtr(MachineFunction &MF) { 2593 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2594 FuncInfo->setUsesTOCBasePtr(); 2595 } 2596 2597 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2598 setUsesTOCBasePtr(DAG.getMachineFunction()); 2599 } 2600 2601 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2602 SDValue GA) { 2603 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2604 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2605 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2606 2607 SDValue Ops[] = { GA, Reg }; 2608 return DAG.getMemIntrinsicNode( 2609 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2610 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2611 MachineMemOperand::MOLoad); 2612 } 2613 2614 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2615 SelectionDAG &DAG) const { 2616 EVT PtrVT = Op.getValueType(); 2617 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2618 const Constant *C = CP->getConstVal(); 2619 2620 // 64-bit SVR4 ABI code is always position-independent. 2621 // The actual address of the GlobalValue is stored in the TOC. 2622 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2623 setUsesTOCBasePtr(DAG); 2624 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2625 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2626 } 2627 2628 unsigned MOHiFlag, MOLoFlag; 2629 bool IsPIC = isPositionIndependent(); 2630 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2631 2632 if (IsPIC && Subtarget.isSVR4ABI()) { 2633 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2634 PPCII::MO_PIC_FLAG); 2635 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2636 } 2637 2638 SDValue CPIHi = 2639 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2640 SDValue CPILo = 2641 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2642 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2643 } 2644 2645 // For 64-bit PowerPC, prefer the more compact relative encodings. 2646 // This trades 32 bits per jump table entry for one or two instructions 2647 // on the jump site. 2648 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2649 if (isJumpTableRelative()) 2650 return MachineJumpTableInfo::EK_LabelDifference32; 2651 2652 return TargetLowering::getJumpTableEncoding(); 2653 } 2654 2655 bool PPCTargetLowering::isJumpTableRelative() const { 2656 if (Subtarget.isPPC64()) 2657 return true; 2658 return TargetLowering::isJumpTableRelative(); 2659 } 2660 2661 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2662 SelectionDAG &DAG) const { 2663 if (!Subtarget.isPPC64()) 2664 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2665 2666 switch (getTargetMachine().getCodeModel()) { 2667 case CodeModel::Small: 2668 case CodeModel::Medium: 2669 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2670 default: 2671 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2672 getPointerTy(DAG.getDataLayout())); 2673 } 2674 } 2675 2676 const MCExpr * 2677 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2678 unsigned JTI, 2679 MCContext &Ctx) const { 2680 if (!Subtarget.isPPC64()) 2681 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2682 2683 switch (getTargetMachine().getCodeModel()) { 2684 case CodeModel::Small: 2685 case CodeModel::Medium: 2686 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2687 default: 2688 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2689 } 2690 } 2691 2692 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2693 EVT PtrVT = Op.getValueType(); 2694 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2695 2696 // 64-bit SVR4 ABI code is always position-independent. 2697 // The actual address of the GlobalValue is stored in the TOC. 2698 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2699 setUsesTOCBasePtr(DAG); 2700 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2701 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2702 } 2703 2704 unsigned MOHiFlag, MOLoFlag; 2705 bool IsPIC = isPositionIndependent(); 2706 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2707 2708 if (IsPIC && Subtarget.isSVR4ABI()) { 2709 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2710 PPCII::MO_PIC_FLAG); 2711 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2712 } 2713 2714 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2715 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2716 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2717 } 2718 2719 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2720 SelectionDAG &DAG) const { 2721 EVT PtrVT = Op.getValueType(); 2722 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2723 const BlockAddress *BA = BASDN->getBlockAddress(); 2724 2725 // 64-bit SVR4 ABI code is always position-independent. 2726 // The actual BlockAddress is stored in the TOC. 2727 if (Subtarget.isSVR4ABI() && 2728 (Subtarget.isPPC64() || isPositionIndependent())) { 2729 if (Subtarget.isPPC64()) 2730 setUsesTOCBasePtr(DAG); 2731 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2732 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2733 } 2734 2735 unsigned MOHiFlag, MOLoFlag; 2736 bool IsPIC = isPositionIndependent(); 2737 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2738 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2739 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2740 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2741 } 2742 2743 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2744 SelectionDAG &DAG) const { 2745 // FIXME: TLS addresses currently use medium model code sequences, 2746 // which is the most useful form. Eventually support for small and 2747 // large models could be added if users need it, at the cost of 2748 // additional complexity. 2749 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2750 if (DAG.getTarget().useEmulatedTLS()) 2751 return LowerToTLSEmulatedModel(GA, DAG); 2752 2753 SDLoc dl(GA); 2754 const GlobalValue *GV = GA->getGlobal(); 2755 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2756 bool is64bit = Subtarget.isPPC64(); 2757 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2758 PICLevel::Level picLevel = M->getPICLevel(); 2759 2760 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2761 2762 if (Model == TLSModel::LocalExec) { 2763 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2764 PPCII::MO_TPREL_HA); 2765 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2766 PPCII::MO_TPREL_LO); 2767 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2768 : DAG.getRegister(PPC::R2, MVT::i32); 2769 2770 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2771 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2772 } 2773 2774 if (Model == TLSModel::InitialExec) { 2775 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2776 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2777 PPCII::MO_TLS); 2778 SDValue GOTPtr; 2779 if (is64bit) { 2780 setUsesTOCBasePtr(DAG); 2781 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2782 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2783 PtrVT, GOTReg, TGA); 2784 } else 2785 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2786 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2787 PtrVT, TGA, GOTPtr); 2788 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2789 } 2790 2791 if (Model == TLSModel::GeneralDynamic) { 2792 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2793 SDValue GOTPtr; 2794 if (is64bit) { 2795 setUsesTOCBasePtr(DAG); 2796 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2797 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2798 GOTReg, TGA); 2799 } else { 2800 if (picLevel == PICLevel::SmallPIC) 2801 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2802 else 2803 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2804 } 2805 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2806 GOTPtr, TGA, TGA); 2807 } 2808 2809 if (Model == TLSModel::LocalDynamic) { 2810 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2811 SDValue GOTPtr; 2812 if (is64bit) { 2813 setUsesTOCBasePtr(DAG); 2814 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2815 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2816 GOTReg, TGA); 2817 } else { 2818 if (picLevel == PICLevel::SmallPIC) 2819 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2820 else 2821 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2822 } 2823 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2824 PtrVT, GOTPtr, TGA, TGA); 2825 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2826 PtrVT, TLSAddr, TGA); 2827 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2828 } 2829 2830 llvm_unreachable("Unknown TLS model!"); 2831 } 2832 2833 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2834 SelectionDAG &DAG) const { 2835 EVT PtrVT = Op.getValueType(); 2836 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2837 SDLoc DL(GSDN); 2838 const GlobalValue *GV = GSDN->getGlobal(); 2839 2840 // 64-bit SVR4 ABI code is always position-independent. 2841 // The actual address of the GlobalValue is stored in the TOC. 2842 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2843 setUsesTOCBasePtr(DAG); 2844 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2845 return getTOCEntry(DAG, DL, true, GA); 2846 } 2847 2848 unsigned MOHiFlag, MOLoFlag; 2849 bool IsPIC = isPositionIndependent(); 2850 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2851 2852 if (IsPIC && Subtarget.isSVR4ABI()) { 2853 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2854 GSDN->getOffset(), 2855 PPCII::MO_PIC_FLAG); 2856 return getTOCEntry(DAG, DL, false, GA); 2857 } 2858 2859 SDValue GAHi = 2860 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2861 SDValue GALo = 2862 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2863 2864 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2865 2866 // If the global reference is actually to a non-lazy-pointer, we have to do an 2867 // extra load to get the address of the global. 2868 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2869 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2870 return Ptr; 2871 } 2872 2873 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2874 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2875 SDLoc dl(Op); 2876 2877 if (Op.getValueType() == MVT::v2i64) { 2878 // When the operands themselves are v2i64 values, we need to do something 2879 // special because VSX has no underlying comparison operations for these. 2880 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2881 // Equality can be handled by casting to the legal type for Altivec 2882 // comparisons, everything else needs to be expanded. 2883 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2884 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2885 DAG.getSetCC(dl, MVT::v4i32, 2886 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2887 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2888 CC)); 2889 } 2890 2891 return SDValue(); 2892 } 2893 2894 // We handle most of these in the usual way. 2895 return Op; 2896 } 2897 2898 // If we're comparing for equality to zero, expose the fact that this is 2899 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2900 // fold the new nodes. 2901 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2902 return V; 2903 2904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2905 // Leave comparisons against 0 and -1 alone for now, since they're usually 2906 // optimized. FIXME: revisit this when we can custom lower all setcc 2907 // optimizations. 2908 if (C->isAllOnesValue() || C->isNullValue()) 2909 return SDValue(); 2910 } 2911 2912 // If we have an integer seteq/setne, turn it into a compare against zero 2913 // by xor'ing the rhs with the lhs, which is faster than setting a 2914 // condition register, reading it back out, and masking the correct bit. The 2915 // normal approach here uses sub to do this instead of xor. Using xor exposes 2916 // the result to other bit-twiddling opportunities. 2917 EVT LHSVT = Op.getOperand(0).getValueType(); 2918 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2919 EVT VT = Op.getValueType(); 2920 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2921 Op.getOperand(1)); 2922 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2923 } 2924 return SDValue(); 2925 } 2926 2927 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2928 SDNode *Node = Op.getNode(); 2929 EVT VT = Node->getValueType(0); 2930 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2931 SDValue InChain = Node->getOperand(0); 2932 SDValue VAListPtr = Node->getOperand(1); 2933 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2934 SDLoc dl(Node); 2935 2936 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2937 2938 // gpr_index 2939 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2940 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2941 InChain = GprIndex.getValue(1); 2942 2943 if (VT == MVT::i64) { 2944 // Check if GprIndex is even 2945 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2946 DAG.getConstant(1, dl, MVT::i32)); 2947 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2948 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2949 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2950 DAG.getConstant(1, dl, MVT::i32)); 2951 // Align GprIndex to be even if it isn't 2952 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2953 GprIndex); 2954 } 2955 2956 // fpr index is 1 byte after gpr 2957 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2958 DAG.getConstant(1, dl, MVT::i32)); 2959 2960 // fpr 2961 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2962 FprPtr, MachinePointerInfo(SV), MVT::i8); 2963 InChain = FprIndex.getValue(1); 2964 2965 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2966 DAG.getConstant(8, dl, MVT::i32)); 2967 2968 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2969 DAG.getConstant(4, dl, MVT::i32)); 2970 2971 // areas 2972 SDValue OverflowArea = 2973 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2974 InChain = OverflowArea.getValue(1); 2975 2976 SDValue RegSaveArea = 2977 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2978 InChain = RegSaveArea.getValue(1); 2979 2980 // select overflow_area if index > 8 2981 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2982 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2983 2984 // adjustment constant gpr_index * 4/8 2985 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2986 VT.isInteger() ? GprIndex : FprIndex, 2987 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2988 MVT::i32)); 2989 2990 // OurReg = RegSaveArea + RegConstant 2991 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2992 RegConstant); 2993 2994 // Floating types are 32 bytes into RegSaveArea 2995 if (VT.isFloatingPoint()) 2996 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2997 DAG.getConstant(32, dl, MVT::i32)); 2998 2999 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3000 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3001 VT.isInteger() ? GprIndex : FprIndex, 3002 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3003 MVT::i32)); 3004 3005 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3006 VT.isInteger() ? VAListPtr : FprPtr, 3007 MachinePointerInfo(SV), MVT::i8); 3008 3009 // determine if we should load from reg_save_area or overflow_area 3010 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3011 3012 // increase overflow_area by 4/8 if gpr/fpr > 8 3013 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3014 DAG.getConstant(VT.isInteger() ? 4 : 8, 3015 dl, MVT::i32)); 3016 3017 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3018 OverflowAreaPlusN); 3019 3020 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3021 MachinePointerInfo(), MVT::i32); 3022 3023 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3024 } 3025 3026 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3027 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3028 3029 // We have to copy the entire va_list struct: 3030 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3031 return DAG.getMemcpy(Op.getOperand(0), Op, 3032 Op.getOperand(1), Op.getOperand(2), 3033 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3034 false, MachinePointerInfo(), MachinePointerInfo()); 3035 } 3036 3037 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3038 SelectionDAG &DAG) const { 3039 return Op.getOperand(0); 3040 } 3041 3042 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3043 SelectionDAG &DAG) const { 3044 SDValue Chain = Op.getOperand(0); 3045 SDValue Trmp = Op.getOperand(1); // trampoline 3046 SDValue FPtr = Op.getOperand(2); // nested function 3047 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3048 SDLoc dl(Op); 3049 3050 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3051 bool isPPC64 = (PtrVT == MVT::i64); 3052 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3053 3054 TargetLowering::ArgListTy Args; 3055 TargetLowering::ArgListEntry Entry; 3056 3057 Entry.Ty = IntPtrTy; 3058 Entry.Node = Trmp; Args.push_back(Entry); 3059 3060 // TrampSize == (isPPC64 ? 48 : 40); 3061 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3062 isPPC64 ? MVT::i64 : MVT::i32); 3063 Args.push_back(Entry); 3064 3065 Entry.Node = FPtr; Args.push_back(Entry); 3066 Entry.Node = Nest; Args.push_back(Entry); 3067 3068 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3069 TargetLowering::CallLoweringInfo CLI(DAG); 3070 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3071 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3072 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3073 3074 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3075 return CallResult.second; 3076 } 3077 3078 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3079 MachineFunction &MF = DAG.getMachineFunction(); 3080 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3081 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3082 3083 SDLoc dl(Op); 3084 3085 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3086 // vastart just stores the address of the VarArgsFrameIndex slot into the 3087 // memory location argument. 3088 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3089 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3090 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3091 MachinePointerInfo(SV)); 3092 } 3093 3094 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3095 // We suppose the given va_list is already allocated. 3096 // 3097 // typedef struct { 3098 // char gpr; /* index into the array of 8 GPRs 3099 // * stored in the register save area 3100 // * gpr=0 corresponds to r3, 3101 // * gpr=1 to r4, etc. 3102 // */ 3103 // char fpr; /* index into the array of 8 FPRs 3104 // * stored in the register save area 3105 // * fpr=0 corresponds to f1, 3106 // * fpr=1 to f2, etc. 3107 // */ 3108 // char *overflow_arg_area; 3109 // /* location on stack that holds 3110 // * the next overflow argument 3111 // */ 3112 // char *reg_save_area; 3113 // /* where r3:r10 and f1:f8 (if saved) 3114 // * are stored 3115 // */ 3116 // } va_list[1]; 3117 3118 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3119 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3120 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3121 PtrVT); 3122 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3123 PtrVT); 3124 3125 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3126 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3127 3128 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3129 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3130 3131 uint64_t FPROffset = 1; 3132 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3133 3134 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3135 3136 // Store first byte : number of int regs 3137 SDValue firstStore = 3138 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3139 MachinePointerInfo(SV), MVT::i8); 3140 uint64_t nextOffset = FPROffset; 3141 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3142 ConstFPROffset); 3143 3144 // Store second byte : number of float regs 3145 SDValue secondStore = 3146 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3147 MachinePointerInfo(SV, nextOffset), MVT::i8); 3148 nextOffset += StackOffset; 3149 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3150 3151 // Store second word : arguments given on stack 3152 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3153 MachinePointerInfo(SV, nextOffset)); 3154 nextOffset += FrameOffset; 3155 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3156 3157 // Store third word : arguments given in registers 3158 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3159 MachinePointerInfo(SV, nextOffset)); 3160 } 3161 3162 /// FPR - The set of FP registers that should be allocated for arguments, 3163 /// on Darwin. 3164 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3165 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3166 PPC::F11, PPC::F12, PPC::F13}; 3167 3168 /// QFPR - The set of QPX registers that should be allocated for arguments. 3169 static const MCPhysReg QFPR[] = { 3170 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3171 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3172 3173 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3174 /// the stack. 3175 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3176 unsigned PtrByteSize) { 3177 unsigned ArgSize = ArgVT.getStoreSize(); 3178 if (Flags.isByVal()) 3179 ArgSize = Flags.getByValSize(); 3180 3181 // Round up to multiples of the pointer size, except for array members, 3182 // which are always packed. 3183 if (!Flags.isInConsecutiveRegs()) 3184 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3185 3186 return ArgSize; 3187 } 3188 3189 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3190 /// on the stack. 3191 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3192 ISD::ArgFlagsTy Flags, 3193 unsigned PtrByteSize) { 3194 unsigned Align = PtrByteSize; 3195 3196 // Altivec parameters are padded to a 16 byte boundary. 3197 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3198 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3199 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3200 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3201 Align = 16; 3202 // QPX vector types stored in double-precision are padded to a 32 byte 3203 // boundary. 3204 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3205 Align = 32; 3206 3207 // ByVal parameters are aligned as requested. 3208 if (Flags.isByVal()) { 3209 unsigned BVAlign = Flags.getByValAlign(); 3210 if (BVAlign > PtrByteSize) { 3211 if (BVAlign % PtrByteSize != 0) 3212 llvm_unreachable( 3213 "ByVal alignment is not a multiple of the pointer size"); 3214 3215 Align = BVAlign; 3216 } 3217 } 3218 3219 // Array members are always packed to their original alignment. 3220 if (Flags.isInConsecutiveRegs()) { 3221 // If the array member was split into multiple registers, the first 3222 // needs to be aligned to the size of the full type. (Except for 3223 // ppcf128, which is only aligned as its f64 components.) 3224 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3225 Align = OrigVT.getStoreSize(); 3226 else 3227 Align = ArgVT.getStoreSize(); 3228 } 3229 3230 return Align; 3231 } 3232 3233 /// CalculateStackSlotUsed - Return whether this argument will use its 3234 /// stack slot (instead of being passed in registers). ArgOffset, 3235 /// AvailableFPRs, and AvailableVRs must hold the current argument 3236 /// position, and will be updated to account for this argument. 3237 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3238 ISD::ArgFlagsTy Flags, 3239 unsigned PtrByteSize, 3240 unsigned LinkageSize, 3241 unsigned ParamAreaSize, 3242 unsigned &ArgOffset, 3243 unsigned &AvailableFPRs, 3244 unsigned &AvailableVRs, bool HasQPX) { 3245 bool UseMemory = false; 3246 3247 // Respect alignment of argument on the stack. 3248 unsigned Align = 3249 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3250 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3251 // If there's no space left in the argument save area, we must 3252 // use memory (this check also catches zero-sized arguments). 3253 if (ArgOffset >= LinkageSize + ParamAreaSize) 3254 UseMemory = true; 3255 3256 // Allocate argument on the stack. 3257 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3258 if (Flags.isInConsecutiveRegsLast()) 3259 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3260 // If we overran the argument save area, we must use memory 3261 // (this check catches arguments passed partially in memory) 3262 if (ArgOffset > LinkageSize + ParamAreaSize) 3263 UseMemory = true; 3264 3265 // However, if the argument is actually passed in an FPR or a VR, 3266 // we don't use memory after all. 3267 if (!Flags.isByVal()) { 3268 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3269 // QPX registers overlap with the scalar FP registers. 3270 (HasQPX && (ArgVT == MVT::v4f32 || 3271 ArgVT == MVT::v4f64 || 3272 ArgVT == MVT::v4i1))) 3273 if (AvailableFPRs > 0) { 3274 --AvailableFPRs; 3275 return false; 3276 } 3277 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3278 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3279 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3280 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3281 if (AvailableVRs > 0) { 3282 --AvailableVRs; 3283 return false; 3284 } 3285 } 3286 3287 return UseMemory; 3288 } 3289 3290 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3291 /// ensure minimum alignment required for target. 3292 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3293 unsigned NumBytes) { 3294 unsigned TargetAlign = Lowering->getStackAlignment(); 3295 unsigned AlignMask = TargetAlign - 1; 3296 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3297 return NumBytes; 3298 } 3299 3300 SDValue PPCTargetLowering::LowerFormalArguments( 3301 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3302 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3303 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3304 if (Subtarget.isSVR4ABI()) { 3305 if (Subtarget.isPPC64()) 3306 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3307 dl, DAG, InVals); 3308 else 3309 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3310 dl, DAG, InVals); 3311 } else { 3312 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3313 dl, DAG, InVals); 3314 } 3315 } 3316 3317 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3318 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3319 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3320 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3321 3322 // 32-bit SVR4 ABI Stack Frame Layout: 3323 // +-----------------------------------+ 3324 // +--> | Back chain | 3325 // | +-----------------------------------+ 3326 // | | Floating-point register save area | 3327 // | +-----------------------------------+ 3328 // | | General register save area | 3329 // | +-----------------------------------+ 3330 // | | CR save word | 3331 // | +-----------------------------------+ 3332 // | | VRSAVE save word | 3333 // | +-----------------------------------+ 3334 // | | Alignment padding | 3335 // | +-----------------------------------+ 3336 // | | Vector register save area | 3337 // | +-----------------------------------+ 3338 // | | Local variable space | 3339 // | +-----------------------------------+ 3340 // | | Parameter list area | 3341 // | +-----------------------------------+ 3342 // | | LR save word | 3343 // | +-----------------------------------+ 3344 // SP--> +--- | Back chain | 3345 // +-----------------------------------+ 3346 // 3347 // Specifications: 3348 // System V Application Binary Interface PowerPC Processor Supplement 3349 // AltiVec Technology Programming Interface Manual 3350 3351 MachineFunction &MF = DAG.getMachineFunction(); 3352 MachineFrameInfo &MFI = MF.getFrameInfo(); 3353 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3354 3355 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3356 // Potential tail calls could cause overwriting of argument stack slots. 3357 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3358 (CallConv == CallingConv::Fast)); 3359 unsigned PtrByteSize = 4; 3360 3361 // Assign locations to all of the incoming arguments. 3362 SmallVector<CCValAssign, 16> ArgLocs; 3363 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3364 *DAG.getContext()); 3365 3366 // Reserve space for the linkage area on the stack. 3367 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3368 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3369 if (useSoftFloat() || hasSPE()) 3370 CCInfo.PreAnalyzeFormalArguments(Ins); 3371 3372 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3373 CCInfo.clearWasPPCF128(); 3374 3375 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3376 CCValAssign &VA = ArgLocs[i]; 3377 3378 // Arguments stored in registers. 3379 if (VA.isRegLoc()) { 3380 const TargetRegisterClass *RC; 3381 EVT ValVT = VA.getValVT(); 3382 3383 switch (ValVT.getSimpleVT().SimpleTy) { 3384 default: 3385 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3386 case MVT::i1: 3387 case MVT::i32: 3388 RC = &PPC::GPRCRegClass; 3389 break; 3390 case MVT::f32: 3391 if (Subtarget.hasP8Vector()) 3392 RC = &PPC::VSSRCRegClass; 3393 else if (Subtarget.hasSPE()) 3394 RC = &PPC::SPE4RCRegClass; 3395 else 3396 RC = &PPC::F4RCRegClass; 3397 break; 3398 case MVT::f64: 3399 if (Subtarget.hasVSX()) 3400 RC = &PPC::VSFRCRegClass; 3401 else if (Subtarget.hasSPE()) 3402 RC = &PPC::SPERCRegClass; 3403 else 3404 RC = &PPC::F8RCRegClass; 3405 break; 3406 case MVT::v16i8: 3407 case MVT::v8i16: 3408 case MVT::v4i32: 3409 RC = &PPC::VRRCRegClass; 3410 break; 3411 case MVT::v4f32: 3412 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3413 break; 3414 case MVT::v2f64: 3415 case MVT::v2i64: 3416 RC = &PPC::VRRCRegClass; 3417 break; 3418 case MVT::v4f64: 3419 RC = &PPC::QFRCRegClass; 3420 break; 3421 case MVT::v4i1: 3422 RC = &PPC::QBRCRegClass; 3423 break; 3424 } 3425 3426 // Transform the arguments stored in physical registers into virtual ones. 3427 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3428 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3429 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3430 3431 if (ValVT == MVT::i1) 3432 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3433 3434 InVals.push_back(ArgValue); 3435 } else { 3436 // Argument stored in memory. 3437 assert(VA.isMemLoc()); 3438 3439 // Get the extended size of the argument type in stack 3440 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3441 // Get the actual size of the argument type 3442 unsigned ObjSize = VA.getValVT().getStoreSize(); 3443 unsigned ArgOffset = VA.getLocMemOffset(); 3444 // Stack objects in PPC32 are right justified. 3445 ArgOffset += ArgSize - ObjSize; 3446 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3447 3448 // Create load nodes to retrieve arguments from the stack. 3449 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3450 InVals.push_back( 3451 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3452 } 3453 } 3454 3455 // Assign locations to all of the incoming aggregate by value arguments. 3456 // Aggregates passed by value are stored in the local variable space of the 3457 // caller's stack frame, right above the parameter list area. 3458 SmallVector<CCValAssign, 16> ByValArgLocs; 3459 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3460 ByValArgLocs, *DAG.getContext()); 3461 3462 // Reserve stack space for the allocations in CCInfo. 3463 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3464 3465 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3466 3467 // Area that is at least reserved in the caller of this function. 3468 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3469 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3470 3471 // Set the size that is at least reserved in caller of this function. Tail 3472 // call optimized function's reserved stack space needs to be aligned so that 3473 // taking the difference between two stack areas will result in an aligned 3474 // stack. 3475 MinReservedArea = 3476 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3477 FuncInfo->setMinReservedArea(MinReservedArea); 3478 3479 SmallVector<SDValue, 8> MemOps; 3480 3481 // If the function takes variable number of arguments, make a frame index for 3482 // the start of the first vararg value... for expansion of llvm.va_start. 3483 if (isVarArg) { 3484 static const MCPhysReg GPArgRegs[] = { 3485 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3486 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3487 }; 3488 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3489 3490 static const MCPhysReg FPArgRegs[] = { 3491 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3492 PPC::F8 3493 }; 3494 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3495 3496 if (useSoftFloat() || hasSPE()) 3497 NumFPArgRegs = 0; 3498 3499 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3500 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3501 3502 // Make room for NumGPArgRegs and NumFPArgRegs. 3503 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3504 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3505 3506 FuncInfo->setVarArgsStackOffset( 3507 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3508 CCInfo.getNextStackOffset(), true)); 3509 3510 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3511 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3512 3513 // The fixed integer arguments of a variadic function are stored to the 3514 // VarArgsFrameIndex on the stack so that they may be loaded by 3515 // dereferencing the result of va_next. 3516 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3517 // Get an existing live-in vreg, or add a new one. 3518 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3519 if (!VReg) 3520 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3521 3522 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3523 SDValue Store = 3524 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3525 MemOps.push_back(Store); 3526 // Increment the address by four for the next argument to store 3527 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3528 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3529 } 3530 3531 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3532 // is set. 3533 // The double arguments are stored to the VarArgsFrameIndex 3534 // on the stack. 3535 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3536 // Get an existing live-in vreg, or add a new one. 3537 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3538 if (!VReg) 3539 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3540 3541 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3542 SDValue Store = 3543 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3544 MemOps.push_back(Store); 3545 // Increment the address by eight for the next argument to store 3546 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3547 PtrVT); 3548 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3549 } 3550 } 3551 3552 if (!MemOps.empty()) 3553 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3554 3555 return Chain; 3556 } 3557 3558 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3559 // value to MVT::i64 and then truncate to the correct register size. 3560 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3561 EVT ObjectVT, SelectionDAG &DAG, 3562 SDValue ArgVal, 3563 const SDLoc &dl) const { 3564 if (Flags.isSExt()) 3565 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3566 DAG.getValueType(ObjectVT)); 3567 else if (Flags.isZExt()) 3568 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3569 DAG.getValueType(ObjectVT)); 3570 3571 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3572 } 3573 3574 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3575 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3576 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3577 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3578 // TODO: add description of PPC stack frame format, or at least some docs. 3579 // 3580 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3581 bool isLittleEndian = Subtarget.isLittleEndian(); 3582 MachineFunction &MF = DAG.getMachineFunction(); 3583 MachineFrameInfo &MFI = MF.getFrameInfo(); 3584 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3585 3586 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3587 "fastcc not supported on varargs functions"); 3588 3589 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3590 // Potential tail calls could cause overwriting of argument stack slots. 3591 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3592 (CallConv == CallingConv::Fast)); 3593 unsigned PtrByteSize = 8; 3594 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3595 3596 static const MCPhysReg GPR[] = { 3597 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3598 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3599 }; 3600 static const MCPhysReg VR[] = { 3601 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3602 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3603 }; 3604 3605 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3606 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3607 const unsigned Num_VR_Regs = array_lengthof(VR); 3608 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3609 3610 // Do a first pass over the arguments to determine whether the ABI 3611 // guarantees that our caller has allocated the parameter save area 3612 // on its stack frame. In the ELFv1 ABI, this is always the case; 3613 // in the ELFv2 ABI, it is true if this is a vararg function or if 3614 // any parameter is located in a stack slot. 3615 3616 bool HasParameterArea = !isELFv2ABI || isVarArg; 3617 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3618 unsigned NumBytes = LinkageSize; 3619 unsigned AvailableFPRs = Num_FPR_Regs; 3620 unsigned AvailableVRs = Num_VR_Regs; 3621 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3622 if (Ins[i].Flags.isNest()) 3623 continue; 3624 3625 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3626 PtrByteSize, LinkageSize, ParamAreaSize, 3627 NumBytes, AvailableFPRs, AvailableVRs, 3628 Subtarget.hasQPX())) 3629 HasParameterArea = true; 3630 } 3631 3632 // Add DAG nodes to load the arguments or copy them out of registers. On 3633 // entry to a function on PPC, the arguments start after the linkage area, 3634 // although the first ones are often in registers. 3635 3636 unsigned ArgOffset = LinkageSize; 3637 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3638 unsigned &QFPR_idx = FPR_idx; 3639 SmallVector<SDValue, 8> MemOps; 3640 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3641 unsigned CurArgIdx = 0; 3642 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3643 SDValue ArgVal; 3644 bool needsLoad = false; 3645 EVT ObjectVT = Ins[ArgNo].VT; 3646 EVT OrigVT = Ins[ArgNo].ArgVT; 3647 unsigned ObjSize = ObjectVT.getStoreSize(); 3648 unsigned ArgSize = ObjSize; 3649 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3650 if (Ins[ArgNo].isOrigArg()) { 3651 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3652 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3653 } 3654 // We re-align the argument offset for each argument, except when using the 3655 // fast calling convention, when we need to make sure we do that only when 3656 // we'll actually use a stack slot. 3657 unsigned CurArgOffset, Align; 3658 auto ComputeArgOffset = [&]() { 3659 /* Respect alignment of argument on the stack. */ 3660 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3661 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3662 CurArgOffset = ArgOffset; 3663 }; 3664 3665 if (CallConv != CallingConv::Fast) { 3666 ComputeArgOffset(); 3667 3668 /* Compute GPR index associated with argument offset. */ 3669 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3670 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3671 } 3672 3673 // FIXME the codegen can be much improved in some cases. 3674 // We do not have to keep everything in memory. 3675 if (Flags.isByVal()) { 3676 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3677 3678 if (CallConv == CallingConv::Fast) 3679 ComputeArgOffset(); 3680 3681 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3682 ObjSize = Flags.getByValSize(); 3683 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3684 // Empty aggregate parameters do not take up registers. Examples: 3685 // struct { } a; 3686 // union { } b; 3687 // int c[0]; 3688 // etc. However, we have to provide a place-holder in InVals, so 3689 // pretend we have an 8-byte item at the current address for that 3690 // purpose. 3691 if (!ObjSize) { 3692 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3693 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3694 InVals.push_back(FIN); 3695 continue; 3696 } 3697 3698 // Create a stack object covering all stack doublewords occupied 3699 // by the argument. If the argument is (fully or partially) on 3700 // the stack, or if the argument is fully in registers but the 3701 // caller has allocated the parameter save anyway, we can refer 3702 // directly to the caller's stack frame. Otherwise, create a 3703 // local copy in our own frame. 3704 int FI; 3705 if (HasParameterArea || 3706 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3707 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3708 else 3709 FI = MFI.CreateStackObject(ArgSize, Align, false); 3710 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3711 3712 // Handle aggregates smaller than 8 bytes. 3713 if (ObjSize < PtrByteSize) { 3714 // The value of the object is its address, which differs from the 3715 // address of the enclosing doubleword on big-endian systems. 3716 SDValue Arg = FIN; 3717 if (!isLittleEndian) { 3718 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3719 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3720 } 3721 InVals.push_back(Arg); 3722 3723 if (GPR_idx != Num_GPR_Regs) { 3724 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3725 FuncInfo->addLiveInAttr(VReg, Flags); 3726 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3727 SDValue Store; 3728 3729 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3730 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3731 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3732 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3733 MachinePointerInfo(&*FuncArg), ObjType); 3734 } else { 3735 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3736 // store the whole register as-is to the parameter save area 3737 // slot. 3738 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3739 MachinePointerInfo(&*FuncArg)); 3740 } 3741 3742 MemOps.push_back(Store); 3743 } 3744 // Whether we copied from a register or not, advance the offset 3745 // into the parameter save area by a full doubleword. 3746 ArgOffset += PtrByteSize; 3747 continue; 3748 } 3749 3750 // The value of the object is its address, which is the address of 3751 // its first stack doubleword. 3752 InVals.push_back(FIN); 3753 3754 // Store whatever pieces of the object are in registers to memory. 3755 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3756 if (GPR_idx == Num_GPR_Regs) 3757 break; 3758 3759 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3760 FuncInfo->addLiveInAttr(VReg, Flags); 3761 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3762 SDValue Addr = FIN; 3763 if (j) { 3764 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3765 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3766 } 3767 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3768 MachinePointerInfo(&*FuncArg, j)); 3769 MemOps.push_back(Store); 3770 ++GPR_idx; 3771 } 3772 ArgOffset += ArgSize; 3773 continue; 3774 } 3775 3776 switch (ObjectVT.getSimpleVT().SimpleTy) { 3777 default: llvm_unreachable("Unhandled argument type!"); 3778 case MVT::i1: 3779 case MVT::i32: 3780 case MVT::i64: 3781 if (Flags.isNest()) { 3782 // The 'nest' parameter, if any, is passed in R11. 3783 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3784 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3785 3786 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3787 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3788 3789 break; 3790 } 3791 3792 // These can be scalar arguments or elements of an integer array type 3793 // passed directly. Clang may use those instead of "byval" aggregate 3794 // types to avoid forcing arguments to memory unnecessarily. 3795 if (GPR_idx != Num_GPR_Regs) { 3796 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3797 FuncInfo->addLiveInAttr(VReg, Flags); 3798 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3799 3800 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3801 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3802 // value to MVT::i64 and then truncate to the correct register size. 3803 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3804 } else { 3805 if (CallConv == CallingConv::Fast) 3806 ComputeArgOffset(); 3807 3808 needsLoad = true; 3809 ArgSize = PtrByteSize; 3810 } 3811 if (CallConv != CallingConv::Fast || needsLoad) 3812 ArgOffset += 8; 3813 break; 3814 3815 case MVT::f32: 3816 case MVT::f64: 3817 // These can be scalar arguments or elements of a float array type 3818 // passed directly. The latter are used to implement ELFv2 homogenous 3819 // float aggregates. 3820 if (FPR_idx != Num_FPR_Regs) { 3821 unsigned VReg; 3822 3823 if (ObjectVT == MVT::f32) 3824 VReg = MF.addLiveIn(FPR[FPR_idx], 3825 Subtarget.hasP8Vector() 3826 ? &PPC::VSSRCRegClass 3827 : &PPC::F4RCRegClass); 3828 else 3829 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3830 ? &PPC::VSFRCRegClass 3831 : &PPC::F8RCRegClass); 3832 3833 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3834 ++FPR_idx; 3835 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3836 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3837 // once we support fp <-> gpr moves. 3838 3839 // This can only ever happen in the presence of f32 array types, 3840 // since otherwise we never run out of FPRs before running out 3841 // of GPRs. 3842 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3843 FuncInfo->addLiveInAttr(VReg, Flags); 3844 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3845 3846 if (ObjectVT == MVT::f32) { 3847 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3848 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3849 DAG.getConstant(32, dl, MVT::i32)); 3850 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3851 } 3852 3853 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3854 } else { 3855 if (CallConv == CallingConv::Fast) 3856 ComputeArgOffset(); 3857 3858 needsLoad = true; 3859 } 3860 3861 // When passing an array of floats, the array occupies consecutive 3862 // space in the argument area; only round up to the next doubleword 3863 // at the end of the array. Otherwise, each float takes 8 bytes. 3864 if (CallConv != CallingConv::Fast || needsLoad) { 3865 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3866 ArgOffset += ArgSize; 3867 if (Flags.isInConsecutiveRegsLast()) 3868 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3869 } 3870 break; 3871 case MVT::v4f32: 3872 case MVT::v4i32: 3873 case MVT::v8i16: 3874 case MVT::v16i8: 3875 case MVT::v2f64: 3876 case MVT::v2i64: 3877 case MVT::v1i128: 3878 case MVT::f128: 3879 if (!Subtarget.hasQPX()) { 3880 // These can be scalar arguments or elements of a vector array type 3881 // passed directly. The latter are used to implement ELFv2 homogenous 3882 // vector aggregates. 3883 if (VR_idx != Num_VR_Regs) { 3884 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3885 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3886 ++VR_idx; 3887 } else { 3888 if (CallConv == CallingConv::Fast) 3889 ComputeArgOffset(); 3890 needsLoad = true; 3891 } 3892 if (CallConv != CallingConv::Fast || needsLoad) 3893 ArgOffset += 16; 3894 break; 3895 } // not QPX 3896 3897 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3898 "Invalid QPX parameter type"); 3899 LLVM_FALLTHROUGH; 3900 3901 case MVT::v4f64: 3902 case MVT::v4i1: 3903 // QPX vectors are treated like their scalar floating-point subregisters 3904 // (except that they're larger). 3905 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3906 if (QFPR_idx != Num_QFPR_Regs) { 3907 const TargetRegisterClass *RC; 3908 switch (ObjectVT.getSimpleVT().SimpleTy) { 3909 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3910 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3911 default: RC = &PPC::QBRCRegClass; break; 3912 } 3913 3914 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3915 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3916 ++QFPR_idx; 3917 } else { 3918 if (CallConv == CallingConv::Fast) 3919 ComputeArgOffset(); 3920 needsLoad = true; 3921 } 3922 if (CallConv != CallingConv::Fast || needsLoad) 3923 ArgOffset += Sz; 3924 break; 3925 } 3926 3927 // We need to load the argument to a virtual register if we determined 3928 // above that we ran out of physical registers of the appropriate type. 3929 if (needsLoad) { 3930 if (ObjSize < ArgSize && !isLittleEndian) 3931 CurArgOffset += ArgSize - ObjSize; 3932 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3933 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3934 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3935 } 3936 3937 InVals.push_back(ArgVal); 3938 } 3939 3940 // Area that is at least reserved in the caller of this function. 3941 unsigned MinReservedArea; 3942 if (HasParameterArea) 3943 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3944 else 3945 MinReservedArea = LinkageSize; 3946 3947 // Set the size that is at least reserved in caller of this function. Tail 3948 // call optimized functions' reserved stack space needs to be aligned so that 3949 // taking the difference between two stack areas will result in an aligned 3950 // stack. 3951 MinReservedArea = 3952 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3953 FuncInfo->setMinReservedArea(MinReservedArea); 3954 3955 // If the function takes variable number of arguments, make a frame index for 3956 // the start of the first vararg value... for expansion of llvm.va_start. 3957 if (isVarArg) { 3958 int Depth = ArgOffset; 3959 3960 FuncInfo->setVarArgsFrameIndex( 3961 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3962 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3963 3964 // If this function is vararg, store any remaining integer argument regs 3965 // to their spots on the stack so that they may be loaded by dereferencing 3966 // the result of va_next. 3967 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3968 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3969 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3970 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3971 SDValue Store = 3972 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3973 MemOps.push_back(Store); 3974 // Increment the address by four for the next argument to store 3975 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3976 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3977 } 3978 } 3979 3980 if (!MemOps.empty()) 3981 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3982 3983 return Chain; 3984 } 3985 3986 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3987 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3988 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3989 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3990 // TODO: add description of PPC stack frame format, or at least some docs. 3991 // 3992 MachineFunction &MF = DAG.getMachineFunction(); 3993 MachineFrameInfo &MFI = MF.getFrameInfo(); 3994 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3995 3996 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3997 bool isPPC64 = PtrVT == MVT::i64; 3998 // Potential tail calls could cause overwriting of argument stack slots. 3999 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4000 (CallConv == CallingConv::Fast)); 4001 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4002 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4003 unsigned ArgOffset = LinkageSize; 4004 // Area that is at least reserved in caller of this function. 4005 unsigned MinReservedArea = ArgOffset; 4006 4007 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4008 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4009 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4010 }; 4011 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4012 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4013 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4014 }; 4015 static const MCPhysReg VR[] = { 4016 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4017 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4018 }; 4019 4020 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4021 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4022 const unsigned Num_VR_Regs = array_lengthof( VR); 4023 4024 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4025 4026 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4027 4028 // In 32-bit non-varargs functions, the stack space for vectors is after the 4029 // stack space for non-vectors. We do not use this space unless we have 4030 // too many vectors to fit in registers, something that only occurs in 4031 // constructed examples:), but we have to walk the arglist to figure 4032 // that out...for the pathological case, compute VecArgOffset as the 4033 // start of the vector parameter area. Computing VecArgOffset is the 4034 // entire point of the following loop. 4035 unsigned VecArgOffset = ArgOffset; 4036 if (!isVarArg && !isPPC64) { 4037 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4038 ++ArgNo) { 4039 EVT ObjectVT = Ins[ArgNo].VT; 4040 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4041 4042 if (Flags.isByVal()) { 4043 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4044 unsigned ObjSize = Flags.getByValSize(); 4045 unsigned ArgSize = 4046 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4047 VecArgOffset += ArgSize; 4048 continue; 4049 } 4050 4051 switch(ObjectVT.getSimpleVT().SimpleTy) { 4052 default: llvm_unreachable("Unhandled argument type!"); 4053 case MVT::i1: 4054 case MVT::i32: 4055 case MVT::f32: 4056 VecArgOffset += 4; 4057 break; 4058 case MVT::i64: // PPC64 4059 case MVT::f64: 4060 // FIXME: We are guaranteed to be !isPPC64 at this point. 4061 // Does MVT::i64 apply? 4062 VecArgOffset += 8; 4063 break; 4064 case MVT::v4f32: 4065 case MVT::v4i32: 4066 case MVT::v8i16: 4067 case MVT::v16i8: 4068 // Nothing to do, we're only looking at Nonvector args here. 4069 break; 4070 } 4071 } 4072 } 4073 // We've found where the vector parameter area in memory is. Skip the 4074 // first 12 parameters; these don't use that memory. 4075 VecArgOffset = ((VecArgOffset+15)/16)*16; 4076 VecArgOffset += 12*16; 4077 4078 // Add DAG nodes to load the arguments or copy them out of registers. On 4079 // entry to a function on PPC, the arguments start after the linkage area, 4080 // although the first ones are often in registers. 4081 4082 SmallVector<SDValue, 8> MemOps; 4083 unsigned nAltivecParamsAtEnd = 0; 4084 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4085 unsigned CurArgIdx = 0; 4086 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4087 SDValue ArgVal; 4088 bool needsLoad = false; 4089 EVT ObjectVT = Ins[ArgNo].VT; 4090 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4091 unsigned ArgSize = ObjSize; 4092 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4093 if (Ins[ArgNo].isOrigArg()) { 4094 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4095 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4096 } 4097 unsigned CurArgOffset = ArgOffset; 4098 4099 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4100 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4101 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4102 if (isVarArg || isPPC64) { 4103 MinReservedArea = ((MinReservedArea+15)/16)*16; 4104 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4105 Flags, 4106 PtrByteSize); 4107 } else nAltivecParamsAtEnd++; 4108 } else 4109 // Calculate min reserved area. 4110 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4111 Flags, 4112 PtrByteSize); 4113 4114 // FIXME the codegen can be much improved in some cases. 4115 // We do not have to keep everything in memory. 4116 if (Flags.isByVal()) { 4117 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4118 4119 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4120 ObjSize = Flags.getByValSize(); 4121 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4122 // Objects of size 1 and 2 are right justified, everything else is 4123 // left justified. This means the memory address is adjusted forwards. 4124 if (ObjSize==1 || ObjSize==2) { 4125 CurArgOffset = CurArgOffset + (4 - ObjSize); 4126 } 4127 // The value of the object is its address. 4128 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4129 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4130 InVals.push_back(FIN); 4131 if (ObjSize==1 || ObjSize==2) { 4132 if (GPR_idx != Num_GPR_Regs) { 4133 unsigned VReg; 4134 if (isPPC64) 4135 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4136 else 4137 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4138 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4139 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4140 SDValue Store = 4141 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4142 MachinePointerInfo(&*FuncArg), ObjType); 4143 MemOps.push_back(Store); 4144 ++GPR_idx; 4145 } 4146 4147 ArgOffset += PtrByteSize; 4148 4149 continue; 4150 } 4151 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4152 // Store whatever pieces of the object are in registers 4153 // to memory. ArgOffset will be the address of the beginning 4154 // of the object. 4155 if (GPR_idx != Num_GPR_Regs) { 4156 unsigned VReg; 4157 if (isPPC64) 4158 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4159 else 4160 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4161 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4163 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4164 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4165 MachinePointerInfo(&*FuncArg, j)); 4166 MemOps.push_back(Store); 4167 ++GPR_idx; 4168 ArgOffset += PtrByteSize; 4169 } else { 4170 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4171 break; 4172 } 4173 } 4174 continue; 4175 } 4176 4177 switch (ObjectVT.getSimpleVT().SimpleTy) { 4178 default: llvm_unreachable("Unhandled argument type!"); 4179 case MVT::i1: 4180 case MVT::i32: 4181 if (!isPPC64) { 4182 if (GPR_idx != Num_GPR_Regs) { 4183 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4184 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4185 4186 if (ObjectVT == MVT::i1) 4187 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4188 4189 ++GPR_idx; 4190 } else { 4191 needsLoad = true; 4192 ArgSize = PtrByteSize; 4193 } 4194 // All int arguments reserve stack space in the Darwin ABI. 4195 ArgOffset += PtrByteSize; 4196 break; 4197 } 4198 LLVM_FALLTHROUGH; 4199 case MVT::i64: // PPC64 4200 if (GPR_idx != Num_GPR_Regs) { 4201 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4202 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4203 4204 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4205 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4206 // value to MVT::i64 and then truncate to the correct register size. 4207 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4208 4209 ++GPR_idx; 4210 } else { 4211 needsLoad = true; 4212 ArgSize = PtrByteSize; 4213 } 4214 // All int arguments reserve stack space in the Darwin ABI. 4215 ArgOffset += 8; 4216 break; 4217 4218 case MVT::f32: 4219 case MVT::f64: 4220 // Every 4 bytes of argument space consumes one of the GPRs available for 4221 // argument passing. 4222 if (GPR_idx != Num_GPR_Regs) { 4223 ++GPR_idx; 4224 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4225 ++GPR_idx; 4226 } 4227 if (FPR_idx != Num_FPR_Regs) { 4228 unsigned VReg; 4229 4230 if (ObjectVT == MVT::f32) 4231 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4232 else 4233 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4234 4235 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4236 ++FPR_idx; 4237 } else { 4238 needsLoad = true; 4239 } 4240 4241 // All FP arguments reserve stack space in the Darwin ABI. 4242 ArgOffset += isPPC64 ? 8 : ObjSize; 4243 break; 4244 case MVT::v4f32: 4245 case MVT::v4i32: 4246 case MVT::v8i16: 4247 case MVT::v16i8: 4248 // Note that vector arguments in registers don't reserve stack space, 4249 // except in varargs functions. 4250 if (VR_idx != Num_VR_Regs) { 4251 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4252 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4253 if (isVarArg) { 4254 while ((ArgOffset % 16) != 0) { 4255 ArgOffset += PtrByteSize; 4256 if (GPR_idx != Num_GPR_Regs) 4257 GPR_idx++; 4258 } 4259 ArgOffset += 16; 4260 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4261 } 4262 ++VR_idx; 4263 } else { 4264 if (!isVarArg && !isPPC64) { 4265 // Vectors go after all the nonvectors. 4266 CurArgOffset = VecArgOffset; 4267 VecArgOffset += 16; 4268 } else { 4269 // Vectors are aligned. 4270 ArgOffset = ((ArgOffset+15)/16)*16; 4271 CurArgOffset = ArgOffset; 4272 ArgOffset += 16; 4273 } 4274 needsLoad = true; 4275 } 4276 break; 4277 } 4278 4279 // We need to load the argument to a virtual register if we determined above 4280 // that we ran out of physical registers of the appropriate type. 4281 if (needsLoad) { 4282 int FI = MFI.CreateFixedObject(ObjSize, 4283 CurArgOffset + (ArgSize - ObjSize), 4284 isImmutable); 4285 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4286 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4287 } 4288 4289 InVals.push_back(ArgVal); 4290 } 4291 4292 // Allow for Altivec parameters at the end, if needed. 4293 if (nAltivecParamsAtEnd) { 4294 MinReservedArea = ((MinReservedArea+15)/16)*16; 4295 MinReservedArea += 16*nAltivecParamsAtEnd; 4296 } 4297 4298 // Area that is at least reserved in the caller of this function. 4299 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4300 4301 // Set the size that is at least reserved in caller of this function. Tail 4302 // call optimized functions' reserved stack space needs to be aligned so that 4303 // taking the difference between two stack areas will result in an aligned 4304 // stack. 4305 MinReservedArea = 4306 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4307 FuncInfo->setMinReservedArea(MinReservedArea); 4308 4309 // If the function takes variable number of arguments, make a frame index for 4310 // the start of the first vararg value... for expansion of llvm.va_start. 4311 if (isVarArg) { 4312 int Depth = ArgOffset; 4313 4314 FuncInfo->setVarArgsFrameIndex( 4315 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4316 Depth, true)); 4317 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4318 4319 // If this function is vararg, store any remaining integer argument regs 4320 // to their spots on the stack so that they may be loaded by dereferencing 4321 // the result of va_next. 4322 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4323 unsigned VReg; 4324 4325 if (isPPC64) 4326 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4327 else 4328 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4329 4330 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4331 SDValue Store = 4332 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4333 MemOps.push_back(Store); 4334 // Increment the address by four for the next argument to store 4335 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4336 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4337 } 4338 } 4339 4340 if (!MemOps.empty()) 4341 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4342 4343 return Chain; 4344 } 4345 4346 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4347 /// adjusted to accommodate the arguments for the tailcall. 4348 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4349 unsigned ParamSize) { 4350 4351 if (!isTailCall) return 0; 4352 4353 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4354 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4355 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4356 // Remember only if the new adjustment is bigger. 4357 if (SPDiff < FI->getTailCallSPDelta()) 4358 FI->setTailCallSPDelta(SPDiff); 4359 4360 return SPDiff; 4361 } 4362 4363 static bool isFunctionGlobalAddress(SDValue Callee); 4364 4365 static bool 4366 callsShareTOCBase(const Function *Caller, SDValue Callee, 4367 const TargetMachine &TM) { 4368 // If !G, Callee can be an external symbol. 4369 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4370 if (!G) 4371 return false; 4372 4373 // The medium and large code models are expected to provide a sufficiently 4374 // large TOC to provide all data addressing needs of a module with a 4375 // single TOC. Since each module will be addressed with a single TOC then we 4376 // only need to check that caller and callee don't cross dso boundaries. 4377 if (CodeModel::Medium == TM.getCodeModel() || 4378 CodeModel::Large == TM.getCodeModel()) 4379 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4380 4381 // Otherwise we need to ensure callee and caller are in the same section, 4382 // since the linker may allocate multiple TOCs, and we don't know which 4383 // sections will belong to the same TOC base. 4384 4385 const GlobalValue *GV = G->getGlobal(); 4386 if (!GV->isStrongDefinitionForLinker()) 4387 return false; 4388 4389 // Any explicitly-specified sections and section prefixes must also match. 4390 // Also, if we're using -ffunction-sections, then each function is always in 4391 // a different section (the same is true for COMDAT functions). 4392 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4393 GV->getSection() != Caller->getSection()) 4394 return false; 4395 if (const auto *F = dyn_cast<Function>(GV)) { 4396 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4397 return false; 4398 } 4399 4400 // If the callee might be interposed, then we can't assume the ultimate call 4401 // target will be in the same section. Even in cases where we can assume that 4402 // interposition won't happen, in any case where the linker might insert a 4403 // stub to allow for interposition, we must generate code as though 4404 // interposition might occur. To understand why this matters, consider a 4405 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4406 // in the same section, but a is in a different module (i.e. has a different 4407 // TOC base pointer). If the linker allows for interposition between b and c, 4408 // then it will generate a stub for the call edge between b and c which will 4409 // save the TOC pointer into the designated stack slot allocated by b. If we 4410 // return true here, and therefore allow a tail call between b and c, that 4411 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4412 // pointer into the stack slot allocated by a (where the a -> b stub saved 4413 // a's TOC base pointer). If we're not considering a tail call, but rather, 4414 // whether a nop is needed after the call instruction in b, because the linker 4415 // will insert a stub, it might complain about a missing nop if we omit it 4416 // (although many don't complain in this case). 4417 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4418 return false; 4419 4420 return true; 4421 } 4422 4423 static bool 4424 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4425 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4426 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4427 4428 const unsigned PtrByteSize = 8; 4429 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4430 4431 static const MCPhysReg GPR[] = { 4432 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4433 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4434 }; 4435 static const MCPhysReg VR[] = { 4436 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4437 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4438 }; 4439 4440 const unsigned NumGPRs = array_lengthof(GPR); 4441 const unsigned NumFPRs = 13; 4442 const unsigned NumVRs = array_lengthof(VR); 4443 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4444 4445 unsigned NumBytes = LinkageSize; 4446 unsigned AvailableFPRs = NumFPRs; 4447 unsigned AvailableVRs = NumVRs; 4448 4449 for (const ISD::OutputArg& Param : Outs) { 4450 if (Param.Flags.isNest()) continue; 4451 4452 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4453 PtrByteSize, LinkageSize, ParamAreaSize, 4454 NumBytes, AvailableFPRs, AvailableVRs, 4455 Subtarget.hasQPX())) 4456 return true; 4457 } 4458 return false; 4459 } 4460 4461 static bool 4462 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4463 if (CS.arg_size() != CallerFn->arg_size()) 4464 return false; 4465 4466 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4467 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4468 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4469 4470 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4471 const Value* CalleeArg = *CalleeArgIter; 4472 const Value* CallerArg = &(*CallerArgIter); 4473 if (CalleeArg == CallerArg) 4474 continue; 4475 4476 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4477 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4478 // } 4479 // 1st argument of callee is undef and has the same type as caller. 4480 if (CalleeArg->getType() == CallerArg->getType() && 4481 isa<UndefValue>(CalleeArg)) 4482 continue; 4483 4484 return false; 4485 } 4486 4487 return true; 4488 } 4489 4490 // Returns true if TCO is possible between the callers and callees 4491 // calling conventions. 4492 static bool 4493 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4494 CallingConv::ID CalleeCC) { 4495 // Tail calls are possible with fastcc and ccc. 4496 auto isTailCallableCC = [] (CallingConv::ID CC){ 4497 return CC == CallingConv::C || CC == CallingConv::Fast; 4498 }; 4499 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4500 return false; 4501 4502 // We can safely tail call both fastcc and ccc callees from a c calling 4503 // convention caller. If the caller is fastcc, we may have less stack space 4504 // than a non-fastcc caller with the same signature so disable tail-calls in 4505 // that case. 4506 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4507 } 4508 4509 bool 4510 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4511 SDValue Callee, 4512 CallingConv::ID CalleeCC, 4513 ImmutableCallSite CS, 4514 bool isVarArg, 4515 const SmallVectorImpl<ISD::OutputArg> &Outs, 4516 const SmallVectorImpl<ISD::InputArg> &Ins, 4517 SelectionDAG& DAG) const { 4518 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4519 4520 if (DisableSCO && !TailCallOpt) return false; 4521 4522 // Variadic argument functions are not supported. 4523 if (isVarArg) return false; 4524 4525 auto &Caller = DAG.getMachineFunction().getFunction(); 4526 // Check that the calling conventions are compatible for tco. 4527 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4528 return false; 4529 4530 // Caller contains any byval parameter is not supported. 4531 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4532 return false; 4533 4534 // Callee contains any byval parameter is not supported, too. 4535 // Note: This is a quick work around, because in some cases, e.g. 4536 // caller's stack size > callee's stack size, we are still able to apply 4537 // sibling call optimization. For example, gcc is able to do SCO for caller1 4538 // in the following example, but not for caller2. 4539 // struct test { 4540 // long int a; 4541 // char ary[56]; 4542 // } gTest; 4543 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4544 // b->a = v.a; 4545 // return 0; 4546 // } 4547 // void caller1(struct test a, struct test c, struct test *b) { 4548 // callee(gTest, b); } 4549 // void caller2(struct test *b) { callee(gTest, b); } 4550 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4551 return false; 4552 4553 // If callee and caller use different calling conventions, we cannot pass 4554 // parameters on stack since offsets for the parameter area may be different. 4555 if (Caller.getCallingConv() != CalleeCC && 4556 needStackSlotPassParameters(Subtarget, Outs)) 4557 return false; 4558 4559 // No TCO/SCO on indirect call because Caller have to restore its TOC 4560 if (!isFunctionGlobalAddress(Callee) && 4561 !isa<ExternalSymbolSDNode>(Callee)) 4562 return false; 4563 4564 // If the caller and callee potentially have different TOC bases then we 4565 // cannot tail call since we need to restore the TOC pointer after the call. 4566 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4567 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4568 return false; 4569 4570 // TCO allows altering callee ABI, so we don't have to check further. 4571 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4572 return true; 4573 4574 if (DisableSCO) return false; 4575 4576 // If callee use the same argument list that caller is using, then we can 4577 // apply SCO on this case. If it is not, then we need to check if callee needs 4578 // stack for passing arguments. 4579 if (!hasSameArgumentList(&Caller, CS) && 4580 needStackSlotPassParameters(Subtarget, Outs)) { 4581 return false; 4582 } 4583 4584 return true; 4585 } 4586 4587 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4588 /// for tail call optimization. Targets which want to do tail call 4589 /// optimization should implement this function. 4590 bool 4591 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4592 CallingConv::ID CalleeCC, 4593 bool isVarArg, 4594 const SmallVectorImpl<ISD::InputArg> &Ins, 4595 SelectionDAG& DAG) const { 4596 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4597 return false; 4598 4599 // Variable argument functions are not supported. 4600 if (isVarArg) 4601 return false; 4602 4603 MachineFunction &MF = DAG.getMachineFunction(); 4604 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4605 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4606 // Functions containing by val parameters are not supported. 4607 for (unsigned i = 0; i != Ins.size(); i++) { 4608 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4609 if (Flags.isByVal()) return false; 4610 } 4611 4612 // Non-PIC/GOT tail calls are supported. 4613 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4614 return true; 4615 4616 // At the moment we can only do local tail calls (in same module, hidden 4617 // or protected) if we are generating PIC. 4618 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4619 return G->getGlobal()->hasHiddenVisibility() 4620 || G->getGlobal()->hasProtectedVisibility(); 4621 } 4622 4623 return false; 4624 } 4625 4626 /// isCallCompatibleAddress - Return the immediate to use if the specified 4627 /// 32-bit value is representable in the immediate field of a BxA instruction. 4628 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4629 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4630 if (!C) return nullptr; 4631 4632 int Addr = C->getZExtValue(); 4633 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4634 SignExtend32<26>(Addr) != Addr) 4635 return nullptr; // Top 6 bits have to be sext of immediate. 4636 4637 return DAG 4638 .getConstant( 4639 (int)C->getZExtValue() >> 2, SDLoc(Op), 4640 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4641 .getNode(); 4642 } 4643 4644 namespace { 4645 4646 struct TailCallArgumentInfo { 4647 SDValue Arg; 4648 SDValue FrameIdxOp; 4649 int FrameIdx = 0; 4650 4651 TailCallArgumentInfo() = default; 4652 }; 4653 4654 } // end anonymous namespace 4655 4656 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4657 static void StoreTailCallArgumentsToStackSlot( 4658 SelectionDAG &DAG, SDValue Chain, 4659 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4660 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4661 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4662 SDValue Arg = TailCallArgs[i].Arg; 4663 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4664 int FI = TailCallArgs[i].FrameIdx; 4665 // Store relative to framepointer. 4666 MemOpChains.push_back(DAG.getStore( 4667 Chain, dl, Arg, FIN, 4668 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4669 } 4670 } 4671 4672 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4673 /// the appropriate stack slot for the tail call optimized function call. 4674 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4675 SDValue OldRetAddr, SDValue OldFP, 4676 int SPDiff, const SDLoc &dl) { 4677 if (SPDiff) { 4678 // Calculate the new stack slot for the return address. 4679 MachineFunction &MF = DAG.getMachineFunction(); 4680 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4681 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4682 bool isPPC64 = Subtarget.isPPC64(); 4683 int SlotSize = isPPC64 ? 8 : 4; 4684 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4685 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4686 NewRetAddrLoc, true); 4687 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4688 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4689 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4690 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4691 4692 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4693 // slot as the FP is never overwritten. 4694 if (Subtarget.isDarwinABI()) { 4695 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4696 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4697 true); 4698 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4699 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4700 MachinePointerInfo::getFixedStack( 4701 DAG.getMachineFunction(), NewFPIdx)); 4702 } 4703 } 4704 return Chain; 4705 } 4706 4707 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4708 /// the position of the argument. 4709 static void 4710 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4711 SDValue Arg, int SPDiff, unsigned ArgOffset, 4712 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4713 int Offset = ArgOffset + SPDiff; 4714 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4715 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4716 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4717 SDValue FIN = DAG.getFrameIndex(FI, VT); 4718 TailCallArgumentInfo Info; 4719 Info.Arg = Arg; 4720 Info.FrameIdxOp = FIN; 4721 Info.FrameIdx = FI; 4722 TailCallArguments.push_back(Info); 4723 } 4724 4725 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4726 /// stack slot. Returns the chain as result and the loaded frame pointers in 4727 /// LROpOut/FPOpout. Used when tail calling. 4728 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4729 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4730 SDValue &FPOpOut, const SDLoc &dl) const { 4731 if (SPDiff) { 4732 // Load the LR and FP stack slot for later adjusting. 4733 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4734 LROpOut = getReturnAddrFrameIndex(DAG); 4735 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4736 Chain = SDValue(LROpOut.getNode(), 1); 4737 4738 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4739 // slot as the FP is never overwritten. 4740 if (Subtarget.isDarwinABI()) { 4741 FPOpOut = getFramePointerFrameIndex(DAG); 4742 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4743 Chain = SDValue(FPOpOut.getNode(), 1); 4744 } 4745 } 4746 return Chain; 4747 } 4748 4749 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4750 /// by "Src" to address "Dst" of size "Size". Alignment information is 4751 /// specified by the specific parameter attribute. The copy will be passed as 4752 /// a byval function parameter. 4753 /// Sometimes what we are copying is the end of a larger object, the part that 4754 /// does not fit in registers. 4755 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4756 SDValue Chain, ISD::ArgFlagsTy Flags, 4757 SelectionDAG &DAG, const SDLoc &dl) { 4758 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4759 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4760 false, false, false, MachinePointerInfo(), 4761 MachinePointerInfo()); 4762 } 4763 4764 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4765 /// tail calls. 4766 static void LowerMemOpCallTo( 4767 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4768 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4769 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4770 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4771 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4772 if (!isTailCall) { 4773 if (isVector) { 4774 SDValue StackPtr; 4775 if (isPPC64) 4776 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4777 else 4778 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4779 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4780 DAG.getConstant(ArgOffset, dl, PtrVT)); 4781 } 4782 MemOpChains.push_back( 4783 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4784 // Calculate and remember argument location. 4785 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4786 TailCallArguments); 4787 } 4788 4789 static void 4790 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4791 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4792 SDValue FPOp, 4793 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4794 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4795 // might overwrite each other in case of tail call optimization. 4796 SmallVector<SDValue, 8> MemOpChains2; 4797 // Do not flag preceding copytoreg stuff together with the following stuff. 4798 InFlag = SDValue(); 4799 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4800 MemOpChains2, dl); 4801 if (!MemOpChains2.empty()) 4802 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4803 4804 // Store the return address to the appropriate stack slot. 4805 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4806 4807 // Emit callseq_end just before tailcall node. 4808 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4809 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4810 InFlag = Chain.getValue(1); 4811 } 4812 4813 // Is this global address that of a function that can be called by name? (as 4814 // opposed to something that must hold a descriptor for an indirect call). 4815 static bool isFunctionGlobalAddress(SDValue Callee) { 4816 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4817 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4818 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4819 return false; 4820 4821 return G->getGlobal()->getValueType()->isFunctionTy(); 4822 } 4823 4824 return false; 4825 } 4826 4827 static unsigned 4828 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4829 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4830 bool isPatchPoint, bool hasNest, 4831 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4832 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4833 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4834 bool isPPC64 = Subtarget.isPPC64(); 4835 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4836 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4837 4838 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4839 NodeTys.push_back(MVT::Other); // Returns a chain 4840 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4841 4842 unsigned CallOpc = PPCISD::CALL; 4843 4844 bool needIndirectCall = true; 4845 if (!isSVR4ABI || !isPPC64) 4846 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4847 // If this is an absolute destination address, use the munged value. 4848 Callee = SDValue(Dest, 0); 4849 needIndirectCall = false; 4850 } 4851 4852 // PC-relative references to external symbols should go through $stub, unless 4853 // we're building with the leopard linker or later, which automatically 4854 // synthesizes these stubs. 4855 const TargetMachine &TM = DAG.getTarget(); 4856 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4857 const GlobalValue *GV = nullptr; 4858 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4859 GV = G->getGlobal(); 4860 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4861 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4862 4863 if (isFunctionGlobalAddress(Callee)) { 4864 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4865 // A call to a TLS address is actually an indirect call to a 4866 // thread-specific pointer. 4867 unsigned OpFlags = 0; 4868 if (UsePlt) 4869 OpFlags = PPCII::MO_PLT; 4870 4871 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4872 // every direct call is) turn it into a TargetGlobalAddress / 4873 // TargetExternalSymbol node so that legalize doesn't hack it. 4874 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4875 Callee.getValueType(), 0, OpFlags); 4876 needIndirectCall = false; 4877 } 4878 4879 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4880 unsigned char OpFlags = 0; 4881 4882 if (UsePlt) 4883 OpFlags = PPCII::MO_PLT; 4884 4885 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4886 OpFlags); 4887 needIndirectCall = false; 4888 } 4889 4890 if (isPatchPoint) { 4891 // We'll form an invalid direct call when lowering a patchpoint; the full 4892 // sequence for an indirect call is complicated, and many of the 4893 // instructions introduced might have side effects (and, thus, can't be 4894 // removed later). The call itself will be removed as soon as the 4895 // argument/return lowering is complete, so the fact that it has the wrong 4896 // kind of operands should not really matter. 4897 needIndirectCall = false; 4898 } 4899 4900 if (needIndirectCall) { 4901 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4902 // to do the call, we can't use PPCISD::CALL. 4903 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4904 4905 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4906 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4907 // entry point, but to the function descriptor (the function entry point 4908 // address is part of the function descriptor though). 4909 // The function descriptor is a three doubleword structure with the 4910 // following fields: function entry point, TOC base address and 4911 // environment pointer. 4912 // Thus for a call through a function pointer, the following actions need 4913 // to be performed: 4914 // 1. Save the TOC of the caller in the TOC save area of its stack 4915 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4916 // 2. Load the address of the function entry point from the function 4917 // descriptor. 4918 // 3. Load the TOC of the callee from the function descriptor into r2. 4919 // 4. Load the environment pointer from the function descriptor into 4920 // r11. 4921 // 5. Branch to the function entry point address. 4922 // 6. On return of the callee, the TOC of the caller needs to be 4923 // restored (this is done in FinishCall()). 4924 // 4925 // The loads are scheduled at the beginning of the call sequence, and the 4926 // register copies are flagged together to ensure that no other 4927 // operations can be scheduled in between. E.g. without flagging the 4928 // copies together, a TOC access in the caller could be scheduled between 4929 // the assignment of the callee TOC and the branch to the callee, which 4930 // results in the TOC access going through the TOC of the callee instead 4931 // of going through the TOC of the caller, which leads to incorrect code. 4932 4933 // Load the address of the function entry point from the function 4934 // descriptor. 4935 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4936 if (LDChain.getValueType() == MVT::Glue) 4937 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4938 4939 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4940 ? (MachineMemOperand::MODereferenceable | 4941 MachineMemOperand::MOInvariant) 4942 : MachineMemOperand::MONone; 4943 4944 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4945 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4946 /* Alignment = */ 8, MMOFlags); 4947 4948 // Load environment pointer into r11. 4949 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4950 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4951 SDValue LoadEnvPtr = 4952 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4953 /* Alignment = */ 8, MMOFlags); 4954 4955 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4956 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4957 SDValue TOCPtr = 4958 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4959 /* Alignment = */ 8, MMOFlags); 4960 4961 setUsesTOCBasePtr(DAG); 4962 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4963 InFlag); 4964 Chain = TOCVal.getValue(0); 4965 InFlag = TOCVal.getValue(1); 4966 4967 // If the function call has an explicit 'nest' parameter, it takes the 4968 // place of the environment pointer. 4969 if (!hasNest) { 4970 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4971 InFlag); 4972 4973 Chain = EnvVal.getValue(0); 4974 InFlag = EnvVal.getValue(1); 4975 } 4976 4977 MTCTROps[0] = Chain; 4978 MTCTROps[1] = LoadFuncPtr; 4979 MTCTROps[2] = InFlag; 4980 } 4981 4982 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4983 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4984 InFlag = Chain.getValue(1); 4985 4986 NodeTys.clear(); 4987 NodeTys.push_back(MVT::Other); 4988 NodeTys.push_back(MVT::Glue); 4989 Ops.push_back(Chain); 4990 CallOpc = PPCISD::BCTRL; 4991 Callee.setNode(nullptr); 4992 // Add use of X11 (holding environment pointer) 4993 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4994 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4995 // Add CTR register as callee so a bctr can be emitted later. 4996 if (isTailCall) 4997 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4998 } 4999 5000 // If this is a direct call, pass the chain and the callee. 5001 if (Callee.getNode()) { 5002 Ops.push_back(Chain); 5003 Ops.push_back(Callee); 5004 } 5005 // If this is a tail call add stack pointer delta. 5006 if (isTailCall) 5007 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5008 5009 // Add argument registers to the end of the list so that they are known live 5010 // into the call. 5011 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5012 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5013 RegsToPass[i].second.getValueType())); 5014 5015 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 5016 // into the call. 5017 // We do need to reserve X2 to appease the verifier for the PATCHPOINT. 5018 if (isSVR4ABI && isPPC64) { 5019 setUsesTOCBasePtr(DAG); 5020 5021 // We cannot add X2 as an operand here for PATCHPOINT, because there is no 5022 // way to mark dependencies as implicit here. We will add the X2 dependency 5023 // in EmitInstrWithCustomInserter. 5024 if (!isPatchPoint) 5025 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 5026 } 5027 5028 return CallOpc; 5029 } 5030 5031 SDValue PPCTargetLowering::LowerCallResult( 5032 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5033 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5034 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5035 SmallVector<CCValAssign, 16> RVLocs; 5036 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5037 *DAG.getContext()); 5038 5039 CCRetInfo.AnalyzeCallResult( 5040 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5041 ? RetCC_PPC_Cold 5042 : RetCC_PPC); 5043 5044 // Copy all of the result registers out of their specified physreg. 5045 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5046 CCValAssign &VA = RVLocs[i]; 5047 assert(VA.isRegLoc() && "Can only return in registers!"); 5048 5049 SDValue Val = DAG.getCopyFromReg(Chain, dl, 5050 VA.getLocReg(), VA.getLocVT(), InFlag); 5051 Chain = Val.getValue(1); 5052 InFlag = Val.getValue(2); 5053 5054 switch (VA.getLocInfo()) { 5055 default: llvm_unreachable("Unknown loc info!"); 5056 case CCValAssign::Full: break; 5057 case CCValAssign::AExt: 5058 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5059 break; 5060 case CCValAssign::ZExt: 5061 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5062 DAG.getValueType(VA.getValVT())); 5063 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5064 break; 5065 case CCValAssign::SExt: 5066 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5067 DAG.getValueType(VA.getValVT())); 5068 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5069 break; 5070 } 5071 5072 InVals.push_back(Val); 5073 } 5074 5075 return Chain; 5076 } 5077 5078 SDValue PPCTargetLowering::FinishCall( 5079 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5080 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5081 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5082 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5083 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5084 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5085 std::vector<EVT> NodeTys; 5086 SmallVector<SDValue, 8> Ops; 5087 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5088 SPDiff, isTailCall, isPatchPoint, hasNest, 5089 RegsToPass, Ops, NodeTys, CS, Subtarget); 5090 5091 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5092 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5093 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5094 5095 // When performing tail call optimization the callee pops its arguments off 5096 // the stack. Account for this here so these bytes can be pushed back on in 5097 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5098 int BytesCalleePops = 5099 (CallConv == CallingConv::Fast && 5100 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5101 5102 // Add a register mask operand representing the call-preserved registers. 5103 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5104 const uint32_t *Mask = 5105 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5106 assert(Mask && "Missing call preserved mask for calling convention"); 5107 Ops.push_back(DAG.getRegisterMask(Mask)); 5108 5109 if (InFlag.getNode()) 5110 Ops.push_back(InFlag); 5111 5112 // Emit tail call. 5113 if (isTailCall) { 5114 assert(((Callee.getOpcode() == ISD::Register && 5115 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5116 Callee.getOpcode() == ISD::TargetExternalSymbol || 5117 Callee.getOpcode() == ISD::TargetGlobalAddress || 5118 isa<ConstantSDNode>(Callee)) && 5119 "Expecting an global address, external symbol, absolute value or register"); 5120 5121 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5122 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5123 } 5124 5125 // Add a NOP immediately after the branch instruction when using the 64-bit 5126 // SVR4 ABI. At link time, if caller and callee are in a different module and 5127 // thus have a different TOC, the call will be replaced with a call to a stub 5128 // function which saves the current TOC, loads the TOC of the callee and 5129 // branches to the callee. The NOP will be replaced with a load instruction 5130 // which restores the TOC of the caller from the TOC save slot of the current 5131 // stack frame. If caller and callee belong to the same module (and have the 5132 // same TOC), the NOP will remain unchanged. 5133 5134 MachineFunction &MF = DAG.getMachineFunction(); 5135 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5136 !isPatchPoint) { 5137 if (CallOpc == PPCISD::BCTRL) { 5138 // This is a call through a function pointer. 5139 // Restore the caller TOC from the save area into R2. 5140 // See PrepareCall() for more information about calls through function 5141 // pointers in the 64-bit SVR4 ABI. 5142 // We are using a target-specific load with r2 hard coded, because the 5143 // result of a target-independent load would never go directly into r2, 5144 // since r2 is a reserved register (which prevents the register allocator 5145 // from allocating it), resulting in an additional register being 5146 // allocated and an unnecessary move instruction being generated. 5147 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5148 5149 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5150 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5151 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5152 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5153 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5154 5155 // The address needs to go after the chain input but before the flag (or 5156 // any other variadic arguments). 5157 Ops.insert(std::next(Ops.begin()), AddTOC); 5158 } else if (CallOpc == PPCISD::CALL && 5159 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5160 // Otherwise insert NOP for non-local calls. 5161 CallOpc = PPCISD::CALL_NOP; 5162 } 5163 } 5164 5165 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5166 InFlag = Chain.getValue(1); 5167 5168 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5169 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5170 InFlag, dl); 5171 if (!Ins.empty()) 5172 InFlag = Chain.getValue(1); 5173 5174 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5175 Ins, dl, DAG, InVals); 5176 } 5177 5178 SDValue 5179 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5180 SmallVectorImpl<SDValue> &InVals) const { 5181 SelectionDAG &DAG = CLI.DAG; 5182 SDLoc &dl = CLI.DL; 5183 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5184 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5185 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5186 SDValue Chain = CLI.Chain; 5187 SDValue Callee = CLI.Callee; 5188 bool &isTailCall = CLI.IsTailCall; 5189 CallingConv::ID CallConv = CLI.CallConv; 5190 bool isVarArg = CLI.IsVarArg; 5191 bool isPatchPoint = CLI.IsPatchPoint; 5192 ImmutableCallSite CS = CLI.CS; 5193 5194 if (isTailCall) { 5195 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5196 isTailCall = false; 5197 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5198 isTailCall = 5199 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5200 isVarArg, Outs, Ins, DAG); 5201 else 5202 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5203 Ins, DAG); 5204 if (isTailCall) { 5205 ++NumTailCalls; 5206 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5207 ++NumSiblingCalls; 5208 5209 assert(isa<GlobalAddressSDNode>(Callee) && 5210 "Callee should be an llvm::Function object."); 5211 LLVM_DEBUG( 5212 const GlobalValue *GV = 5213 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5214 const unsigned Width = 5215 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5216 dbgs() << "TCO caller: " 5217 << left_justify(DAG.getMachineFunction().getName(), Width) 5218 << ", callee linkage: " << GV->getVisibility() << ", " 5219 << GV->getLinkage() << "\n"); 5220 } 5221 } 5222 5223 if (!isTailCall && CS && CS.isMustTailCall()) 5224 report_fatal_error("failed to perform tail call elimination on a call " 5225 "site marked musttail"); 5226 5227 // When long calls (i.e. indirect calls) are always used, calls are always 5228 // made via function pointer. If we have a function name, first translate it 5229 // into a pointer. 5230 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5231 !isTailCall) 5232 Callee = LowerGlobalAddress(Callee, DAG); 5233 5234 if (Subtarget.isSVR4ABI()) { 5235 if (Subtarget.isPPC64()) 5236 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5237 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5238 dl, DAG, InVals, CS); 5239 else 5240 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5241 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5242 dl, DAG, InVals, CS); 5243 } 5244 5245 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5246 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5247 dl, DAG, InVals, CS); 5248 } 5249 5250 SDValue PPCTargetLowering::LowerCall_32SVR4( 5251 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5252 bool isTailCall, bool isPatchPoint, 5253 const SmallVectorImpl<ISD::OutputArg> &Outs, 5254 const SmallVectorImpl<SDValue> &OutVals, 5255 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5256 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5257 ImmutableCallSite CS) const { 5258 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5259 // of the 32-bit SVR4 ABI stack frame layout. 5260 5261 assert((CallConv == CallingConv::C || 5262 CallConv == CallingConv::Cold || 5263 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5264 5265 unsigned PtrByteSize = 4; 5266 5267 MachineFunction &MF = DAG.getMachineFunction(); 5268 5269 // Mark this function as potentially containing a function that contains a 5270 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5271 // and restoring the callers stack pointer in this functions epilog. This is 5272 // done because by tail calling the called function might overwrite the value 5273 // in this function's (MF) stack pointer stack slot 0(SP). 5274 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5275 CallConv == CallingConv::Fast) 5276 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5277 5278 // Count how many bytes are to be pushed on the stack, including the linkage 5279 // area, parameter list area and the part of the local variable space which 5280 // contains copies of aggregates which are passed by value. 5281 5282 // Assign locations to all of the outgoing arguments. 5283 SmallVector<CCValAssign, 16> ArgLocs; 5284 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5285 5286 // Reserve space for the linkage area on the stack. 5287 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5288 PtrByteSize); 5289 if (useSoftFloat()) 5290 CCInfo.PreAnalyzeCallOperands(Outs); 5291 5292 if (isVarArg) { 5293 // Handle fixed and variable vector arguments differently. 5294 // Fixed vector arguments go into registers as long as registers are 5295 // available. Variable vector arguments always go into memory. 5296 unsigned NumArgs = Outs.size(); 5297 5298 for (unsigned i = 0; i != NumArgs; ++i) { 5299 MVT ArgVT = Outs[i].VT; 5300 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5301 bool Result; 5302 5303 if (Outs[i].IsFixed) { 5304 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5305 CCInfo); 5306 } else { 5307 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5308 ArgFlags, CCInfo); 5309 } 5310 5311 if (Result) { 5312 #ifndef NDEBUG 5313 errs() << "Call operand #" << i << " has unhandled type " 5314 << EVT(ArgVT).getEVTString() << "\n"; 5315 #endif 5316 llvm_unreachable(nullptr); 5317 } 5318 } 5319 } else { 5320 // All arguments are treated the same. 5321 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5322 } 5323 CCInfo.clearWasPPCF128(); 5324 5325 // Assign locations to all of the outgoing aggregate by value arguments. 5326 SmallVector<CCValAssign, 16> ByValArgLocs; 5327 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5328 5329 // Reserve stack space for the allocations in CCInfo. 5330 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5331 5332 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5333 5334 // Size of the linkage area, parameter list area and the part of the local 5335 // space variable where copies of aggregates which are passed by value are 5336 // stored. 5337 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5338 5339 // Calculate by how many bytes the stack has to be adjusted in case of tail 5340 // call optimization. 5341 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5342 5343 // Adjust the stack pointer for the new arguments... 5344 // These operations are automatically eliminated by the prolog/epilog pass 5345 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5346 SDValue CallSeqStart = Chain; 5347 5348 // Load the return address and frame pointer so it can be moved somewhere else 5349 // later. 5350 SDValue LROp, FPOp; 5351 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5352 5353 // Set up a copy of the stack pointer for use loading and storing any 5354 // arguments that may not fit in the registers available for argument 5355 // passing. 5356 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5357 5358 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5359 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5360 SmallVector<SDValue, 8> MemOpChains; 5361 5362 bool seenFloatArg = false; 5363 // Walk the register/memloc assignments, inserting copies/loads. 5364 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5365 i != e; 5366 ++i) { 5367 CCValAssign &VA = ArgLocs[i]; 5368 SDValue Arg = OutVals[i]; 5369 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5370 5371 if (Flags.isByVal()) { 5372 // Argument is an aggregate which is passed by value, thus we need to 5373 // create a copy of it in the local variable space of the current stack 5374 // frame (which is the stack frame of the caller) and pass the address of 5375 // this copy to the callee. 5376 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5377 CCValAssign &ByValVA = ByValArgLocs[j++]; 5378 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5379 5380 // Memory reserved in the local variable space of the callers stack frame. 5381 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5382 5383 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5384 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5385 StackPtr, PtrOff); 5386 5387 // Create a copy of the argument in the local area of the current 5388 // stack frame. 5389 SDValue MemcpyCall = 5390 CreateCopyOfByValArgument(Arg, PtrOff, 5391 CallSeqStart.getNode()->getOperand(0), 5392 Flags, DAG, dl); 5393 5394 // This must go outside the CALLSEQ_START..END. 5395 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5396 SDLoc(MemcpyCall)); 5397 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5398 NewCallSeqStart.getNode()); 5399 Chain = CallSeqStart = NewCallSeqStart; 5400 5401 // Pass the address of the aggregate copy on the stack either in a 5402 // physical register or in the parameter list area of the current stack 5403 // frame to the callee. 5404 Arg = PtrOff; 5405 } 5406 5407 // When useCRBits() is true, there can be i1 arguments. 5408 // It is because getRegisterType(MVT::i1) => MVT::i1, 5409 // and for other integer types getRegisterType() => MVT::i32. 5410 // Extend i1 and ensure callee will get i32. 5411 if (Arg.getValueType() == MVT::i1) 5412 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5413 dl, MVT::i32, Arg); 5414 5415 if (VA.isRegLoc()) { 5416 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5417 // Put argument in a physical register. 5418 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5419 } else { 5420 // Put argument in the parameter list area of the current stack frame. 5421 assert(VA.isMemLoc()); 5422 unsigned LocMemOffset = VA.getLocMemOffset(); 5423 5424 if (!isTailCall) { 5425 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5426 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5427 StackPtr, PtrOff); 5428 5429 MemOpChains.push_back( 5430 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5431 } else { 5432 // Calculate and remember argument location. 5433 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5434 TailCallArguments); 5435 } 5436 } 5437 } 5438 5439 if (!MemOpChains.empty()) 5440 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5441 5442 // Build a sequence of copy-to-reg nodes chained together with token chain 5443 // and flag operands which copy the outgoing args into the appropriate regs. 5444 SDValue InFlag; 5445 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5446 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5447 RegsToPass[i].second, InFlag); 5448 InFlag = Chain.getValue(1); 5449 } 5450 5451 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5452 // registers. 5453 if (isVarArg) { 5454 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5455 SDValue Ops[] = { Chain, InFlag }; 5456 5457 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5458 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5459 5460 InFlag = Chain.getValue(1); 5461 } 5462 5463 if (isTailCall) 5464 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5465 TailCallArguments); 5466 5467 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5468 /* unused except on PPC64 ELFv1 */ false, DAG, 5469 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5470 NumBytes, Ins, InVals, CS); 5471 } 5472 5473 // Copy an argument into memory, being careful to do this outside the 5474 // call sequence for the call to which the argument belongs. 5475 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5476 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5477 SelectionDAG &DAG, const SDLoc &dl) const { 5478 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5479 CallSeqStart.getNode()->getOperand(0), 5480 Flags, DAG, dl); 5481 // The MEMCPY must go outside the CALLSEQ_START..END. 5482 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5483 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5484 SDLoc(MemcpyCall)); 5485 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5486 NewCallSeqStart.getNode()); 5487 return NewCallSeqStart; 5488 } 5489 5490 SDValue PPCTargetLowering::LowerCall_64SVR4( 5491 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5492 bool isTailCall, bool isPatchPoint, 5493 const SmallVectorImpl<ISD::OutputArg> &Outs, 5494 const SmallVectorImpl<SDValue> &OutVals, 5495 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5496 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5497 ImmutableCallSite CS) const { 5498 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5499 bool isLittleEndian = Subtarget.isLittleEndian(); 5500 unsigned NumOps = Outs.size(); 5501 bool hasNest = false; 5502 bool IsSibCall = false; 5503 5504 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5505 unsigned PtrByteSize = 8; 5506 5507 MachineFunction &MF = DAG.getMachineFunction(); 5508 5509 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5510 IsSibCall = true; 5511 5512 // Mark this function as potentially containing a function that contains a 5513 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5514 // and restoring the callers stack pointer in this functions epilog. This is 5515 // done because by tail calling the called function might overwrite the value 5516 // in this function's (MF) stack pointer stack slot 0(SP). 5517 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5518 CallConv == CallingConv::Fast) 5519 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5520 5521 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5522 "fastcc not supported on varargs functions"); 5523 5524 // Count how many bytes are to be pushed on the stack, including the linkage 5525 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5526 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5527 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5528 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5529 unsigned NumBytes = LinkageSize; 5530 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5531 unsigned &QFPR_idx = FPR_idx; 5532 5533 static const MCPhysReg GPR[] = { 5534 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5535 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5536 }; 5537 static const MCPhysReg VR[] = { 5538 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5539 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5540 }; 5541 5542 const unsigned NumGPRs = array_lengthof(GPR); 5543 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5544 const unsigned NumVRs = array_lengthof(VR); 5545 const unsigned NumQFPRs = NumFPRs; 5546 5547 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5548 // can be passed to the callee in registers. 5549 // For the fast calling convention, there is another check below. 5550 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5551 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5552 if (!HasParameterArea) { 5553 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5554 unsigned AvailableFPRs = NumFPRs; 5555 unsigned AvailableVRs = NumVRs; 5556 unsigned NumBytesTmp = NumBytes; 5557 for (unsigned i = 0; i != NumOps; ++i) { 5558 if (Outs[i].Flags.isNest()) continue; 5559 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5560 PtrByteSize, LinkageSize, ParamAreaSize, 5561 NumBytesTmp, AvailableFPRs, AvailableVRs, 5562 Subtarget.hasQPX())) 5563 HasParameterArea = true; 5564 } 5565 } 5566 5567 // When using the fast calling convention, we don't provide backing for 5568 // arguments that will be in registers. 5569 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5570 5571 // Avoid allocating parameter area for fastcc functions if all the arguments 5572 // can be passed in the registers. 5573 if (CallConv == CallingConv::Fast) 5574 HasParameterArea = false; 5575 5576 // Add up all the space actually used. 5577 for (unsigned i = 0; i != NumOps; ++i) { 5578 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5579 EVT ArgVT = Outs[i].VT; 5580 EVT OrigVT = Outs[i].ArgVT; 5581 5582 if (Flags.isNest()) 5583 continue; 5584 5585 if (CallConv == CallingConv::Fast) { 5586 if (Flags.isByVal()) { 5587 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5588 if (NumGPRsUsed > NumGPRs) 5589 HasParameterArea = true; 5590 } else { 5591 switch (ArgVT.getSimpleVT().SimpleTy) { 5592 default: llvm_unreachable("Unexpected ValueType for argument!"); 5593 case MVT::i1: 5594 case MVT::i32: 5595 case MVT::i64: 5596 if (++NumGPRsUsed <= NumGPRs) 5597 continue; 5598 break; 5599 case MVT::v4i32: 5600 case MVT::v8i16: 5601 case MVT::v16i8: 5602 case MVT::v2f64: 5603 case MVT::v2i64: 5604 case MVT::v1i128: 5605 case MVT::f128: 5606 if (++NumVRsUsed <= NumVRs) 5607 continue; 5608 break; 5609 case MVT::v4f32: 5610 // When using QPX, this is handled like a FP register, otherwise, it 5611 // is an Altivec register. 5612 if (Subtarget.hasQPX()) { 5613 if (++NumFPRsUsed <= NumFPRs) 5614 continue; 5615 } else { 5616 if (++NumVRsUsed <= NumVRs) 5617 continue; 5618 } 5619 break; 5620 case MVT::f32: 5621 case MVT::f64: 5622 case MVT::v4f64: // QPX 5623 case MVT::v4i1: // QPX 5624 if (++NumFPRsUsed <= NumFPRs) 5625 continue; 5626 break; 5627 } 5628 HasParameterArea = true; 5629 } 5630 } 5631 5632 /* Respect alignment of argument on the stack. */ 5633 unsigned Align = 5634 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5635 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5636 5637 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5638 if (Flags.isInConsecutiveRegsLast()) 5639 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5640 } 5641 5642 unsigned NumBytesActuallyUsed = NumBytes; 5643 5644 // In the old ELFv1 ABI, 5645 // the prolog code of the callee may store up to 8 GPR argument registers to 5646 // the stack, allowing va_start to index over them in memory if its varargs. 5647 // Because we cannot tell if this is needed on the caller side, we have to 5648 // conservatively assume that it is needed. As such, make sure we have at 5649 // least enough stack space for the caller to store the 8 GPRs. 5650 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5651 // really requires memory operands, e.g. a vararg function. 5652 if (HasParameterArea) 5653 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5654 else 5655 NumBytes = LinkageSize; 5656 5657 // Tail call needs the stack to be aligned. 5658 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5659 CallConv == CallingConv::Fast) 5660 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5661 5662 int SPDiff = 0; 5663 5664 // Calculate by how many bytes the stack has to be adjusted in case of tail 5665 // call optimization. 5666 if (!IsSibCall) 5667 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5668 5669 // To protect arguments on the stack from being clobbered in a tail call, 5670 // force all the loads to happen before doing any other lowering. 5671 if (isTailCall) 5672 Chain = DAG.getStackArgumentTokenFactor(Chain); 5673 5674 // Adjust the stack pointer for the new arguments... 5675 // These operations are automatically eliminated by the prolog/epilog pass 5676 if (!IsSibCall) 5677 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5678 SDValue CallSeqStart = Chain; 5679 5680 // Load the return address and frame pointer so it can be move somewhere else 5681 // later. 5682 SDValue LROp, FPOp; 5683 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5684 5685 // Set up a copy of the stack pointer for use loading and storing any 5686 // arguments that may not fit in the registers available for argument 5687 // passing. 5688 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5689 5690 // Figure out which arguments are going to go in registers, and which in 5691 // memory. Also, if this is a vararg function, floating point operations 5692 // must be stored to our stack, and loaded into integer regs as well, if 5693 // any integer regs are available for argument passing. 5694 unsigned ArgOffset = LinkageSize; 5695 5696 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5697 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5698 5699 SmallVector<SDValue, 8> MemOpChains; 5700 for (unsigned i = 0; i != NumOps; ++i) { 5701 SDValue Arg = OutVals[i]; 5702 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5703 EVT ArgVT = Outs[i].VT; 5704 EVT OrigVT = Outs[i].ArgVT; 5705 5706 // PtrOff will be used to store the current argument to the stack if a 5707 // register cannot be found for it. 5708 SDValue PtrOff; 5709 5710 // We re-align the argument offset for each argument, except when using the 5711 // fast calling convention, when we need to make sure we do that only when 5712 // we'll actually use a stack slot. 5713 auto ComputePtrOff = [&]() { 5714 /* Respect alignment of argument on the stack. */ 5715 unsigned Align = 5716 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5717 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5718 5719 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5720 5721 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5722 }; 5723 5724 if (CallConv != CallingConv::Fast) { 5725 ComputePtrOff(); 5726 5727 /* Compute GPR index associated with argument offset. */ 5728 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5729 GPR_idx = std::min(GPR_idx, NumGPRs); 5730 } 5731 5732 // Promote integers to 64-bit values. 5733 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5734 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5735 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5736 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5737 } 5738 5739 // FIXME memcpy is used way more than necessary. Correctness first. 5740 // Note: "by value" is code for passing a structure by value, not 5741 // basic types. 5742 if (Flags.isByVal()) { 5743 // Note: Size includes alignment padding, so 5744 // struct x { short a; char b; } 5745 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5746 // These are the proper values we need for right-justifying the 5747 // aggregate in a parameter register. 5748 unsigned Size = Flags.getByValSize(); 5749 5750 // An empty aggregate parameter takes up no storage and no 5751 // registers. 5752 if (Size == 0) 5753 continue; 5754 5755 if (CallConv == CallingConv::Fast) 5756 ComputePtrOff(); 5757 5758 // All aggregates smaller than 8 bytes must be passed right-justified. 5759 if (Size==1 || Size==2 || Size==4) { 5760 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5761 if (GPR_idx != NumGPRs) { 5762 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5763 MachinePointerInfo(), VT); 5764 MemOpChains.push_back(Load.getValue(1)); 5765 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5766 5767 ArgOffset += PtrByteSize; 5768 continue; 5769 } 5770 } 5771 5772 if (GPR_idx == NumGPRs && Size < 8) { 5773 SDValue AddPtr = PtrOff; 5774 if (!isLittleEndian) { 5775 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5776 PtrOff.getValueType()); 5777 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5778 } 5779 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5780 CallSeqStart, 5781 Flags, DAG, dl); 5782 ArgOffset += PtrByteSize; 5783 continue; 5784 } 5785 // Copy entire object into memory. There are cases where gcc-generated 5786 // code assumes it is there, even if it could be put entirely into 5787 // registers. (This is not what the doc says.) 5788 5789 // FIXME: The above statement is likely due to a misunderstanding of the 5790 // documents. All arguments must be copied into the parameter area BY 5791 // THE CALLEE in the event that the callee takes the address of any 5792 // formal argument. That has not yet been implemented. However, it is 5793 // reasonable to use the stack area as a staging area for the register 5794 // load. 5795 5796 // Skip this for small aggregates, as we will use the same slot for a 5797 // right-justified copy, below. 5798 if (Size >= 8) 5799 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5800 CallSeqStart, 5801 Flags, DAG, dl); 5802 5803 // When a register is available, pass a small aggregate right-justified. 5804 if (Size < 8 && GPR_idx != NumGPRs) { 5805 // The easiest way to get this right-justified in a register 5806 // is to copy the structure into the rightmost portion of a 5807 // local variable slot, then load the whole slot into the 5808 // register. 5809 // FIXME: The memcpy seems to produce pretty awful code for 5810 // small aggregates, particularly for packed ones. 5811 // FIXME: It would be preferable to use the slot in the 5812 // parameter save area instead of a new local variable. 5813 SDValue AddPtr = PtrOff; 5814 if (!isLittleEndian) { 5815 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5816 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5817 } 5818 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5819 CallSeqStart, 5820 Flags, DAG, dl); 5821 5822 // Load the slot into the register. 5823 SDValue Load = 5824 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5825 MemOpChains.push_back(Load.getValue(1)); 5826 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5827 5828 // Done with this argument. 5829 ArgOffset += PtrByteSize; 5830 continue; 5831 } 5832 5833 // For aggregates larger than PtrByteSize, copy the pieces of the 5834 // object that fit into registers from the parameter save area. 5835 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5836 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5837 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5838 if (GPR_idx != NumGPRs) { 5839 SDValue Load = 5840 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5841 MemOpChains.push_back(Load.getValue(1)); 5842 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5843 ArgOffset += PtrByteSize; 5844 } else { 5845 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5846 break; 5847 } 5848 } 5849 continue; 5850 } 5851 5852 switch (Arg.getSimpleValueType().SimpleTy) { 5853 default: llvm_unreachable("Unexpected ValueType for argument!"); 5854 case MVT::i1: 5855 case MVT::i32: 5856 case MVT::i64: 5857 if (Flags.isNest()) { 5858 // The 'nest' parameter, if any, is passed in R11. 5859 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5860 hasNest = true; 5861 break; 5862 } 5863 5864 // These can be scalar arguments or elements of an integer array type 5865 // passed directly. Clang may use those instead of "byval" aggregate 5866 // types to avoid forcing arguments to memory unnecessarily. 5867 if (GPR_idx != NumGPRs) { 5868 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5869 } else { 5870 if (CallConv == CallingConv::Fast) 5871 ComputePtrOff(); 5872 5873 assert(HasParameterArea && 5874 "Parameter area must exist to pass an argument in memory."); 5875 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5876 true, isTailCall, false, MemOpChains, 5877 TailCallArguments, dl); 5878 if (CallConv == CallingConv::Fast) 5879 ArgOffset += PtrByteSize; 5880 } 5881 if (CallConv != CallingConv::Fast) 5882 ArgOffset += PtrByteSize; 5883 break; 5884 case MVT::f32: 5885 case MVT::f64: { 5886 // These can be scalar arguments or elements of a float array type 5887 // passed directly. The latter are used to implement ELFv2 homogenous 5888 // float aggregates. 5889 5890 // Named arguments go into FPRs first, and once they overflow, the 5891 // remaining arguments go into GPRs and then the parameter save area. 5892 // Unnamed arguments for vararg functions always go to GPRs and 5893 // then the parameter save area. For now, put all arguments to vararg 5894 // routines always in both locations (FPR *and* GPR or stack slot). 5895 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5896 bool NeededLoad = false; 5897 5898 // First load the argument into the next available FPR. 5899 if (FPR_idx != NumFPRs) 5900 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5901 5902 // Next, load the argument into GPR or stack slot if needed. 5903 if (!NeedGPROrStack) 5904 ; 5905 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5906 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5907 // once we support fp <-> gpr moves. 5908 5909 // In the non-vararg case, this can only ever happen in the 5910 // presence of f32 array types, since otherwise we never run 5911 // out of FPRs before running out of GPRs. 5912 SDValue ArgVal; 5913 5914 // Double values are always passed in a single GPR. 5915 if (Arg.getValueType() != MVT::f32) { 5916 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5917 5918 // Non-array float values are extended and passed in a GPR. 5919 } else if (!Flags.isInConsecutiveRegs()) { 5920 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5921 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5922 5923 // If we have an array of floats, we collect every odd element 5924 // together with its predecessor into one GPR. 5925 } else if (ArgOffset % PtrByteSize != 0) { 5926 SDValue Lo, Hi; 5927 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5928 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5929 if (!isLittleEndian) 5930 std::swap(Lo, Hi); 5931 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5932 5933 // The final element, if even, goes into the first half of a GPR. 5934 } else if (Flags.isInConsecutiveRegsLast()) { 5935 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5936 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5937 if (!isLittleEndian) 5938 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5939 DAG.getConstant(32, dl, MVT::i32)); 5940 5941 // Non-final even elements are skipped; they will be handled 5942 // together the with subsequent argument on the next go-around. 5943 } else 5944 ArgVal = SDValue(); 5945 5946 if (ArgVal.getNode()) 5947 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5948 } else { 5949 if (CallConv == CallingConv::Fast) 5950 ComputePtrOff(); 5951 5952 // Single-precision floating-point values are mapped to the 5953 // second (rightmost) word of the stack doubleword. 5954 if (Arg.getValueType() == MVT::f32 && 5955 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5956 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5957 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5958 } 5959 5960 assert(HasParameterArea && 5961 "Parameter area must exist to pass an argument in memory."); 5962 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5963 true, isTailCall, false, MemOpChains, 5964 TailCallArguments, dl); 5965 5966 NeededLoad = true; 5967 } 5968 // When passing an array of floats, the array occupies consecutive 5969 // space in the argument area; only round up to the next doubleword 5970 // at the end of the array. Otherwise, each float takes 8 bytes. 5971 if (CallConv != CallingConv::Fast || NeededLoad) { 5972 ArgOffset += (Arg.getValueType() == MVT::f32 && 5973 Flags.isInConsecutiveRegs()) ? 4 : 8; 5974 if (Flags.isInConsecutiveRegsLast()) 5975 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5976 } 5977 break; 5978 } 5979 case MVT::v4f32: 5980 case MVT::v4i32: 5981 case MVT::v8i16: 5982 case MVT::v16i8: 5983 case MVT::v2f64: 5984 case MVT::v2i64: 5985 case MVT::v1i128: 5986 case MVT::f128: 5987 if (!Subtarget.hasQPX()) { 5988 // These can be scalar arguments or elements of a vector array type 5989 // passed directly. The latter are used to implement ELFv2 homogenous 5990 // vector aggregates. 5991 5992 // For a varargs call, named arguments go into VRs or on the stack as 5993 // usual; unnamed arguments always go to the stack or the corresponding 5994 // GPRs when within range. For now, we always put the value in both 5995 // locations (or even all three). 5996 if (isVarArg) { 5997 assert(HasParameterArea && 5998 "Parameter area must exist if we have a varargs call."); 5999 // We could elide this store in the case where the object fits 6000 // entirely in R registers. Maybe later. 6001 SDValue Store = 6002 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6003 MemOpChains.push_back(Store); 6004 if (VR_idx != NumVRs) { 6005 SDValue Load = 6006 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6007 MemOpChains.push_back(Load.getValue(1)); 6008 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6009 } 6010 ArgOffset += 16; 6011 for (unsigned i=0; i<16; i+=PtrByteSize) { 6012 if (GPR_idx == NumGPRs) 6013 break; 6014 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6015 DAG.getConstant(i, dl, PtrVT)); 6016 SDValue Load = 6017 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6018 MemOpChains.push_back(Load.getValue(1)); 6019 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6020 } 6021 break; 6022 } 6023 6024 // Non-varargs Altivec params go into VRs or on the stack. 6025 if (VR_idx != NumVRs) { 6026 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6027 } else { 6028 if (CallConv == CallingConv::Fast) 6029 ComputePtrOff(); 6030 6031 assert(HasParameterArea && 6032 "Parameter area must exist to pass an argument in memory."); 6033 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6034 true, isTailCall, true, MemOpChains, 6035 TailCallArguments, dl); 6036 if (CallConv == CallingConv::Fast) 6037 ArgOffset += 16; 6038 } 6039 6040 if (CallConv != CallingConv::Fast) 6041 ArgOffset += 16; 6042 break; 6043 } // not QPX 6044 6045 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6046 "Invalid QPX parameter type"); 6047 6048 LLVM_FALLTHROUGH; 6049 case MVT::v4f64: 6050 case MVT::v4i1: { 6051 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6052 if (isVarArg) { 6053 assert(HasParameterArea && 6054 "Parameter area must exist if we have a varargs call."); 6055 // We could elide this store in the case where the object fits 6056 // entirely in R registers. Maybe later. 6057 SDValue Store = 6058 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6059 MemOpChains.push_back(Store); 6060 if (QFPR_idx != NumQFPRs) { 6061 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6062 PtrOff, MachinePointerInfo()); 6063 MemOpChains.push_back(Load.getValue(1)); 6064 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6065 } 6066 ArgOffset += (IsF32 ? 16 : 32); 6067 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6068 if (GPR_idx == NumGPRs) 6069 break; 6070 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6071 DAG.getConstant(i, dl, PtrVT)); 6072 SDValue Load = 6073 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6074 MemOpChains.push_back(Load.getValue(1)); 6075 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6076 } 6077 break; 6078 } 6079 6080 // Non-varargs QPX params go into registers or on the stack. 6081 if (QFPR_idx != NumQFPRs) { 6082 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6083 } else { 6084 if (CallConv == CallingConv::Fast) 6085 ComputePtrOff(); 6086 6087 assert(HasParameterArea && 6088 "Parameter area must exist to pass an argument in memory."); 6089 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6090 true, isTailCall, true, MemOpChains, 6091 TailCallArguments, dl); 6092 if (CallConv == CallingConv::Fast) 6093 ArgOffset += (IsF32 ? 16 : 32); 6094 } 6095 6096 if (CallConv != CallingConv::Fast) 6097 ArgOffset += (IsF32 ? 16 : 32); 6098 break; 6099 } 6100 } 6101 } 6102 6103 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6104 "mismatch in size of parameter area"); 6105 (void)NumBytesActuallyUsed; 6106 6107 if (!MemOpChains.empty()) 6108 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6109 6110 // Check if this is an indirect call (MTCTR/BCTRL). 6111 // See PrepareCall() for more information about calls through function 6112 // pointers in the 64-bit SVR4 ABI. 6113 if (!isTailCall && !isPatchPoint && 6114 !isFunctionGlobalAddress(Callee) && 6115 !isa<ExternalSymbolSDNode>(Callee)) { 6116 // Load r2 into a virtual register and store it to the TOC save area. 6117 setUsesTOCBasePtr(DAG); 6118 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6119 // TOC save area offset. 6120 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6121 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6122 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6123 Chain = DAG.getStore( 6124 Val.getValue(1), dl, Val, AddPtr, 6125 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6126 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6127 // This does not mean the MTCTR instruction must use R12; it's easier 6128 // to model this as an extra parameter, so do that. 6129 if (isELFv2ABI && !isPatchPoint) 6130 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6131 } 6132 6133 // Build a sequence of copy-to-reg nodes chained together with token chain 6134 // and flag operands which copy the outgoing args into the appropriate regs. 6135 SDValue InFlag; 6136 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6137 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6138 RegsToPass[i].second, InFlag); 6139 InFlag = Chain.getValue(1); 6140 } 6141 6142 if (isTailCall && !IsSibCall) 6143 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6144 TailCallArguments); 6145 6146 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6147 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6148 SPDiff, NumBytes, Ins, InVals, CS); 6149 } 6150 6151 SDValue PPCTargetLowering::LowerCall_Darwin( 6152 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6153 bool isTailCall, bool isPatchPoint, 6154 const SmallVectorImpl<ISD::OutputArg> &Outs, 6155 const SmallVectorImpl<SDValue> &OutVals, 6156 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6157 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6158 ImmutableCallSite CS) const { 6159 unsigned NumOps = Outs.size(); 6160 6161 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6162 bool isPPC64 = PtrVT == MVT::i64; 6163 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6164 6165 MachineFunction &MF = DAG.getMachineFunction(); 6166 6167 // Mark this function as potentially containing a function that contains a 6168 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6169 // and restoring the callers stack pointer in this functions epilog. This is 6170 // done because by tail calling the called function might overwrite the value 6171 // in this function's (MF) stack pointer stack slot 0(SP). 6172 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6173 CallConv == CallingConv::Fast) 6174 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6175 6176 // Count how many bytes are to be pushed on the stack, including the linkage 6177 // area, and parameter passing area. We start with 24/48 bytes, which is 6178 // prereserved space for [SP][CR][LR][3 x unused]. 6179 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6180 unsigned NumBytes = LinkageSize; 6181 6182 // Add up all the space actually used. 6183 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6184 // they all go in registers, but we must reserve stack space for them for 6185 // possible use by the caller. In varargs or 64-bit calls, parameters are 6186 // assigned stack space in order, with padding so Altivec parameters are 6187 // 16-byte aligned. 6188 unsigned nAltivecParamsAtEnd = 0; 6189 for (unsigned i = 0; i != NumOps; ++i) { 6190 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6191 EVT ArgVT = Outs[i].VT; 6192 // Varargs Altivec parameters are padded to a 16 byte boundary. 6193 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6194 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6195 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6196 if (!isVarArg && !isPPC64) { 6197 // Non-varargs Altivec parameters go after all the non-Altivec 6198 // parameters; handle those later so we know how much padding we need. 6199 nAltivecParamsAtEnd++; 6200 continue; 6201 } 6202 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6203 NumBytes = ((NumBytes+15)/16)*16; 6204 } 6205 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6206 } 6207 6208 // Allow for Altivec parameters at the end, if needed. 6209 if (nAltivecParamsAtEnd) { 6210 NumBytes = ((NumBytes+15)/16)*16; 6211 NumBytes += 16*nAltivecParamsAtEnd; 6212 } 6213 6214 // The prolog code of the callee may store up to 8 GPR argument registers to 6215 // the stack, allowing va_start to index over them in memory if its varargs. 6216 // Because we cannot tell if this is needed on the caller side, we have to 6217 // conservatively assume that it is needed. As such, make sure we have at 6218 // least enough stack space for the caller to store the 8 GPRs. 6219 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6220 6221 // Tail call needs the stack to be aligned. 6222 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6223 CallConv == CallingConv::Fast) 6224 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6225 6226 // Calculate by how many bytes the stack has to be adjusted in case of tail 6227 // call optimization. 6228 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6229 6230 // To protect arguments on the stack from being clobbered in a tail call, 6231 // force all the loads to happen before doing any other lowering. 6232 if (isTailCall) 6233 Chain = DAG.getStackArgumentTokenFactor(Chain); 6234 6235 // Adjust the stack pointer for the new arguments... 6236 // These operations are automatically eliminated by the prolog/epilog pass 6237 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6238 SDValue CallSeqStart = Chain; 6239 6240 // Load the return address and frame pointer so it can be move somewhere else 6241 // later. 6242 SDValue LROp, FPOp; 6243 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6244 6245 // Set up a copy of the stack pointer for use loading and storing any 6246 // arguments that may not fit in the registers available for argument 6247 // passing. 6248 SDValue StackPtr; 6249 if (isPPC64) 6250 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6251 else 6252 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6253 6254 // Figure out which arguments are going to go in registers, and which in 6255 // memory. Also, if this is a vararg function, floating point operations 6256 // must be stored to our stack, and loaded into integer regs as well, if 6257 // any integer regs are available for argument passing. 6258 unsigned ArgOffset = LinkageSize; 6259 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6260 6261 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6262 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6263 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6264 }; 6265 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6266 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6267 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6268 }; 6269 static const MCPhysReg VR[] = { 6270 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6271 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6272 }; 6273 const unsigned NumGPRs = array_lengthof(GPR_32); 6274 const unsigned NumFPRs = 13; 6275 const unsigned NumVRs = array_lengthof(VR); 6276 6277 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6278 6279 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6280 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6281 6282 SmallVector<SDValue, 8> MemOpChains; 6283 for (unsigned i = 0; i != NumOps; ++i) { 6284 SDValue Arg = OutVals[i]; 6285 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6286 6287 // PtrOff will be used to store the current argument to the stack if a 6288 // register cannot be found for it. 6289 SDValue PtrOff; 6290 6291 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6292 6293 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6294 6295 // On PPC64, promote integers to 64-bit values. 6296 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6297 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6298 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6299 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6300 } 6301 6302 // FIXME memcpy is used way more than necessary. Correctness first. 6303 // Note: "by value" is code for passing a structure by value, not 6304 // basic types. 6305 if (Flags.isByVal()) { 6306 unsigned Size = Flags.getByValSize(); 6307 // Very small objects are passed right-justified. Everything else is 6308 // passed left-justified. 6309 if (Size==1 || Size==2) { 6310 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6311 if (GPR_idx != NumGPRs) { 6312 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6313 MachinePointerInfo(), VT); 6314 MemOpChains.push_back(Load.getValue(1)); 6315 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6316 6317 ArgOffset += PtrByteSize; 6318 } else { 6319 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6320 PtrOff.getValueType()); 6321 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6322 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6323 CallSeqStart, 6324 Flags, DAG, dl); 6325 ArgOffset += PtrByteSize; 6326 } 6327 continue; 6328 } 6329 // Copy entire object into memory. There are cases where gcc-generated 6330 // code assumes it is there, even if it could be put entirely into 6331 // registers. (This is not what the doc says.) 6332 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6333 CallSeqStart, 6334 Flags, DAG, dl); 6335 6336 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6337 // copy the pieces of the object that fit into registers from the 6338 // parameter save area. 6339 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6340 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6341 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6342 if (GPR_idx != NumGPRs) { 6343 SDValue Load = 6344 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6345 MemOpChains.push_back(Load.getValue(1)); 6346 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6347 ArgOffset += PtrByteSize; 6348 } else { 6349 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6350 break; 6351 } 6352 } 6353 continue; 6354 } 6355 6356 switch (Arg.getSimpleValueType().SimpleTy) { 6357 default: llvm_unreachable("Unexpected ValueType for argument!"); 6358 case MVT::i1: 6359 case MVT::i32: 6360 case MVT::i64: 6361 if (GPR_idx != NumGPRs) { 6362 if (Arg.getValueType() == MVT::i1) 6363 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6364 6365 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6366 } else { 6367 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6368 isPPC64, isTailCall, false, MemOpChains, 6369 TailCallArguments, dl); 6370 } 6371 ArgOffset += PtrByteSize; 6372 break; 6373 case MVT::f32: 6374 case MVT::f64: 6375 if (FPR_idx != NumFPRs) { 6376 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6377 6378 if (isVarArg) { 6379 SDValue Store = 6380 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6381 MemOpChains.push_back(Store); 6382 6383 // Float varargs are always shadowed in available integer registers 6384 if (GPR_idx != NumGPRs) { 6385 SDValue Load = 6386 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6387 MemOpChains.push_back(Load.getValue(1)); 6388 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6389 } 6390 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6391 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6392 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6393 SDValue Load = 6394 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6395 MemOpChains.push_back(Load.getValue(1)); 6396 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6397 } 6398 } else { 6399 // If we have any FPRs remaining, we may also have GPRs remaining. 6400 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6401 // GPRs. 6402 if (GPR_idx != NumGPRs) 6403 ++GPR_idx; 6404 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6405 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6406 ++GPR_idx; 6407 } 6408 } else 6409 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6410 isPPC64, isTailCall, false, MemOpChains, 6411 TailCallArguments, dl); 6412 if (isPPC64) 6413 ArgOffset += 8; 6414 else 6415 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6416 break; 6417 case MVT::v4f32: 6418 case MVT::v4i32: 6419 case MVT::v8i16: 6420 case MVT::v16i8: 6421 if (isVarArg) { 6422 // These go aligned on the stack, or in the corresponding R registers 6423 // when within range. The Darwin PPC ABI doc claims they also go in 6424 // V registers; in fact gcc does this only for arguments that are 6425 // prototyped, not for those that match the ... We do it for all 6426 // arguments, seems to work. 6427 while (ArgOffset % 16 !=0) { 6428 ArgOffset += PtrByteSize; 6429 if (GPR_idx != NumGPRs) 6430 GPR_idx++; 6431 } 6432 // We could elide this store in the case where the object fits 6433 // entirely in R registers. Maybe later. 6434 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6435 DAG.getConstant(ArgOffset, dl, PtrVT)); 6436 SDValue Store = 6437 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6438 MemOpChains.push_back(Store); 6439 if (VR_idx != NumVRs) { 6440 SDValue Load = 6441 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6442 MemOpChains.push_back(Load.getValue(1)); 6443 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6444 } 6445 ArgOffset += 16; 6446 for (unsigned i=0; i<16; i+=PtrByteSize) { 6447 if (GPR_idx == NumGPRs) 6448 break; 6449 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6450 DAG.getConstant(i, dl, PtrVT)); 6451 SDValue Load = 6452 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6453 MemOpChains.push_back(Load.getValue(1)); 6454 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6455 } 6456 break; 6457 } 6458 6459 // Non-varargs Altivec params generally go in registers, but have 6460 // stack space allocated at the end. 6461 if (VR_idx != NumVRs) { 6462 // Doesn't have GPR space allocated. 6463 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6464 } else if (nAltivecParamsAtEnd==0) { 6465 // We are emitting Altivec params in order. 6466 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6467 isPPC64, isTailCall, true, MemOpChains, 6468 TailCallArguments, dl); 6469 ArgOffset += 16; 6470 } 6471 break; 6472 } 6473 } 6474 // If all Altivec parameters fit in registers, as they usually do, 6475 // they get stack space following the non-Altivec parameters. We 6476 // don't track this here because nobody below needs it. 6477 // If there are more Altivec parameters than fit in registers emit 6478 // the stores here. 6479 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6480 unsigned j = 0; 6481 // Offset is aligned; skip 1st 12 params which go in V registers. 6482 ArgOffset = ((ArgOffset+15)/16)*16; 6483 ArgOffset += 12*16; 6484 for (unsigned i = 0; i != NumOps; ++i) { 6485 SDValue Arg = OutVals[i]; 6486 EVT ArgType = Outs[i].VT; 6487 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6488 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6489 if (++j > NumVRs) { 6490 SDValue PtrOff; 6491 // We are emitting Altivec params in order. 6492 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6493 isPPC64, isTailCall, true, MemOpChains, 6494 TailCallArguments, dl); 6495 ArgOffset += 16; 6496 } 6497 } 6498 } 6499 } 6500 6501 if (!MemOpChains.empty()) 6502 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6503 6504 // On Darwin, R12 must contain the address of an indirect callee. This does 6505 // not mean the MTCTR instruction must use R12; it's easier to model this as 6506 // an extra parameter, so do that. 6507 if (!isTailCall && 6508 !isFunctionGlobalAddress(Callee) && 6509 !isa<ExternalSymbolSDNode>(Callee) && 6510 !isBLACompatibleAddress(Callee, DAG)) 6511 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6512 PPC::R12), Callee)); 6513 6514 // Build a sequence of copy-to-reg nodes chained together with token chain 6515 // and flag operands which copy the outgoing args into the appropriate regs. 6516 SDValue InFlag; 6517 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6518 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6519 RegsToPass[i].second, InFlag); 6520 InFlag = Chain.getValue(1); 6521 } 6522 6523 if (isTailCall) 6524 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6525 TailCallArguments); 6526 6527 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6528 /* unused except on PPC64 ELFv1 */ false, DAG, 6529 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6530 NumBytes, Ins, InVals, CS); 6531 } 6532 6533 bool 6534 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6535 MachineFunction &MF, bool isVarArg, 6536 const SmallVectorImpl<ISD::OutputArg> &Outs, 6537 LLVMContext &Context) const { 6538 SmallVector<CCValAssign, 16> RVLocs; 6539 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6540 return CCInfo.CheckReturn( 6541 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6542 ? RetCC_PPC_Cold 6543 : RetCC_PPC); 6544 } 6545 6546 SDValue 6547 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6548 bool isVarArg, 6549 const SmallVectorImpl<ISD::OutputArg> &Outs, 6550 const SmallVectorImpl<SDValue> &OutVals, 6551 const SDLoc &dl, SelectionDAG &DAG) const { 6552 SmallVector<CCValAssign, 16> RVLocs; 6553 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6554 *DAG.getContext()); 6555 CCInfo.AnalyzeReturn(Outs, 6556 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6557 ? RetCC_PPC_Cold 6558 : RetCC_PPC); 6559 6560 SDValue Flag; 6561 SmallVector<SDValue, 4> RetOps(1, Chain); 6562 6563 // Copy the result values into the output registers. 6564 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6565 CCValAssign &VA = RVLocs[i]; 6566 assert(VA.isRegLoc() && "Can only return in registers!"); 6567 6568 SDValue Arg = OutVals[i]; 6569 6570 switch (VA.getLocInfo()) { 6571 default: llvm_unreachable("Unknown loc info!"); 6572 case CCValAssign::Full: break; 6573 case CCValAssign::AExt: 6574 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6575 break; 6576 case CCValAssign::ZExt: 6577 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6578 break; 6579 case CCValAssign::SExt: 6580 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6581 break; 6582 } 6583 6584 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6585 Flag = Chain.getValue(1); 6586 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6587 } 6588 6589 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6590 const MCPhysReg *I = 6591 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6592 if (I) { 6593 for (; *I; ++I) { 6594 6595 if (PPC::G8RCRegClass.contains(*I)) 6596 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6597 else if (PPC::F8RCRegClass.contains(*I)) 6598 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6599 else if (PPC::CRRCRegClass.contains(*I)) 6600 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6601 else if (PPC::VRRCRegClass.contains(*I)) 6602 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6603 else 6604 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6605 } 6606 } 6607 6608 RetOps[0] = Chain; // Update chain. 6609 6610 // Add the flag if we have it. 6611 if (Flag.getNode()) 6612 RetOps.push_back(Flag); 6613 6614 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6615 } 6616 6617 SDValue 6618 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6619 SelectionDAG &DAG) const { 6620 SDLoc dl(Op); 6621 6622 // Get the correct type for integers. 6623 EVT IntVT = Op.getValueType(); 6624 6625 // Get the inputs. 6626 SDValue Chain = Op.getOperand(0); 6627 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6628 // Build a DYNAREAOFFSET node. 6629 SDValue Ops[2] = {Chain, FPSIdx}; 6630 SDVTList VTs = DAG.getVTList(IntVT); 6631 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6632 } 6633 6634 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6635 SelectionDAG &DAG) const { 6636 // When we pop the dynamic allocation we need to restore the SP link. 6637 SDLoc dl(Op); 6638 6639 // Get the correct type for pointers. 6640 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6641 6642 // Construct the stack pointer operand. 6643 bool isPPC64 = Subtarget.isPPC64(); 6644 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6645 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6646 6647 // Get the operands for the STACKRESTORE. 6648 SDValue Chain = Op.getOperand(0); 6649 SDValue SaveSP = Op.getOperand(1); 6650 6651 // Load the old link SP. 6652 SDValue LoadLinkSP = 6653 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6654 6655 // Restore the stack pointer. 6656 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6657 6658 // Store the old link SP. 6659 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6660 } 6661 6662 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6663 MachineFunction &MF = DAG.getMachineFunction(); 6664 bool isPPC64 = Subtarget.isPPC64(); 6665 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6666 6667 // Get current frame pointer save index. The users of this index will be 6668 // primarily DYNALLOC instructions. 6669 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6670 int RASI = FI->getReturnAddrSaveIndex(); 6671 6672 // If the frame pointer save index hasn't been defined yet. 6673 if (!RASI) { 6674 // Find out what the fix offset of the frame pointer save area. 6675 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6676 // Allocate the frame index for frame pointer save area. 6677 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6678 // Save the result. 6679 FI->setReturnAddrSaveIndex(RASI); 6680 } 6681 return DAG.getFrameIndex(RASI, PtrVT); 6682 } 6683 6684 SDValue 6685 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6686 MachineFunction &MF = DAG.getMachineFunction(); 6687 bool isPPC64 = Subtarget.isPPC64(); 6688 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6689 6690 // Get current frame pointer save index. The users of this index will be 6691 // primarily DYNALLOC instructions. 6692 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6693 int FPSI = FI->getFramePointerSaveIndex(); 6694 6695 // If the frame pointer save index hasn't been defined yet. 6696 if (!FPSI) { 6697 // Find out what the fix offset of the frame pointer save area. 6698 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6699 // Allocate the frame index for frame pointer save area. 6700 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6701 // Save the result. 6702 FI->setFramePointerSaveIndex(FPSI); 6703 } 6704 return DAG.getFrameIndex(FPSI, PtrVT); 6705 } 6706 6707 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6708 SelectionDAG &DAG) const { 6709 // Get the inputs. 6710 SDValue Chain = Op.getOperand(0); 6711 SDValue Size = Op.getOperand(1); 6712 SDLoc dl(Op); 6713 6714 // Get the correct type for pointers. 6715 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6716 // Negate the size. 6717 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6718 DAG.getConstant(0, dl, PtrVT), Size); 6719 // Construct a node for the frame pointer save index. 6720 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6721 // Build a DYNALLOC node. 6722 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6723 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6724 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6725 } 6726 6727 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6728 SelectionDAG &DAG) const { 6729 MachineFunction &MF = DAG.getMachineFunction(); 6730 6731 bool isPPC64 = Subtarget.isPPC64(); 6732 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6733 6734 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6735 return DAG.getFrameIndex(FI, PtrVT); 6736 } 6737 6738 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6739 SelectionDAG &DAG) const { 6740 SDLoc DL(Op); 6741 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6742 DAG.getVTList(MVT::i32, MVT::Other), 6743 Op.getOperand(0), Op.getOperand(1)); 6744 } 6745 6746 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6747 SelectionDAG &DAG) const { 6748 SDLoc DL(Op); 6749 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6750 Op.getOperand(0), Op.getOperand(1)); 6751 } 6752 6753 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6754 if (Op.getValueType().isVector()) 6755 return LowerVectorLoad(Op, DAG); 6756 6757 assert(Op.getValueType() == MVT::i1 && 6758 "Custom lowering only for i1 loads"); 6759 6760 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6761 6762 SDLoc dl(Op); 6763 LoadSDNode *LD = cast<LoadSDNode>(Op); 6764 6765 SDValue Chain = LD->getChain(); 6766 SDValue BasePtr = LD->getBasePtr(); 6767 MachineMemOperand *MMO = LD->getMemOperand(); 6768 6769 SDValue NewLD = 6770 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6771 BasePtr, MVT::i8, MMO); 6772 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6773 6774 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6775 return DAG.getMergeValues(Ops, dl); 6776 } 6777 6778 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6779 if (Op.getOperand(1).getValueType().isVector()) 6780 return LowerVectorStore(Op, DAG); 6781 6782 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6783 "Custom lowering only for i1 stores"); 6784 6785 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6786 6787 SDLoc dl(Op); 6788 StoreSDNode *ST = cast<StoreSDNode>(Op); 6789 6790 SDValue Chain = ST->getChain(); 6791 SDValue BasePtr = ST->getBasePtr(); 6792 SDValue Value = ST->getValue(); 6793 MachineMemOperand *MMO = ST->getMemOperand(); 6794 6795 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6796 Value); 6797 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6798 } 6799 6800 // FIXME: Remove this once the ANDI glue bug is fixed: 6801 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6802 assert(Op.getValueType() == MVT::i1 && 6803 "Custom lowering only for i1 results"); 6804 6805 SDLoc DL(Op); 6806 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6807 Op.getOperand(0)); 6808 } 6809 6810 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 6811 SelectionDAG &DAG) const { 6812 6813 // Implements a vector truncate that fits in a vector register as a shuffle. 6814 // We want to legalize vector truncates down to where the source fits in 6815 // a vector register (and target is therefore smaller than vector register 6816 // size). At that point legalization will try to custom lower the sub-legal 6817 // result and get here - where we can contain the truncate as a single target 6818 // operation. 6819 6820 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 6821 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 6822 // 6823 // We will implement it for big-endian ordering as this (where x denotes 6824 // undefined): 6825 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 6826 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 6827 // 6828 // The same operation in little-endian ordering will be: 6829 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 6830 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 6831 6832 assert(Op.getValueType().isVector() && "Vector type expected."); 6833 6834 SDLoc DL(Op); 6835 SDValue N1 = Op.getOperand(0); 6836 unsigned SrcSize = N1.getValueType().getSizeInBits(); 6837 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 6838 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 6839 6840 EVT TrgVT = Op.getValueType(); 6841 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 6842 EVT EltVT = TrgVT.getVectorElementType(); 6843 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 6844 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 6845 6846 // First list the elements we want to keep. 6847 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 6848 SmallVector<int, 16> ShuffV; 6849 if (Subtarget.isLittleEndian()) 6850 for (unsigned i = 0; i < TrgNumElts; ++i) 6851 ShuffV.push_back(i * SizeMult); 6852 else 6853 for (unsigned i = 1; i <= TrgNumElts; ++i) 6854 ShuffV.push_back(i * SizeMult - 1); 6855 6856 // Populate the remaining elements with undefs. 6857 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 6858 // ShuffV.push_back(i + WideNumElts); 6859 ShuffV.push_back(WideNumElts + 1); 6860 6861 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 6862 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 6863 } 6864 6865 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6866 /// possible. 6867 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6868 // Not FP? Not a fsel. 6869 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6870 !Op.getOperand(2).getValueType().isFloatingPoint()) 6871 return Op; 6872 6873 // We might be able to do better than this under some circumstances, but in 6874 // general, fsel-based lowering of select is a finite-math-only optimization. 6875 // For more information, see section F.3 of the 2.06 ISA specification. 6876 if (!DAG.getTarget().Options.NoInfsFPMath || 6877 !DAG.getTarget().Options.NoNaNsFPMath) 6878 return Op; 6879 // TODO: Propagate flags from the select rather than global settings. 6880 SDNodeFlags Flags; 6881 Flags.setNoInfs(true); 6882 Flags.setNoNaNs(true); 6883 6884 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6885 6886 EVT ResVT = Op.getValueType(); 6887 EVT CmpVT = Op.getOperand(0).getValueType(); 6888 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6889 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6890 SDLoc dl(Op); 6891 6892 // If the RHS of the comparison is a 0.0, we don't need to do the 6893 // subtraction at all. 6894 SDValue Sel1; 6895 if (isFloatingPointZero(RHS)) 6896 switch (CC) { 6897 default: break; // SETUO etc aren't handled by fsel. 6898 case ISD::SETNE: 6899 std::swap(TV, FV); 6900 LLVM_FALLTHROUGH; 6901 case ISD::SETEQ: 6902 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6903 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6904 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6905 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6906 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6907 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6908 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6909 case ISD::SETULT: 6910 case ISD::SETLT: 6911 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6912 LLVM_FALLTHROUGH; 6913 case ISD::SETOGE: 6914 case ISD::SETGE: 6915 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6916 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6917 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6918 case ISD::SETUGT: 6919 case ISD::SETGT: 6920 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6921 LLVM_FALLTHROUGH; 6922 case ISD::SETOLE: 6923 case ISD::SETLE: 6924 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6925 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6926 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6927 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6928 } 6929 6930 SDValue Cmp; 6931 switch (CC) { 6932 default: break; // SETUO etc aren't handled by fsel. 6933 case ISD::SETNE: 6934 std::swap(TV, FV); 6935 LLVM_FALLTHROUGH; 6936 case ISD::SETEQ: 6937 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6938 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6939 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6940 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6941 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6942 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6943 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6944 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6945 case ISD::SETULT: 6946 case ISD::SETLT: 6947 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6948 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6949 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6950 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6951 case ISD::SETOGE: 6952 case ISD::SETGE: 6953 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6954 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6955 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6956 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6957 case ISD::SETUGT: 6958 case ISD::SETGT: 6959 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6960 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6961 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6962 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6963 case ISD::SETOLE: 6964 case ISD::SETLE: 6965 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6966 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6967 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6968 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6969 } 6970 return Op; 6971 } 6972 6973 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6974 SelectionDAG &DAG, 6975 const SDLoc &dl) const { 6976 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6977 SDValue Src = Op.getOperand(0); 6978 if (Src.getValueType() == MVT::f32) 6979 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6980 6981 SDValue Tmp; 6982 switch (Op.getSimpleValueType().SimpleTy) { 6983 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6984 case MVT::i32: 6985 Tmp = DAG.getNode( 6986 Op.getOpcode() == ISD::FP_TO_SINT 6987 ? PPCISD::FCTIWZ 6988 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6989 dl, MVT::f64, Src); 6990 break; 6991 case MVT::i64: 6992 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6993 "i64 FP_TO_UINT is supported only with FPCVT"); 6994 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6995 PPCISD::FCTIDUZ, 6996 dl, MVT::f64, Src); 6997 break; 6998 } 6999 7000 // Convert the FP value to an int value through memory. 7001 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7002 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7003 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7004 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7005 MachinePointerInfo MPI = 7006 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7007 7008 // Emit a store to the stack slot. 7009 SDValue Chain; 7010 if (i32Stack) { 7011 MachineFunction &MF = DAG.getMachineFunction(); 7012 MachineMemOperand *MMO = 7013 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7014 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7015 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7016 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7017 } else 7018 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7019 7020 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7021 // add in a bias on big endian. 7022 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7023 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7024 DAG.getConstant(4, dl, FIPtr.getValueType())); 7025 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7026 } 7027 7028 RLI.Chain = Chain; 7029 RLI.Ptr = FIPtr; 7030 RLI.MPI = MPI; 7031 } 7032 7033 /// Custom lowers floating point to integer conversions to use 7034 /// the direct move instructions available in ISA 2.07 to avoid the 7035 /// need for load/store combinations. 7036 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7037 SelectionDAG &DAG, 7038 const SDLoc &dl) const { 7039 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7040 SDValue Src = Op.getOperand(0); 7041 7042 if (Src.getValueType() == MVT::f32) 7043 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7044 7045 SDValue Tmp; 7046 switch (Op.getSimpleValueType().SimpleTy) { 7047 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7048 case MVT::i32: 7049 Tmp = DAG.getNode( 7050 Op.getOpcode() == ISD::FP_TO_SINT 7051 ? PPCISD::FCTIWZ 7052 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7053 dl, MVT::f64, Src); 7054 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7055 break; 7056 case MVT::i64: 7057 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7058 "i64 FP_TO_UINT is supported only with FPCVT"); 7059 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7060 PPCISD::FCTIDUZ, 7061 dl, MVT::f64, Src); 7062 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7063 break; 7064 } 7065 return Tmp; 7066 } 7067 7068 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7069 const SDLoc &dl) const { 7070 7071 // FP to INT conversions are legal for f128. 7072 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7073 return Op; 7074 7075 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7076 // PPC (the libcall is not available). 7077 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7078 if (Op.getValueType() == MVT::i32) { 7079 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7080 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7081 MVT::f64, Op.getOperand(0), 7082 DAG.getIntPtrConstant(0, dl)); 7083 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7084 MVT::f64, Op.getOperand(0), 7085 DAG.getIntPtrConstant(1, dl)); 7086 7087 // Add the two halves of the long double in round-to-zero mode. 7088 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7089 7090 // Now use a smaller FP_TO_SINT. 7091 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7092 } 7093 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7094 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7095 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7096 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7097 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7098 // FIXME: generated code sucks. 7099 // TODO: Are there fast-math-flags to propagate to this FSUB? 7100 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7101 Op.getOperand(0), Tmp); 7102 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7103 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7104 DAG.getConstant(0x80000000, dl, MVT::i32)); 7105 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7106 Op.getOperand(0)); 7107 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7108 ISD::SETGE); 7109 } 7110 } 7111 7112 return SDValue(); 7113 } 7114 7115 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7116 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7117 7118 ReuseLoadInfo RLI; 7119 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7120 7121 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7122 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7123 } 7124 7125 // We're trying to insert a regular store, S, and then a load, L. If the 7126 // incoming value, O, is a load, we might just be able to have our load use the 7127 // address used by O. However, we don't know if anything else will store to 7128 // that address before we can load from it. To prevent this situation, we need 7129 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7130 // the same chain operand as O, we create a token factor from the chain results 7131 // of O and L, and we replace all uses of O's chain result with that token 7132 // factor (see spliceIntoChain below for this last part). 7133 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7134 ReuseLoadInfo &RLI, 7135 SelectionDAG &DAG, 7136 ISD::LoadExtType ET) const { 7137 SDLoc dl(Op); 7138 if (ET == ISD::NON_EXTLOAD && 7139 (Op.getOpcode() == ISD::FP_TO_UINT || 7140 Op.getOpcode() == ISD::FP_TO_SINT) && 7141 isOperationLegalOrCustom(Op.getOpcode(), 7142 Op.getOperand(0).getValueType())) { 7143 7144 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7145 return true; 7146 } 7147 7148 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7149 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7150 LD->isNonTemporal()) 7151 return false; 7152 if (LD->getMemoryVT() != MemVT) 7153 return false; 7154 7155 RLI.Ptr = LD->getBasePtr(); 7156 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7157 assert(LD->getAddressingMode() == ISD::PRE_INC && 7158 "Non-pre-inc AM on PPC?"); 7159 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7160 LD->getOffset()); 7161 } 7162 7163 RLI.Chain = LD->getChain(); 7164 RLI.MPI = LD->getPointerInfo(); 7165 RLI.IsDereferenceable = LD->isDereferenceable(); 7166 RLI.IsInvariant = LD->isInvariant(); 7167 RLI.Alignment = LD->getAlignment(); 7168 RLI.AAInfo = LD->getAAInfo(); 7169 RLI.Ranges = LD->getRanges(); 7170 7171 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7172 return true; 7173 } 7174 7175 // Given the head of the old chain, ResChain, insert a token factor containing 7176 // it and NewResChain, and make users of ResChain now be users of that token 7177 // factor. 7178 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7179 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7180 SDValue NewResChain, 7181 SelectionDAG &DAG) const { 7182 if (!ResChain) 7183 return; 7184 7185 SDLoc dl(NewResChain); 7186 7187 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7188 NewResChain, DAG.getUNDEF(MVT::Other)); 7189 assert(TF.getNode() != NewResChain.getNode() && 7190 "A new TF really is required here"); 7191 7192 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7193 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7194 } 7195 7196 /// Analyze profitability of direct move 7197 /// prefer float load to int load plus direct move 7198 /// when there is no integer use of int load 7199 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7200 SDNode *Origin = Op.getOperand(0).getNode(); 7201 if (Origin->getOpcode() != ISD::LOAD) 7202 return true; 7203 7204 // If there is no LXSIBZX/LXSIHZX, like Power8, 7205 // prefer direct move if the memory size is 1 or 2 bytes. 7206 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7207 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7208 return true; 7209 7210 for (SDNode::use_iterator UI = Origin->use_begin(), 7211 UE = Origin->use_end(); 7212 UI != UE; ++UI) { 7213 7214 // Only look at the users of the loaded value. 7215 if (UI.getUse().get().getResNo() != 0) 7216 continue; 7217 7218 if (UI->getOpcode() != ISD::SINT_TO_FP && 7219 UI->getOpcode() != ISD::UINT_TO_FP) 7220 return true; 7221 } 7222 7223 return false; 7224 } 7225 7226 /// Custom lowers integer to floating point conversions to use 7227 /// the direct move instructions available in ISA 2.07 to avoid the 7228 /// need for load/store combinations. 7229 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7230 SelectionDAG &DAG, 7231 const SDLoc &dl) const { 7232 assert((Op.getValueType() == MVT::f32 || 7233 Op.getValueType() == MVT::f64) && 7234 "Invalid floating point type as target of conversion"); 7235 assert(Subtarget.hasFPCVT() && 7236 "Int to FP conversions with direct moves require FPCVT"); 7237 SDValue FP; 7238 SDValue Src = Op.getOperand(0); 7239 bool SinglePrec = Op.getValueType() == MVT::f32; 7240 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7241 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7242 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7243 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7244 7245 if (WordInt) { 7246 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7247 dl, MVT::f64, Src); 7248 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7249 } 7250 else { 7251 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7252 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7253 } 7254 7255 return FP; 7256 } 7257 7258 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7259 7260 EVT VecVT = Vec.getValueType(); 7261 assert(VecVT.isVector() && "Expected a vector type."); 7262 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7263 7264 EVT EltVT = VecVT.getVectorElementType(); 7265 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7266 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7267 7268 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7269 SmallVector<SDValue, 16> Ops(NumConcat); 7270 Ops[0] = Vec; 7271 SDValue UndefVec = DAG.getUNDEF(VecVT); 7272 for (unsigned i = 1; i < NumConcat; ++i) 7273 Ops[i] = UndefVec; 7274 7275 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7276 } 7277 7278 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7279 const SDLoc &dl) const { 7280 7281 unsigned Opc = Op.getOpcode(); 7282 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7283 "Unexpected conversion type"); 7284 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7285 "Supports conversions to v2f64/v4f32 only."); 7286 7287 bool SignedConv = Opc == ISD::SINT_TO_FP; 7288 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7289 7290 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7291 EVT WideVT = Wide.getValueType(); 7292 unsigned WideNumElts = WideVT.getVectorNumElements(); 7293 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7294 7295 SmallVector<int, 16> ShuffV; 7296 for (unsigned i = 0; i < WideNumElts; ++i) 7297 ShuffV.push_back(i + WideNumElts); 7298 7299 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7300 int SaveElts = FourEltRes ? 4 : 2; 7301 if (Subtarget.isLittleEndian()) 7302 for (int i = 0; i < SaveElts; i++) 7303 ShuffV[i * Stride] = i; 7304 else 7305 for (int i = 1; i <= SaveElts; i++) 7306 ShuffV[i * Stride - 1] = i - 1; 7307 7308 SDValue ShuffleSrc2 = 7309 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7310 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7311 unsigned ExtendOp = 7312 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7313 7314 SDValue Extend; 7315 if (!Subtarget.hasP9Altivec() && SignedConv) { 7316 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7317 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7318 DAG.getValueType(Op.getOperand(0).getValueType())); 7319 } else 7320 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7321 7322 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7323 } 7324 7325 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7326 SelectionDAG &DAG) const { 7327 SDLoc dl(Op); 7328 7329 EVT InVT = Op.getOperand(0).getValueType(); 7330 EVT OutVT = Op.getValueType(); 7331 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7332 isOperationCustom(Op.getOpcode(), InVT)) 7333 return LowerINT_TO_FPVector(Op, DAG, dl); 7334 7335 // Conversions to f128 are legal. 7336 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7337 return Op; 7338 7339 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7340 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7341 return SDValue(); 7342 7343 SDValue Value = Op.getOperand(0); 7344 // The values are now known to be -1 (false) or 1 (true). To convert this 7345 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7346 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7347 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7348 7349 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7350 7351 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7352 7353 if (Op.getValueType() != MVT::v4f64) 7354 Value = DAG.getNode(ISD::FP_ROUND, dl, 7355 Op.getValueType(), Value, 7356 DAG.getIntPtrConstant(1, dl)); 7357 return Value; 7358 } 7359 7360 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7361 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7362 return SDValue(); 7363 7364 if (Op.getOperand(0).getValueType() == MVT::i1) 7365 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7366 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7367 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7368 7369 // If we have direct moves, we can do all the conversion, skip the store/load 7370 // however, without FPCVT we can't do most conversions. 7371 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7372 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7373 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7374 7375 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7376 "UINT_TO_FP is supported only with FPCVT"); 7377 7378 // If we have FCFIDS, then use it when converting to single-precision. 7379 // Otherwise, convert to double-precision and then round. 7380 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7381 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7382 : PPCISD::FCFIDS) 7383 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7384 : PPCISD::FCFID); 7385 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7386 ? MVT::f32 7387 : MVT::f64; 7388 7389 if (Op.getOperand(0).getValueType() == MVT::i64) { 7390 SDValue SINT = Op.getOperand(0); 7391 // When converting to single-precision, we actually need to convert 7392 // to double-precision first and then round to single-precision. 7393 // To avoid double-rounding effects during that operation, we have 7394 // to prepare the input operand. Bits that might be truncated when 7395 // converting to double-precision are replaced by a bit that won't 7396 // be lost at this stage, but is below the single-precision rounding 7397 // position. 7398 // 7399 // However, if -enable-unsafe-fp-math is in effect, accept double 7400 // rounding to avoid the extra overhead. 7401 if (Op.getValueType() == MVT::f32 && 7402 !Subtarget.hasFPCVT() && 7403 !DAG.getTarget().Options.UnsafeFPMath) { 7404 7405 // Twiddle input to make sure the low 11 bits are zero. (If this 7406 // is the case, we are guaranteed the value will fit into the 53 bit 7407 // mantissa of an IEEE double-precision value without rounding.) 7408 // If any of those low 11 bits were not zero originally, make sure 7409 // bit 12 (value 2048) is set instead, so that the final rounding 7410 // to single-precision gets the correct result. 7411 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7412 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7413 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7414 Round, DAG.getConstant(2047, dl, MVT::i64)); 7415 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7416 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7417 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7418 7419 // However, we cannot use that value unconditionally: if the magnitude 7420 // of the input value is small, the bit-twiddling we did above might 7421 // end up visibly changing the output. Fortunately, in that case, we 7422 // don't need to twiddle bits since the original input will convert 7423 // exactly to double-precision floating-point already. Therefore, 7424 // construct a conditional to use the original value if the top 11 7425 // bits are all sign-bit copies, and use the rounded value computed 7426 // above otherwise. 7427 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7428 SINT, DAG.getConstant(53, dl, MVT::i32)); 7429 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7430 Cond, DAG.getConstant(1, dl, MVT::i64)); 7431 Cond = DAG.getSetCC(dl, MVT::i32, 7432 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7433 7434 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7435 } 7436 7437 ReuseLoadInfo RLI; 7438 SDValue Bits; 7439 7440 MachineFunction &MF = DAG.getMachineFunction(); 7441 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7442 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7443 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7444 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7445 } else if (Subtarget.hasLFIWAX() && 7446 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7447 MachineMemOperand *MMO = 7448 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7449 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7450 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7451 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7452 DAG.getVTList(MVT::f64, MVT::Other), 7453 Ops, MVT::i32, MMO); 7454 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7455 } else if (Subtarget.hasFPCVT() && 7456 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7457 MachineMemOperand *MMO = 7458 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7459 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7460 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7461 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7462 DAG.getVTList(MVT::f64, MVT::Other), 7463 Ops, MVT::i32, MMO); 7464 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7465 } else if (((Subtarget.hasLFIWAX() && 7466 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7467 (Subtarget.hasFPCVT() && 7468 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7469 SINT.getOperand(0).getValueType() == MVT::i32) { 7470 MachineFrameInfo &MFI = MF.getFrameInfo(); 7471 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7472 7473 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7474 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7475 7476 SDValue Store = 7477 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7478 MachinePointerInfo::getFixedStack( 7479 DAG.getMachineFunction(), FrameIdx)); 7480 7481 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7482 "Expected an i32 store"); 7483 7484 RLI.Ptr = FIdx; 7485 RLI.Chain = Store; 7486 RLI.MPI = 7487 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7488 RLI.Alignment = 4; 7489 7490 MachineMemOperand *MMO = 7491 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7492 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7493 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7494 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7495 PPCISD::LFIWZX : PPCISD::LFIWAX, 7496 dl, DAG.getVTList(MVT::f64, MVT::Other), 7497 Ops, MVT::i32, MMO); 7498 } else 7499 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7500 7501 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7502 7503 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7504 FP = DAG.getNode(ISD::FP_ROUND, dl, 7505 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7506 return FP; 7507 } 7508 7509 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7510 "Unhandled INT_TO_FP type in custom expander!"); 7511 // Since we only generate this in 64-bit mode, we can take advantage of 7512 // 64-bit registers. In particular, sign extend the input value into the 7513 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7514 // then lfd it and fcfid it. 7515 MachineFunction &MF = DAG.getMachineFunction(); 7516 MachineFrameInfo &MFI = MF.getFrameInfo(); 7517 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7518 7519 SDValue Ld; 7520 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7521 ReuseLoadInfo RLI; 7522 bool ReusingLoad; 7523 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7524 DAG))) { 7525 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7526 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7527 7528 SDValue Store = 7529 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7530 MachinePointerInfo::getFixedStack( 7531 DAG.getMachineFunction(), FrameIdx)); 7532 7533 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7534 "Expected an i32 store"); 7535 7536 RLI.Ptr = FIdx; 7537 RLI.Chain = Store; 7538 RLI.MPI = 7539 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7540 RLI.Alignment = 4; 7541 } 7542 7543 MachineMemOperand *MMO = 7544 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7545 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7546 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7547 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7548 PPCISD::LFIWZX : PPCISD::LFIWAX, 7549 dl, DAG.getVTList(MVT::f64, MVT::Other), 7550 Ops, MVT::i32, MMO); 7551 if (ReusingLoad) 7552 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7553 } else { 7554 assert(Subtarget.isPPC64() && 7555 "i32->FP without LFIWAX supported only on PPC64"); 7556 7557 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7558 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7559 7560 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7561 Op.getOperand(0)); 7562 7563 // STD the extended value into the stack slot. 7564 SDValue Store = DAG.getStore( 7565 DAG.getEntryNode(), dl, Ext64, FIdx, 7566 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7567 7568 // Load the value as a double. 7569 Ld = DAG.getLoad( 7570 MVT::f64, dl, Store, FIdx, 7571 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7572 } 7573 7574 // FCFID it and return it. 7575 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7576 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7577 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7578 DAG.getIntPtrConstant(0, dl)); 7579 return FP; 7580 } 7581 7582 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7583 SelectionDAG &DAG) const { 7584 SDLoc dl(Op); 7585 /* 7586 The rounding mode is in bits 30:31 of FPSR, and has the following 7587 settings: 7588 00 Round to nearest 7589 01 Round to 0 7590 10 Round to +inf 7591 11 Round to -inf 7592 7593 FLT_ROUNDS, on the other hand, expects the following: 7594 -1 Undefined 7595 0 Round to 0 7596 1 Round to nearest 7597 2 Round to +inf 7598 3 Round to -inf 7599 7600 To perform the conversion, we do: 7601 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7602 */ 7603 7604 MachineFunction &MF = DAG.getMachineFunction(); 7605 EVT VT = Op.getValueType(); 7606 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7607 7608 // Save FP Control Word to register 7609 EVT NodeTys[] = { 7610 MVT::f64, // return register 7611 MVT::Glue // unused in this context 7612 }; 7613 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7614 7615 // Save FP register to stack slot 7616 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7617 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7618 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7619 MachinePointerInfo()); 7620 7621 // Load FP Control Word from low 32 bits of stack slot. 7622 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7623 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7624 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7625 7626 // Transform as necessary 7627 SDValue CWD1 = 7628 DAG.getNode(ISD::AND, dl, MVT::i32, 7629 CWD, DAG.getConstant(3, dl, MVT::i32)); 7630 SDValue CWD2 = 7631 DAG.getNode(ISD::SRL, dl, MVT::i32, 7632 DAG.getNode(ISD::AND, dl, MVT::i32, 7633 DAG.getNode(ISD::XOR, dl, MVT::i32, 7634 CWD, DAG.getConstant(3, dl, MVT::i32)), 7635 DAG.getConstant(3, dl, MVT::i32)), 7636 DAG.getConstant(1, dl, MVT::i32)); 7637 7638 SDValue RetVal = 7639 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7640 7641 return DAG.getNode((VT.getSizeInBits() < 16 ? 7642 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7643 } 7644 7645 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7646 EVT VT = Op.getValueType(); 7647 unsigned BitWidth = VT.getSizeInBits(); 7648 SDLoc dl(Op); 7649 assert(Op.getNumOperands() == 3 && 7650 VT == Op.getOperand(1).getValueType() && 7651 "Unexpected SHL!"); 7652 7653 // Expand into a bunch of logical ops. Note that these ops 7654 // depend on the PPC behavior for oversized shift amounts. 7655 SDValue Lo = Op.getOperand(0); 7656 SDValue Hi = Op.getOperand(1); 7657 SDValue Amt = Op.getOperand(2); 7658 EVT AmtVT = Amt.getValueType(); 7659 7660 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7661 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7662 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7663 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7664 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7665 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7666 DAG.getConstant(-BitWidth, dl, AmtVT)); 7667 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7668 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7669 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7670 SDValue OutOps[] = { OutLo, OutHi }; 7671 return DAG.getMergeValues(OutOps, dl); 7672 } 7673 7674 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7675 EVT VT = Op.getValueType(); 7676 SDLoc dl(Op); 7677 unsigned BitWidth = VT.getSizeInBits(); 7678 assert(Op.getNumOperands() == 3 && 7679 VT == Op.getOperand(1).getValueType() && 7680 "Unexpected SRL!"); 7681 7682 // Expand into a bunch of logical ops. Note that these ops 7683 // depend on the PPC behavior for oversized shift amounts. 7684 SDValue Lo = Op.getOperand(0); 7685 SDValue Hi = Op.getOperand(1); 7686 SDValue Amt = Op.getOperand(2); 7687 EVT AmtVT = Amt.getValueType(); 7688 7689 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7690 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7691 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7692 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7693 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7694 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7695 DAG.getConstant(-BitWidth, dl, AmtVT)); 7696 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7697 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7698 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7699 SDValue OutOps[] = { OutLo, OutHi }; 7700 return DAG.getMergeValues(OutOps, dl); 7701 } 7702 7703 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7704 SDLoc dl(Op); 7705 EVT VT = Op.getValueType(); 7706 unsigned BitWidth = VT.getSizeInBits(); 7707 assert(Op.getNumOperands() == 3 && 7708 VT == Op.getOperand(1).getValueType() && 7709 "Unexpected SRA!"); 7710 7711 // Expand into a bunch of logical ops, followed by a select_cc. 7712 SDValue Lo = Op.getOperand(0); 7713 SDValue Hi = Op.getOperand(1); 7714 SDValue Amt = Op.getOperand(2); 7715 EVT AmtVT = Amt.getValueType(); 7716 7717 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7718 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7719 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7720 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7721 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7722 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7723 DAG.getConstant(-BitWidth, dl, AmtVT)); 7724 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7725 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7726 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7727 Tmp4, Tmp6, ISD::SETLE); 7728 SDValue OutOps[] = { OutLo, OutHi }; 7729 return DAG.getMergeValues(OutOps, dl); 7730 } 7731 7732 //===----------------------------------------------------------------------===// 7733 // Vector related lowering. 7734 // 7735 7736 /// BuildSplatI - Build a canonical splati of Val with an element size of 7737 /// SplatSize. Cast the result to VT. 7738 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7739 SelectionDAG &DAG, const SDLoc &dl) { 7740 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7741 7742 static const MVT VTys[] = { // canonical VT to use for each size. 7743 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7744 }; 7745 7746 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7747 7748 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7749 if (Val == -1) 7750 SplatSize = 1; 7751 7752 EVT CanonicalVT = VTys[SplatSize-1]; 7753 7754 // Build a canonical splat for this value. 7755 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7756 } 7757 7758 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7759 /// specified intrinsic ID. 7760 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7761 const SDLoc &dl, EVT DestVT = MVT::Other) { 7762 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7763 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7764 DAG.getConstant(IID, dl, MVT::i32), Op); 7765 } 7766 7767 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7768 /// specified intrinsic ID. 7769 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7770 SelectionDAG &DAG, const SDLoc &dl, 7771 EVT DestVT = MVT::Other) { 7772 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7773 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7774 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7775 } 7776 7777 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7778 /// specified intrinsic ID. 7779 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7780 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7781 EVT DestVT = MVT::Other) { 7782 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7783 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7784 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7785 } 7786 7787 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7788 /// amount. The result has the specified value type. 7789 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7790 SelectionDAG &DAG, const SDLoc &dl) { 7791 // Force LHS/RHS to be the right type. 7792 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7793 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7794 7795 int Ops[16]; 7796 for (unsigned i = 0; i != 16; ++i) 7797 Ops[i] = i + Amt; 7798 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7799 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7800 } 7801 7802 /// Do we have an efficient pattern in a .td file for this node? 7803 /// 7804 /// \param V - pointer to the BuildVectorSDNode being matched 7805 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7806 /// 7807 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7808 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7809 /// the opposite is true (expansion is beneficial) are: 7810 /// - The node builds a vector out of integers that are not 32 or 64-bits 7811 /// - The node builds a vector out of constants 7812 /// - The node is a "load-and-splat" 7813 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7814 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7815 bool HasDirectMove, 7816 bool HasP8Vector) { 7817 EVT VecVT = V->getValueType(0); 7818 bool RightType = VecVT == MVT::v2f64 || 7819 (HasP8Vector && VecVT == MVT::v4f32) || 7820 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7821 if (!RightType) 7822 return false; 7823 7824 bool IsSplat = true; 7825 bool IsLoad = false; 7826 SDValue Op0 = V->getOperand(0); 7827 7828 // This function is called in a block that confirms the node is not a constant 7829 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7830 // different constants. 7831 if (V->isConstant()) 7832 return false; 7833 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7834 if (V->getOperand(i).isUndef()) 7835 return false; 7836 // We want to expand nodes that represent load-and-splat even if the 7837 // loaded value is a floating point truncation or conversion to int. 7838 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7839 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7840 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7841 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7842 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7843 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7844 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7845 IsLoad = true; 7846 // If the operands are different or the input is not a load and has more 7847 // uses than just this BV node, then it isn't a splat. 7848 if (V->getOperand(i) != Op0 || 7849 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7850 IsSplat = false; 7851 } 7852 return !(IsSplat && IsLoad); 7853 } 7854 7855 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 7856 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 7857 7858 SDLoc dl(Op); 7859 SDValue Op0 = Op->getOperand(0); 7860 7861 if (!EnableQuadPrecision || 7862 (Op.getValueType() != MVT::f128 ) || 7863 (Op0.getOpcode() != ISD::BUILD_PAIR) || 7864 (Op0.getOperand(0).getValueType() != MVT::i64) || 7865 (Op0.getOperand(1).getValueType() != MVT::i64)) 7866 return SDValue(); 7867 7868 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 7869 Op0.getOperand(1)); 7870 } 7871 7872 // If this is a case we can't handle, return null and let the default 7873 // expansion code take care of it. If we CAN select this case, and if it 7874 // selects to a single instruction, return Op. Otherwise, if we can codegen 7875 // this case more efficiently than a constant pool load, lower it to the 7876 // sequence of ops that should be used. 7877 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7878 SelectionDAG &DAG) const { 7879 SDLoc dl(Op); 7880 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7881 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7882 7883 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7884 // We first build an i32 vector, load it into a QPX register, 7885 // then convert it to a floating-point vector and compare it 7886 // to a zero vector to get the boolean result. 7887 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7888 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7889 MachinePointerInfo PtrInfo = 7890 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7891 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7892 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7893 7894 assert(BVN->getNumOperands() == 4 && 7895 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7896 7897 bool IsConst = true; 7898 for (unsigned i = 0; i < 4; ++i) { 7899 if (BVN->getOperand(i).isUndef()) continue; 7900 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7901 IsConst = false; 7902 break; 7903 } 7904 } 7905 7906 if (IsConst) { 7907 Constant *One = 7908 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7909 Constant *NegOne = 7910 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7911 7912 Constant *CV[4]; 7913 for (unsigned i = 0; i < 4; ++i) { 7914 if (BVN->getOperand(i).isUndef()) 7915 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7916 else if (isNullConstant(BVN->getOperand(i))) 7917 CV[i] = NegOne; 7918 else 7919 CV[i] = One; 7920 } 7921 7922 Constant *CP = ConstantVector::get(CV); 7923 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7924 16 /* alignment */); 7925 7926 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7927 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7928 return DAG.getMemIntrinsicNode( 7929 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7930 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7931 } 7932 7933 SmallVector<SDValue, 4> Stores; 7934 for (unsigned i = 0; i < 4; ++i) { 7935 if (BVN->getOperand(i).isUndef()) continue; 7936 7937 unsigned Offset = 4*i; 7938 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7939 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7940 7941 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7942 if (StoreSize > 4) { 7943 Stores.push_back( 7944 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7945 PtrInfo.getWithOffset(Offset), MVT::i32)); 7946 } else { 7947 SDValue StoreValue = BVN->getOperand(i); 7948 if (StoreSize < 4) 7949 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7950 7951 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7952 PtrInfo.getWithOffset(Offset))); 7953 } 7954 } 7955 7956 SDValue StoreChain; 7957 if (!Stores.empty()) 7958 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7959 else 7960 StoreChain = DAG.getEntryNode(); 7961 7962 // Now load from v4i32 into the QPX register; this will extend it to 7963 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7964 // is typed as v4f64 because the QPX register integer states are not 7965 // explicitly represented. 7966 7967 SDValue Ops[] = {StoreChain, 7968 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7969 FIdx}; 7970 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7971 7972 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7973 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7974 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7975 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7976 LoadedVect); 7977 7978 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7979 7980 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7981 } 7982 7983 // All other QPX vectors are handled by generic code. 7984 if (Subtarget.hasQPX()) 7985 return SDValue(); 7986 7987 // Check if this is a splat of a constant value. 7988 APInt APSplatBits, APSplatUndef; 7989 unsigned SplatBitSize; 7990 bool HasAnyUndefs; 7991 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7992 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7993 SplatBitSize > 32) { 7994 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7995 // lowered to VSX instructions under certain conditions. 7996 // Without VSX, there is no pattern more efficient than expanding the node. 7997 if (Subtarget.hasVSX() && 7998 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7999 Subtarget.hasP8Vector())) 8000 return Op; 8001 return SDValue(); 8002 } 8003 8004 unsigned SplatBits = APSplatBits.getZExtValue(); 8005 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8006 unsigned SplatSize = SplatBitSize / 8; 8007 8008 // First, handle single instruction cases. 8009 8010 // All zeros? 8011 if (SplatBits == 0) { 8012 // Canonicalize all zero vectors to be v4i32. 8013 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8014 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8015 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8016 } 8017 return Op; 8018 } 8019 8020 // We have XXSPLTIB for constant splats one byte wide 8021 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8022 // This is a splat of 1-byte elements with some elements potentially undef. 8023 // Rather than trying to match undef in the SDAG patterns, ensure that all 8024 // elements are the same constant. 8025 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8026 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8027 dl, MVT::i32)); 8028 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8029 if (Op.getValueType() != MVT::v16i8) 8030 return DAG.getBitcast(Op.getValueType(), NewBV); 8031 return NewBV; 8032 } 8033 8034 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8035 // detect that constant splats like v8i16: 0xABAB are really just splats 8036 // of a 1-byte constant. In this case, we need to convert the node to a 8037 // splat of v16i8 and a bitcast. 8038 if (Op.getValueType() != MVT::v16i8) 8039 return DAG.getBitcast(Op.getValueType(), 8040 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8041 8042 return Op; 8043 } 8044 8045 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8046 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8047 (32-SplatBitSize)); 8048 if (SextVal >= -16 && SextVal <= 15) 8049 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8050 8051 // Two instruction sequences. 8052 8053 // If this value is in the range [-32,30] and is even, use: 8054 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8055 // If this value is in the range [17,31] and is odd, use: 8056 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8057 // If this value is in the range [-31,-17] and is odd, use: 8058 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8059 // Note the last two are three-instruction sequences. 8060 if (SextVal >= -32 && SextVal <= 31) { 8061 // To avoid having these optimizations undone by constant folding, 8062 // we convert to a pseudo that will be expanded later into one of 8063 // the above forms. 8064 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8065 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8066 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8067 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8068 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8069 if (VT == Op.getValueType()) 8070 return RetVal; 8071 else 8072 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8073 } 8074 8075 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8076 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8077 // for fneg/fabs. 8078 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8079 // Make -1 and vspltisw -1: 8080 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8081 8082 // Make the VSLW intrinsic, computing 0x8000_0000. 8083 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8084 OnesV, DAG, dl); 8085 8086 // xor by OnesV to invert it. 8087 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8088 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8089 } 8090 8091 // Check to see if this is a wide variety of vsplti*, binop self cases. 8092 static const signed char SplatCsts[] = { 8093 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8094 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8095 }; 8096 8097 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8098 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8099 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8100 int i = SplatCsts[idx]; 8101 8102 // Figure out what shift amount will be used by altivec if shifted by i in 8103 // this splat size. 8104 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8105 8106 // vsplti + shl self. 8107 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8108 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8109 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8110 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8111 Intrinsic::ppc_altivec_vslw 8112 }; 8113 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8114 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8115 } 8116 8117 // vsplti + srl self. 8118 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8119 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8120 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8121 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8122 Intrinsic::ppc_altivec_vsrw 8123 }; 8124 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8125 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8126 } 8127 8128 // vsplti + sra self. 8129 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8130 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8131 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8132 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8133 Intrinsic::ppc_altivec_vsraw 8134 }; 8135 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8136 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8137 } 8138 8139 // vsplti + rol self. 8140 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8141 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8142 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8143 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8144 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8145 Intrinsic::ppc_altivec_vrlw 8146 }; 8147 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8148 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8149 } 8150 8151 // t = vsplti c, result = vsldoi t, t, 1 8152 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8153 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8154 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8155 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8156 } 8157 // t = vsplti c, result = vsldoi t, t, 2 8158 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8159 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8160 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8161 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8162 } 8163 // t = vsplti c, result = vsldoi t, t, 3 8164 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8165 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8166 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8167 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8168 } 8169 } 8170 8171 return SDValue(); 8172 } 8173 8174 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8175 /// the specified operations to build the shuffle. 8176 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8177 SDValue RHS, SelectionDAG &DAG, 8178 const SDLoc &dl) { 8179 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8180 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8181 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8182 8183 enum { 8184 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8185 OP_VMRGHW, 8186 OP_VMRGLW, 8187 OP_VSPLTISW0, 8188 OP_VSPLTISW1, 8189 OP_VSPLTISW2, 8190 OP_VSPLTISW3, 8191 OP_VSLDOI4, 8192 OP_VSLDOI8, 8193 OP_VSLDOI12 8194 }; 8195 8196 if (OpNum == OP_COPY) { 8197 if (LHSID == (1*9+2)*9+3) return LHS; 8198 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8199 return RHS; 8200 } 8201 8202 SDValue OpLHS, OpRHS; 8203 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8204 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8205 8206 int ShufIdxs[16]; 8207 switch (OpNum) { 8208 default: llvm_unreachable("Unknown i32 permute!"); 8209 case OP_VMRGHW: 8210 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8211 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8212 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8213 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8214 break; 8215 case OP_VMRGLW: 8216 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8217 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8218 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8219 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8220 break; 8221 case OP_VSPLTISW0: 8222 for (unsigned i = 0; i != 16; ++i) 8223 ShufIdxs[i] = (i&3)+0; 8224 break; 8225 case OP_VSPLTISW1: 8226 for (unsigned i = 0; i != 16; ++i) 8227 ShufIdxs[i] = (i&3)+4; 8228 break; 8229 case OP_VSPLTISW2: 8230 for (unsigned i = 0; i != 16; ++i) 8231 ShufIdxs[i] = (i&3)+8; 8232 break; 8233 case OP_VSPLTISW3: 8234 for (unsigned i = 0; i != 16; ++i) 8235 ShufIdxs[i] = (i&3)+12; 8236 break; 8237 case OP_VSLDOI4: 8238 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8239 case OP_VSLDOI8: 8240 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8241 case OP_VSLDOI12: 8242 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8243 } 8244 EVT VT = OpLHS.getValueType(); 8245 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8246 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8247 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8248 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8249 } 8250 8251 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8252 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8253 /// SDValue. 8254 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8255 SelectionDAG &DAG) const { 8256 const unsigned BytesInVector = 16; 8257 bool IsLE = Subtarget.isLittleEndian(); 8258 SDLoc dl(N); 8259 SDValue V1 = N->getOperand(0); 8260 SDValue V2 = N->getOperand(1); 8261 unsigned ShiftElts = 0, InsertAtByte = 0; 8262 bool Swap = false; 8263 8264 // Shifts required to get the byte we want at element 7. 8265 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8266 0, 15, 14, 13, 12, 11, 10, 9}; 8267 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8268 1, 2, 3, 4, 5, 6, 7, 8}; 8269 8270 ArrayRef<int> Mask = N->getMask(); 8271 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8272 8273 // For each mask element, find out if we're just inserting something 8274 // from V2 into V1 or vice versa. 8275 // Possible permutations inserting an element from V2 into V1: 8276 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8277 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8278 // ... 8279 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8280 // Inserting from V1 into V2 will be similar, except mask range will be 8281 // [16,31]. 8282 8283 bool FoundCandidate = false; 8284 // If both vector operands for the shuffle are the same vector, the mask 8285 // will contain only elements from the first one and the second one will be 8286 // undef. 8287 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8288 // Go through the mask of half-words to find an element that's being moved 8289 // from one vector to the other. 8290 for (unsigned i = 0; i < BytesInVector; ++i) { 8291 unsigned CurrentElement = Mask[i]; 8292 // If 2nd operand is undefined, we should only look for element 7 in the 8293 // Mask. 8294 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8295 continue; 8296 8297 bool OtherElementsInOrder = true; 8298 // Examine the other elements in the Mask to see if they're in original 8299 // order. 8300 for (unsigned j = 0; j < BytesInVector; ++j) { 8301 if (j == i) 8302 continue; 8303 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8304 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8305 // in which we always assume we're always picking from the 1st operand. 8306 int MaskOffset = 8307 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8308 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8309 OtherElementsInOrder = false; 8310 break; 8311 } 8312 } 8313 // If other elements are in original order, we record the number of shifts 8314 // we need to get the element we want into element 7. Also record which byte 8315 // in the vector we should insert into. 8316 if (OtherElementsInOrder) { 8317 // If 2nd operand is undefined, we assume no shifts and no swapping. 8318 if (V2.isUndef()) { 8319 ShiftElts = 0; 8320 Swap = false; 8321 } else { 8322 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8323 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8324 : BigEndianShifts[CurrentElement & 0xF]; 8325 Swap = CurrentElement < BytesInVector; 8326 } 8327 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8328 FoundCandidate = true; 8329 break; 8330 } 8331 } 8332 8333 if (!FoundCandidate) 8334 return SDValue(); 8335 8336 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8337 // optionally with VECSHL if shift is required. 8338 if (Swap) 8339 std::swap(V1, V2); 8340 if (V2.isUndef()) 8341 V2 = V1; 8342 if (ShiftElts) { 8343 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8344 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8345 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8346 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8347 } 8348 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8349 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8350 } 8351 8352 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8353 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8354 /// SDValue. 8355 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8356 SelectionDAG &DAG) const { 8357 const unsigned NumHalfWords = 8; 8358 const unsigned BytesInVector = NumHalfWords * 2; 8359 // Check that the shuffle is on half-words. 8360 if (!isNByteElemShuffleMask(N, 2, 1)) 8361 return SDValue(); 8362 8363 bool IsLE = Subtarget.isLittleEndian(); 8364 SDLoc dl(N); 8365 SDValue V1 = N->getOperand(0); 8366 SDValue V2 = N->getOperand(1); 8367 unsigned ShiftElts = 0, InsertAtByte = 0; 8368 bool Swap = false; 8369 8370 // Shifts required to get the half-word we want at element 3. 8371 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8372 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8373 8374 uint32_t Mask = 0; 8375 uint32_t OriginalOrderLow = 0x1234567; 8376 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8377 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8378 // 32-bit space, only need 4-bit nibbles per element. 8379 for (unsigned i = 0; i < NumHalfWords; ++i) { 8380 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8381 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8382 } 8383 8384 // For each mask element, find out if we're just inserting something 8385 // from V2 into V1 or vice versa. Possible permutations inserting an element 8386 // from V2 into V1: 8387 // X, 1, 2, 3, 4, 5, 6, 7 8388 // 0, X, 2, 3, 4, 5, 6, 7 8389 // 0, 1, X, 3, 4, 5, 6, 7 8390 // 0, 1, 2, X, 4, 5, 6, 7 8391 // 0, 1, 2, 3, X, 5, 6, 7 8392 // 0, 1, 2, 3, 4, X, 6, 7 8393 // 0, 1, 2, 3, 4, 5, X, 7 8394 // 0, 1, 2, 3, 4, 5, 6, X 8395 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8396 8397 bool FoundCandidate = false; 8398 // Go through the mask of half-words to find an element that's being moved 8399 // from one vector to the other. 8400 for (unsigned i = 0; i < NumHalfWords; ++i) { 8401 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8402 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8403 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8404 uint32_t TargetOrder = 0x0; 8405 8406 // If both vector operands for the shuffle are the same vector, the mask 8407 // will contain only elements from the first one and the second one will be 8408 // undef. 8409 if (V2.isUndef()) { 8410 ShiftElts = 0; 8411 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8412 TargetOrder = OriginalOrderLow; 8413 Swap = false; 8414 // Skip if not the correct element or mask of other elements don't equal 8415 // to our expected order. 8416 if (MaskOneElt == VINSERTHSrcElem && 8417 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8418 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8419 FoundCandidate = true; 8420 break; 8421 } 8422 } else { // If both operands are defined. 8423 // Target order is [8,15] if the current mask is between [0,7]. 8424 TargetOrder = 8425 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8426 // Skip if mask of other elements don't equal our expected order. 8427 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8428 // We only need the last 3 bits for the number of shifts. 8429 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8430 : BigEndianShifts[MaskOneElt & 0x7]; 8431 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8432 Swap = MaskOneElt < NumHalfWords; 8433 FoundCandidate = true; 8434 break; 8435 } 8436 } 8437 } 8438 8439 if (!FoundCandidate) 8440 return SDValue(); 8441 8442 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8443 // optionally with VECSHL if shift is required. 8444 if (Swap) 8445 std::swap(V1, V2); 8446 if (V2.isUndef()) 8447 V2 = V1; 8448 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8449 if (ShiftElts) { 8450 // Double ShiftElts because we're left shifting on v16i8 type. 8451 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8452 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8453 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8454 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8455 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8456 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8457 } 8458 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8459 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8460 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8461 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8462 } 8463 8464 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8465 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8466 /// return the code it can be lowered into. Worst case, it can always be 8467 /// lowered into a vperm. 8468 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8469 SelectionDAG &DAG) const { 8470 SDLoc dl(Op); 8471 SDValue V1 = Op.getOperand(0); 8472 SDValue V2 = Op.getOperand(1); 8473 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8474 EVT VT = Op.getValueType(); 8475 bool isLittleEndian = Subtarget.isLittleEndian(); 8476 8477 unsigned ShiftElts, InsertAtByte; 8478 bool Swap = false; 8479 if (Subtarget.hasP9Vector() && 8480 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8481 isLittleEndian)) { 8482 if (Swap) 8483 std::swap(V1, V2); 8484 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8485 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8486 if (ShiftElts) { 8487 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8488 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8489 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8490 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8491 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8492 } 8493 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8494 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8495 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8496 } 8497 8498 if (Subtarget.hasP9Altivec()) { 8499 SDValue NewISDNode; 8500 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8501 return NewISDNode; 8502 8503 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8504 return NewISDNode; 8505 } 8506 8507 if (Subtarget.hasVSX() && 8508 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8509 if (Swap) 8510 std::swap(V1, V2); 8511 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8512 SDValue Conv2 = 8513 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8514 8515 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8516 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8517 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8518 } 8519 8520 if (Subtarget.hasVSX() && 8521 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8522 if (Swap) 8523 std::swap(V1, V2); 8524 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8525 SDValue Conv2 = 8526 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8527 8528 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8529 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8530 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8531 } 8532 8533 if (Subtarget.hasP9Vector()) { 8534 if (PPC::isXXBRHShuffleMask(SVOp)) { 8535 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8536 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8537 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8538 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8539 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8540 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8541 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8542 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8543 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8544 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8545 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8546 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8547 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8548 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8549 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8550 } 8551 } 8552 8553 if (Subtarget.hasVSX()) { 8554 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8555 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8556 8557 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8558 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8559 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8560 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8561 } 8562 8563 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8564 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8565 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8566 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8567 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8568 } 8569 } 8570 8571 if (Subtarget.hasQPX()) { 8572 if (VT.getVectorNumElements() != 4) 8573 return SDValue(); 8574 8575 if (V2.isUndef()) V2 = V1; 8576 8577 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8578 if (AlignIdx != -1) { 8579 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8580 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8581 } else if (SVOp->isSplat()) { 8582 int SplatIdx = SVOp->getSplatIndex(); 8583 if (SplatIdx >= 4) { 8584 std::swap(V1, V2); 8585 SplatIdx -= 4; 8586 } 8587 8588 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8589 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8590 } 8591 8592 // Lower this into a qvgpci/qvfperm pair. 8593 8594 // Compute the qvgpci literal 8595 unsigned idx = 0; 8596 for (unsigned i = 0; i < 4; ++i) { 8597 int m = SVOp->getMaskElt(i); 8598 unsigned mm = m >= 0 ? (unsigned) m : i; 8599 idx |= mm << (3-i)*3; 8600 } 8601 8602 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8603 DAG.getConstant(idx, dl, MVT::i32)); 8604 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8605 } 8606 8607 // Cases that are handled by instructions that take permute immediates 8608 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8609 // selected by the instruction selector. 8610 if (V2.isUndef()) { 8611 if (PPC::isSplatShuffleMask(SVOp, 1) || 8612 PPC::isSplatShuffleMask(SVOp, 2) || 8613 PPC::isSplatShuffleMask(SVOp, 4) || 8614 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8615 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8616 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8617 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8618 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8619 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8620 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8621 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8622 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8623 (Subtarget.hasP8Altivec() && ( 8624 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8625 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8626 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8627 return Op; 8628 } 8629 } 8630 8631 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8632 // and produce a fixed permutation. If any of these match, do not lower to 8633 // VPERM. 8634 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8635 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8636 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8637 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8638 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8639 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8640 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8641 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8642 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8643 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8644 (Subtarget.hasP8Altivec() && ( 8645 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8646 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8647 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8648 return Op; 8649 8650 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8651 // perfect shuffle table to emit an optimal matching sequence. 8652 ArrayRef<int> PermMask = SVOp->getMask(); 8653 8654 unsigned PFIndexes[4]; 8655 bool isFourElementShuffle = true; 8656 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8657 unsigned EltNo = 8; // Start out undef. 8658 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8659 if (PermMask[i*4+j] < 0) 8660 continue; // Undef, ignore it. 8661 8662 unsigned ByteSource = PermMask[i*4+j]; 8663 if ((ByteSource & 3) != j) { 8664 isFourElementShuffle = false; 8665 break; 8666 } 8667 8668 if (EltNo == 8) { 8669 EltNo = ByteSource/4; 8670 } else if (EltNo != ByteSource/4) { 8671 isFourElementShuffle = false; 8672 break; 8673 } 8674 } 8675 PFIndexes[i] = EltNo; 8676 } 8677 8678 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8679 // perfect shuffle vector to determine if it is cost effective to do this as 8680 // discrete instructions, or whether we should use a vperm. 8681 // For now, we skip this for little endian until such time as we have a 8682 // little-endian perfect shuffle table. 8683 if (isFourElementShuffle && !isLittleEndian) { 8684 // Compute the index in the perfect shuffle table. 8685 unsigned PFTableIndex = 8686 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8687 8688 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8689 unsigned Cost = (PFEntry >> 30); 8690 8691 // Determining when to avoid vperm is tricky. Many things affect the cost 8692 // of vperm, particularly how many times the perm mask needs to be computed. 8693 // For example, if the perm mask can be hoisted out of a loop or is already 8694 // used (perhaps because there are multiple permutes with the same shuffle 8695 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8696 // the loop requires an extra register. 8697 // 8698 // As a compromise, we only emit discrete instructions if the shuffle can be 8699 // generated in 3 or fewer operations. When we have loop information 8700 // available, if this block is within a loop, we should avoid using vperm 8701 // for 3-operation perms and use a constant pool load instead. 8702 if (Cost < 3) 8703 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8704 } 8705 8706 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8707 // vector that will get spilled to the constant pool. 8708 if (V2.isUndef()) V2 = V1; 8709 8710 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8711 // that it is in input element units, not in bytes. Convert now. 8712 8713 // For little endian, the order of the input vectors is reversed, and 8714 // the permutation mask is complemented with respect to 31. This is 8715 // necessary to produce proper semantics with the big-endian-biased vperm 8716 // instruction. 8717 EVT EltVT = V1.getValueType().getVectorElementType(); 8718 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8719 8720 SmallVector<SDValue, 16> ResultMask; 8721 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8722 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8723 8724 for (unsigned j = 0; j != BytesPerElement; ++j) 8725 if (isLittleEndian) 8726 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8727 dl, MVT::i32)); 8728 else 8729 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8730 MVT::i32)); 8731 } 8732 8733 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8734 if (isLittleEndian) 8735 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8736 V2, V1, VPermMask); 8737 else 8738 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8739 V1, V2, VPermMask); 8740 } 8741 8742 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8743 /// vector comparison. If it is, return true and fill in Opc/isDot with 8744 /// information about the intrinsic. 8745 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8746 bool &isDot, const PPCSubtarget &Subtarget) { 8747 unsigned IntrinsicID = 8748 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8749 CompareOpc = -1; 8750 isDot = false; 8751 switch (IntrinsicID) { 8752 default: 8753 return false; 8754 // Comparison predicates. 8755 case Intrinsic::ppc_altivec_vcmpbfp_p: 8756 CompareOpc = 966; 8757 isDot = true; 8758 break; 8759 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8760 CompareOpc = 198; 8761 isDot = true; 8762 break; 8763 case Intrinsic::ppc_altivec_vcmpequb_p: 8764 CompareOpc = 6; 8765 isDot = true; 8766 break; 8767 case Intrinsic::ppc_altivec_vcmpequh_p: 8768 CompareOpc = 70; 8769 isDot = true; 8770 break; 8771 case Intrinsic::ppc_altivec_vcmpequw_p: 8772 CompareOpc = 134; 8773 isDot = true; 8774 break; 8775 case Intrinsic::ppc_altivec_vcmpequd_p: 8776 if (Subtarget.hasP8Altivec()) { 8777 CompareOpc = 199; 8778 isDot = true; 8779 } else 8780 return false; 8781 break; 8782 case Intrinsic::ppc_altivec_vcmpneb_p: 8783 case Intrinsic::ppc_altivec_vcmpneh_p: 8784 case Intrinsic::ppc_altivec_vcmpnew_p: 8785 case Intrinsic::ppc_altivec_vcmpnezb_p: 8786 case Intrinsic::ppc_altivec_vcmpnezh_p: 8787 case Intrinsic::ppc_altivec_vcmpnezw_p: 8788 if (Subtarget.hasP9Altivec()) { 8789 switch (IntrinsicID) { 8790 default: 8791 llvm_unreachable("Unknown comparison intrinsic."); 8792 case Intrinsic::ppc_altivec_vcmpneb_p: 8793 CompareOpc = 7; 8794 break; 8795 case Intrinsic::ppc_altivec_vcmpneh_p: 8796 CompareOpc = 71; 8797 break; 8798 case Intrinsic::ppc_altivec_vcmpnew_p: 8799 CompareOpc = 135; 8800 break; 8801 case Intrinsic::ppc_altivec_vcmpnezb_p: 8802 CompareOpc = 263; 8803 break; 8804 case Intrinsic::ppc_altivec_vcmpnezh_p: 8805 CompareOpc = 327; 8806 break; 8807 case Intrinsic::ppc_altivec_vcmpnezw_p: 8808 CompareOpc = 391; 8809 break; 8810 } 8811 isDot = true; 8812 } else 8813 return false; 8814 break; 8815 case Intrinsic::ppc_altivec_vcmpgefp_p: 8816 CompareOpc = 454; 8817 isDot = true; 8818 break; 8819 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8820 CompareOpc = 710; 8821 isDot = true; 8822 break; 8823 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8824 CompareOpc = 774; 8825 isDot = true; 8826 break; 8827 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8828 CompareOpc = 838; 8829 isDot = true; 8830 break; 8831 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8832 CompareOpc = 902; 8833 isDot = true; 8834 break; 8835 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8836 if (Subtarget.hasP8Altivec()) { 8837 CompareOpc = 967; 8838 isDot = true; 8839 } else 8840 return false; 8841 break; 8842 case Intrinsic::ppc_altivec_vcmpgtub_p: 8843 CompareOpc = 518; 8844 isDot = true; 8845 break; 8846 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8847 CompareOpc = 582; 8848 isDot = true; 8849 break; 8850 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8851 CompareOpc = 646; 8852 isDot = true; 8853 break; 8854 case Intrinsic::ppc_altivec_vcmpgtud_p: 8855 if (Subtarget.hasP8Altivec()) { 8856 CompareOpc = 711; 8857 isDot = true; 8858 } else 8859 return false; 8860 break; 8861 8862 // VSX predicate comparisons use the same infrastructure 8863 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8864 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8865 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8866 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8867 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8868 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8869 if (Subtarget.hasVSX()) { 8870 switch (IntrinsicID) { 8871 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8872 CompareOpc = 99; 8873 break; 8874 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8875 CompareOpc = 115; 8876 break; 8877 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8878 CompareOpc = 107; 8879 break; 8880 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8881 CompareOpc = 67; 8882 break; 8883 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8884 CompareOpc = 83; 8885 break; 8886 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8887 CompareOpc = 75; 8888 break; 8889 } 8890 isDot = true; 8891 } else 8892 return false; 8893 break; 8894 8895 // Normal Comparisons. 8896 case Intrinsic::ppc_altivec_vcmpbfp: 8897 CompareOpc = 966; 8898 break; 8899 case Intrinsic::ppc_altivec_vcmpeqfp: 8900 CompareOpc = 198; 8901 break; 8902 case Intrinsic::ppc_altivec_vcmpequb: 8903 CompareOpc = 6; 8904 break; 8905 case Intrinsic::ppc_altivec_vcmpequh: 8906 CompareOpc = 70; 8907 break; 8908 case Intrinsic::ppc_altivec_vcmpequw: 8909 CompareOpc = 134; 8910 break; 8911 case Intrinsic::ppc_altivec_vcmpequd: 8912 if (Subtarget.hasP8Altivec()) 8913 CompareOpc = 199; 8914 else 8915 return false; 8916 break; 8917 case Intrinsic::ppc_altivec_vcmpneb: 8918 case Intrinsic::ppc_altivec_vcmpneh: 8919 case Intrinsic::ppc_altivec_vcmpnew: 8920 case Intrinsic::ppc_altivec_vcmpnezb: 8921 case Intrinsic::ppc_altivec_vcmpnezh: 8922 case Intrinsic::ppc_altivec_vcmpnezw: 8923 if (Subtarget.hasP9Altivec()) 8924 switch (IntrinsicID) { 8925 default: 8926 llvm_unreachable("Unknown comparison intrinsic."); 8927 case Intrinsic::ppc_altivec_vcmpneb: 8928 CompareOpc = 7; 8929 break; 8930 case Intrinsic::ppc_altivec_vcmpneh: 8931 CompareOpc = 71; 8932 break; 8933 case Intrinsic::ppc_altivec_vcmpnew: 8934 CompareOpc = 135; 8935 break; 8936 case Intrinsic::ppc_altivec_vcmpnezb: 8937 CompareOpc = 263; 8938 break; 8939 case Intrinsic::ppc_altivec_vcmpnezh: 8940 CompareOpc = 327; 8941 break; 8942 case Intrinsic::ppc_altivec_vcmpnezw: 8943 CompareOpc = 391; 8944 break; 8945 } 8946 else 8947 return false; 8948 break; 8949 case Intrinsic::ppc_altivec_vcmpgefp: 8950 CompareOpc = 454; 8951 break; 8952 case Intrinsic::ppc_altivec_vcmpgtfp: 8953 CompareOpc = 710; 8954 break; 8955 case Intrinsic::ppc_altivec_vcmpgtsb: 8956 CompareOpc = 774; 8957 break; 8958 case Intrinsic::ppc_altivec_vcmpgtsh: 8959 CompareOpc = 838; 8960 break; 8961 case Intrinsic::ppc_altivec_vcmpgtsw: 8962 CompareOpc = 902; 8963 break; 8964 case Intrinsic::ppc_altivec_vcmpgtsd: 8965 if (Subtarget.hasP8Altivec()) 8966 CompareOpc = 967; 8967 else 8968 return false; 8969 break; 8970 case Intrinsic::ppc_altivec_vcmpgtub: 8971 CompareOpc = 518; 8972 break; 8973 case Intrinsic::ppc_altivec_vcmpgtuh: 8974 CompareOpc = 582; 8975 break; 8976 case Intrinsic::ppc_altivec_vcmpgtuw: 8977 CompareOpc = 646; 8978 break; 8979 case Intrinsic::ppc_altivec_vcmpgtud: 8980 if (Subtarget.hasP8Altivec()) 8981 CompareOpc = 711; 8982 else 8983 return false; 8984 break; 8985 } 8986 return true; 8987 } 8988 8989 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8990 /// lower, do it, otherwise return null. 8991 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8992 SelectionDAG &DAG) const { 8993 unsigned IntrinsicID = 8994 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8995 8996 SDLoc dl(Op); 8997 8998 if (IntrinsicID == Intrinsic::thread_pointer) { 8999 // Reads the thread pointer register, used for __builtin_thread_pointer. 9000 if (Subtarget.isPPC64()) 9001 return DAG.getRegister(PPC::X13, MVT::i64); 9002 return DAG.getRegister(PPC::R2, MVT::i32); 9003 } 9004 9005 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9006 // opcode number of the comparison. 9007 int CompareOpc; 9008 bool isDot; 9009 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9010 return SDValue(); // Don't custom lower most intrinsics. 9011 9012 // If this is a non-dot comparison, make the VCMP node and we are done. 9013 if (!isDot) { 9014 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9015 Op.getOperand(1), Op.getOperand(2), 9016 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9017 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9018 } 9019 9020 // Create the PPCISD altivec 'dot' comparison node. 9021 SDValue Ops[] = { 9022 Op.getOperand(2), // LHS 9023 Op.getOperand(3), // RHS 9024 DAG.getConstant(CompareOpc, dl, MVT::i32) 9025 }; 9026 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9027 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9028 9029 // Now that we have the comparison, emit a copy from the CR to a GPR. 9030 // This is flagged to the above dot comparison. 9031 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9032 DAG.getRegister(PPC::CR6, MVT::i32), 9033 CompNode.getValue(1)); 9034 9035 // Unpack the result based on how the target uses it. 9036 unsigned BitNo; // Bit # of CR6. 9037 bool InvertBit; // Invert result? 9038 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9039 default: // Can't happen, don't crash on invalid number though. 9040 case 0: // Return the value of the EQ bit of CR6. 9041 BitNo = 0; InvertBit = false; 9042 break; 9043 case 1: // Return the inverted value of the EQ bit of CR6. 9044 BitNo = 0; InvertBit = true; 9045 break; 9046 case 2: // Return the value of the LT bit of CR6. 9047 BitNo = 2; InvertBit = false; 9048 break; 9049 case 3: // Return the inverted value of the LT bit of CR6. 9050 BitNo = 2; InvertBit = true; 9051 break; 9052 } 9053 9054 // Shift the bit into the low position. 9055 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9056 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9057 // Isolate the bit. 9058 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9059 DAG.getConstant(1, dl, MVT::i32)); 9060 9061 // If we are supposed to, toggle the bit. 9062 if (InvertBit) 9063 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9064 DAG.getConstant(1, dl, MVT::i32)); 9065 return Flags; 9066 } 9067 9068 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9069 SelectionDAG &DAG) const { 9070 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9071 // the beginning of the argument list. 9072 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9073 SDLoc DL(Op); 9074 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9075 case Intrinsic::ppc_cfence: { 9076 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9077 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9078 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9079 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9080 Op.getOperand(ArgStart + 1)), 9081 Op.getOperand(0)), 9082 0); 9083 } 9084 default: 9085 break; 9086 } 9087 return SDValue(); 9088 } 9089 9090 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9091 // Check for a DIV with the same operands as this REM. 9092 for (auto UI : Op.getOperand(1)->uses()) { 9093 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9094 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9095 if (UI->getOperand(0) == Op.getOperand(0) && 9096 UI->getOperand(1) == Op.getOperand(1)) 9097 return SDValue(); 9098 } 9099 return Op; 9100 } 9101 9102 // Lower scalar BSWAP64 to xxbrd. 9103 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9104 SDLoc dl(Op); 9105 // MTVSRDD 9106 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9107 Op.getOperand(0)); 9108 // XXBRD 9109 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9110 // MFVSRD 9111 int VectorIndex = 0; 9112 if (Subtarget.isLittleEndian()) 9113 VectorIndex = 1; 9114 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9115 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9116 return Op; 9117 } 9118 9119 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9120 // compared to a value that is atomically loaded (atomic loads zero-extend). 9121 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9122 SelectionDAG &DAG) const { 9123 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9124 "Expecting an atomic compare-and-swap here."); 9125 SDLoc dl(Op); 9126 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9127 EVT MemVT = AtomicNode->getMemoryVT(); 9128 if (MemVT.getSizeInBits() >= 32) 9129 return Op; 9130 9131 SDValue CmpOp = Op.getOperand(2); 9132 // If this is already correctly zero-extended, leave it alone. 9133 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9134 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9135 return Op; 9136 9137 // Clear the high bits of the compare operand. 9138 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9139 SDValue NewCmpOp = 9140 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9141 DAG.getConstant(MaskVal, dl, MVT::i32)); 9142 9143 // Replace the existing compare operand with the properly zero-extended one. 9144 SmallVector<SDValue, 4> Ops; 9145 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9146 Ops.push_back(AtomicNode->getOperand(i)); 9147 Ops[2] = NewCmpOp; 9148 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9149 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9150 auto NodeTy = 9151 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9152 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9153 } 9154 9155 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9156 SelectionDAG &DAG) const { 9157 SDLoc dl(Op); 9158 // Create a stack slot that is 16-byte aligned. 9159 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9160 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9161 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9162 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9163 9164 // Store the input value into Value#0 of the stack slot. 9165 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9166 MachinePointerInfo()); 9167 // Load it out. 9168 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9169 } 9170 9171 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9172 SelectionDAG &DAG) const { 9173 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9174 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9175 9176 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9177 // We have legal lowering for constant indices but not for variable ones. 9178 if (!C) 9179 return SDValue(); 9180 9181 EVT VT = Op.getValueType(); 9182 SDLoc dl(Op); 9183 SDValue V1 = Op.getOperand(0); 9184 SDValue V2 = Op.getOperand(1); 9185 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9186 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9187 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9188 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9189 unsigned InsertAtElement = C->getZExtValue(); 9190 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9191 if (Subtarget.isLittleEndian()) { 9192 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9193 } 9194 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9195 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9196 } 9197 return Op; 9198 } 9199 9200 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9201 SelectionDAG &DAG) const { 9202 SDLoc dl(Op); 9203 SDNode *N = Op.getNode(); 9204 9205 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9206 "Unknown extract_vector_elt type"); 9207 9208 SDValue Value = N->getOperand(0); 9209 9210 // The first part of this is like the store lowering except that we don't 9211 // need to track the chain. 9212 9213 // The values are now known to be -1 (false) or 1 (true). To convert this 9214 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9215 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9216 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9217 9218 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9219 // understand how to form the extending load. 9220 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9221 9222 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9223 9224 // Now convert to an integer and store. 9225 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9226 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9227 Value); 9228 9229 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9230 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9231 MachinePointerInfo PtrInfo = 9232 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9233 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9234 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9235 9236 SDValue StoreChain = DAG.getEntryNode(); 9237 SDValue Ops[] = {StoreChain, 9238 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9239 Value, FIdx}; 9240 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9241 9242 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9243 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9244 9245 // Extract the value requested. 9246 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9247 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9248 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9249 9250 SDValue IntVal = 9251 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9252 9253 if (!Subtarget.useCRBits()) 9254 return IntVal; 9255 9256 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9257 } 9258 9259 /// Lowering for QPX v4i1 loads 9260 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9261 SelectionDAG &DAG) const { 9262 SDLoc dl(Op); 9263 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9264 SDValue LoadChain = LN->getChain(); 9265 SDValue BasePtr = LN->getBasePtr(); 9266 9267 if (Op.getValueType() == MVT::v4f64 || 9268 Op.getValueType() == MVT::v4f32) { 9269 EVT MemVT = LN->getMemoryVT(); 9270 unsigned Alignment = LN->getAlignment(); 9271 9272 // If this load is properly aligned, then it is legal. 9273 if (Alignment >= MemVT.getStoreSize()) 9274 return Op; 9275 9276 EVT ScalarVT = Op.getValueType().getScalarType(), 9277 ScalarMemVT = MemVT.getScalarType(); 9278 unsigned Stride = ScalarMemVT.getStoreSize(); 9279 9280 SDValue Vals[4], LoadChains[4]; 9281 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9282 SDValue Load; 9283 if (ScalarVT != ScalarMemVT) 9284 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9285 BasePtr, 9286 LN->getPointerInfo().getWithOffset(Idx * Stride), 9287 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9288 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9289 else 9290 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9291 LN->getPointerInfo().getWithOffset(Idx * Stride), 9292 MinAlign(Alignment, Idx * Stride), 9293 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9294 9295 if (Idx == 0 && LN->isIndexed()) { 9296 assert(LN->getAddressingMode() == ISD::PRE_INC && 9297 "Unknown addressing mode on vector load"); 9298 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9299 LN->getAddressingMode()); 9300 } 9301 9302 Vals[Idx] = Load; 9303 LoadChains[Idx] = Load.getValue(1); 9304 9305 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9306 DAG.getConstant(Stride, dl, 9307 BasePtr.getValueType())); 9308 } 9309 9310 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9311 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9312 9313 if (LN->isIndexed()) { 9314 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9315 return DAG.getMergeValues(RetOps, dl); 9316 } 9317 9318 SDValue RetOps[] = { Value, TF }; 9319 return DAG.getMergeValues(RetOps, dl); 9320 } 9321 9322 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9323 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9324 9325 // To lower v4i1 from a byte array, we load the byte elements of the 9326 // vector and then reuse the BUILD_VECTOR logic. 9327 9328 SDValue VectElmts[4], VectElmtChains[4]; 9329 for (unsigned i = 0; i < 4; ++i) { 9330 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9331 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9332 9333 VectElmts[i] = DAG.getExtLoad( 9334 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9335 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9336 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9337 VectElmtChains[i] = VectElmts[i].getValue(1); 9338 } 9339 9340 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9341 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9342 9343 SDValue RVals[] = { Value, LoadChain }; 9344 return DAG.getMergeValues(RVals, dl); 9345 } 9346 9347 /// Lowering for QPX v4i1 stores 9348 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9349 SelectionDAG &DAG) const { 9350 SDLoc dl(Op); 9351 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9352 SDValue StoreChain = SN->getChain(); 9353 SDValue BasePtr = SN->getBasePtr(); 9354 SDValue Value = SN->getValue(); 9355 9356 if (Value.getValueType() == MVT::v4f64 || 9357 Value.getValueType() == MVT::v4f32) { 9358 EVT MemVT = SN->getMemoryVT(); 9359 unsigned Alignment = SN->getAlignment(); 9360 9361 // If this store is properly aligned, then it is legal. 9362 if (Alignment >= MemVT.getStoreSize()) 9363 return Op; 9364 9365 EVT ScalarVT = Value.getValueType().getScalarType(), 9366 ScalarMemVT = MemVT.getScalarType(); 9367 unsigned Stride = ScalarMemVT.getStoreSize(); 9368 9369 SDValue Stores[4]; 9370 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9371 SDValue Ex = DAG.getNode( 9372 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9373 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9374 SDValue Store; 9375 if (ScalarVT != ScalarMemVT) 9376 Store = 9377 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9378 SN->getPointerInfo().getWithOffset(Idx * Stride), 9379 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9380 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9381 else 9382 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9383 SN->getPointerInfo().getWithOffset(Idx * Stride), 9384 MinAlign(Alignment, Idx * Stride), 9385 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9386 9387 if (Idx == 0 && SN->isIndexed()) { 9388 assert(SN->getAddressingMode() == ISD::PRE_INC && 9389 "Unknown addressing mode on vector store"); 9390 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9391 SN->getAddressingMode()); 9392 } 9393 9394 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9395 DAG.getConstant(Stride, dl, 9396 BasePtr.getValueType())); 9397 Stores[Idx] = Store; 9398 } 9399 9400 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9401 9402 if (SN->isIndexed()) { 9403 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9404 return DAG.getMergeValues(RetOps, dl); 9405 } 9406 9407 return TF; 9408 } 9409 9410 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9411 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9412 9413 // The values are now known to be -1 (false) or 1 (true). To convert this 9414 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9415 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9416 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9417 9418 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9419 // understand how to form the extending load. 9420 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9421 9422 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9423 9424 // Now convert to an integer and store. 9425 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9426 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9427 Value); 9428 9429 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9430 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9431 MachinePointerInfo PtrInfo = 9432 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9433 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9434 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9435 9436 SDValue Ops[] = {StoreChain, 9437 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9438 Value, FIdx}; 9439 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9440 9441 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9442 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9443 9444 // Move data into the byte array. 9445 SDValue Loads[4], LoadChains[4]; 9446 for (unsigned i = 0; i < 4; ++i) { 9447 unsigned Offset = 4*i; 9448 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9449 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9450 9451 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9452 PtrInfo.getWithOffset(Offset)); 9453 LoadChains[i] = Loads[i].getValue(1); 9454 } 9455 9456 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9457 9458 SDValue Stores[4]; 9459 for (unsigned i = 0; i < 4; ++i) { 9460 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9461 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9462 9463 Stores[i] = DAG.getTruncStore( 9464 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9465 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9466 SN->getAAInfo()); 9467 } 9468 9469 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9470 9471 return StoreChain; 9472 } 9473 9474 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9475 SDLoc dl(Op); 9476 if (Op.getValueType() == MVT::v4i32) { 9477 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9478 9479 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9480 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9481 9482 SDValue RHSSwap = // = vrlw RHS, 16 9483 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9484 9485 // Shrinkify inputs to v8i16. 9486 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9487 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9488 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9489 9490 // Low parts multiplied together, generating 32-bit results (we ignore the 9491 // top parts). 9492 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9493 LHS, RHS, DAG, dl, MVT::v4i32); 9494 9495 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9496 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9497 // Shift the high parts up 16 bits. 9498 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9499 Neg16, DAG, dl); 9500 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9501 } else if (Op.getValueType() == MVT::v8i16) { 9502 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9503 9504 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9505 9506 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9507 LHS, RHS, Zero, DAG, dl); 9508 } else if (Op.getValueType() == MVT::v16i8) { 9509 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9510 bool isLittleEndian = Subtarget.isLittleEndian(); 9511 9512 // Multiply the even 8-bit parts, producing 16-bit sums. 9513 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9514 LHS, RHS, DAG, dl, MVT::v8i16); 9515 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9516 9517 // Multiply the odd 8-bit parts, producing 16-bit sums. 9518 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9519 LHS, RHS, DAG, dl, MVT::v8i16); 9520 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9521 9522 // Merge the results together. Because vmuleub and vmuloub are 9523 // instructions with a big-endian bias, we must reverse the 9524 // element numbering and reverse the meaning of "odd" and "even" 9525 // when generating little endian code. 9526 int Ops[16]; 9527 for (unsigned i = 0; i != 8; ++i) { 9528 if (isLittleEndian) { 9529 Ops[i*2 ] = 2*i; 9530 Ops[i*2+1] = 2*i+16; 9531 } else { 9532 Ops[i*2 ] = 2*i+1; 9533 Ops[i*2+1] = 2*i+1+16; 9534 } 9535 } 9536 if (isLittleEndian) 9537 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9538 else 9539 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9540 } else { 9541 llvm_unreachable("Unknown mul to lower!"); 9542 } 9543 } 9544 9545 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9546 9547 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9548 9549 EVT VT = Op.getValueType(); 9550 assert(VT.isVector() && 9551 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9552 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9553 VT == MVT::v16i8) && 9554 "Unexpected vector element type!"); 9555 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9556 "Current subtarget doesn't support smax v2i64!"); 9557 9558 // For vector abs, it can be lowered to: 9559 // abs x 9560 // ==> 9561 // y = -x 9562 // smax(x, y) 9563 9564 SDLoc dl(Op); 9565 SDValue X = Op.getOperand(0); 9566 SDValue Zero = DAG.getConstant(0, dl, VT); 9567 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9568 9569 // SMAX patch https://reviews.llvm.org/D47332 9570 // hasn't landed yet, so use intrinsic first here. 9571 // TODO: Should use SMAX directly once SMAX patch landed 9572 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9573 if (VT == MVT::v2i64) 9574 BifID = Intrinsic::ppc_altivec_vmaxsd; 9575 else if (VT == MVT::v8i16) 9576 BifID = Intrinsic::ppc_altivec_vmaxsh; 9577 else if (VT == MVT::v16i8) 9578 BifID = Intrinsic::ppc_altivec_vmaxsb; 9579 9580 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9581 } 9582 9583 /// LowerOperation - Provide custom lowering hooks for some operations. 9584 /// 9585 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9586 switch (Op.getOpcode()) { 9587 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9588 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9589 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9590 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9591 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9592 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9593 case ISD::SETCC: return LowerSETCC(Op, DAG); 9594 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9595 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9596 9597 // Variable argument lowering. 9598 case ISD::VASTART: return LowerVASTART(Op, DAG); 9599 case ISD::VAARG: return LowerVAARG(Op, DAG); 9600 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9601 9602 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9603 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9604 case ISD::GET_DYNAMIC_AREA_OFFSET: 9605 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9606 9607 // Exception handling lowering. 9608 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9609 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9610 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9611 9612 case ISD::LOAD: return LowerLOAD(Op, DAG); 9613 case ISD::STORE: return LowerSTORE(Op, DAG); 9614 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9615 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9616 case ISD::FP_TO_UINT: 9617 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9618 case ISD::UINT_TO_FP: 9619 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9620 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9621 9622 // Lower 64-bit shifts. 9623 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9624 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9625 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9626 9627 // Vector-related lowering. 9628 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9629 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9630 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9631 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9632 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9633 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9634 case ISD::MUL: return LowerMUL(Op, DAG); 9635 case ISD::ABS: return LowerABS(Op, DAG); 9636 9637 // For counter-based loop handling. 9638 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9639 9640 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9641 9642 // Frame & Return address. 9643 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9644 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9645 9646 case ISD::INTRINSIC_VOID: 9647 return LowerINTRINSIC_VOID(Op, DAG); 9648 case ISD::SREM: 9649 case ISD::UREM: 9650 return LowerREM(Op, DAG); 9651 case ISD::BSWAP: 9652 return LowerBSWAP(Op, DAG); 9653 case ISD::ATOMIC_CMP_SWAP: 9654 return LowerATOMIC_CMP_SWAP(Op, DAG); 9655 } 9656 } 9657 9658 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9659 SmallVectorImpl<SDValue>&Results, 9660 SelectionDAG &DAG) const { 9661 SDLoc dl(N); 9662 switch (N->getOpcode()) { 9663 default: 9664 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9665 case ISD::READCYCLECOUNTER: { 9666 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9667 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9668 9669 Results.push_back(RTB); 9670 Results.push_back(RTB.getValue(1)); 9671 Results.push_back(RTB.getValue(2)); 9672 break; 9673 } 9674 case ISD::INTRINSIC_W_CHAIN: { 9675 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9676 Intrinsic::ppc_is_decremented_ctr_nonzero) 9677 break; 9678 9679 assert(N->getValueType(0) == MVT::i1 && 9680 "Unexpected result type for CTR decrement intrinsic"); 9681 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9682 N->getValueType(0)); 9683 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9684 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9685 N->getOperand(1)); 9686 9687 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 9688 Results.push_back(NewInt.getValue(1)); 9689 break; 9690 } 9691 case ISD::VAARG: { 9692 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9693 return; 9694 9695 EVT VT = N->getValueType(0); 9696 9697 if (VT == MVT::i64) { 9698 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9699 9700 Results.push_back(NewNode); 9701 Results.push_back(NewNode.getValue(1)); 9702 } 9703 return; 9704 } 9705 case ISD::FP_TO_SINT: 9706 case ISD::FP_TO_UINT: 9707 // LowerFP_TO_INT() can only handle f32 and f64. 9708 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9709 return; 9710 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9711 return; 9712 case ISD::TRUNCATE: { 9713 EVT TrgVT = N->getValueType(0); 9714 if (TrgVT.isVector() && 9715 isOperationCustom(N->getOpcode(), TrgVT) && 9716 N->getOperand(0).getValueType().getSizeInBits() <= 128) 9717 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 9718 return; 9719 } 9720 case ISD::BITCAST: 9721 // Don't handle bitcast here. 9722 return; 9723 } 9724 } 9725 9726 //===----------------------------------------------------------------------===// 9727 // Other Lowering Code 9728 //===----------------------------------------------------------------------===// 9729 9730 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9731 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9732 Function *Func = Intrinsic::getDeclaration(M, Id); 9733 return Builder.CreateCall(Func, {}); 9734 } 9735 9736 // The mappings for emitLeading/TrailingFence is taken from 9737 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9738 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9739 Instruction *Inst, 9740 AtomicOrdering Ord) const { 9741 if (Ord == AtomicOrdering::SequentiallyConsistent) 9742 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9743 if (isReleaseOrStronger(Ord)) 9744 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9745 return nullptr; 9746 } 9747 9748 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9749 Instruction *Inst, 9750 AtomicOrdering Ord) const { 9751 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9752 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9753 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9754 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9755 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9756 return Builder.CreateCall( 9757 Intrinsic::getDeclaration( 9758 Builder.GetInsertBlock()->getParent()->getParent(), 9759 Intrinsic::ppc_cfence, {Inst->getType()}), 9760 {Inst}); 9761 // FIXME: Can use isync for rmw operation. 9762 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9763 } 9764 return nullptr; 9765 } 9766 9767 MachineBasicBlock * 9768 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9769 unsigned AtomicSize, 9770 unsigned BinOpcode, 9771 unsigned CmpOpcode, 9772 unsigned CmpPred) const { 9773 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9774 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9775 9776 auto LoadMnemonic = PPC::LDARX; 9777 auto StoreMnemonic = PPC::STDCX; 9778 switch (AtomicSize) { 9779 default: 9780 llvm_unreachable("Unexpected size of atomic entity"); 9781 case 1: 9782 LoadMnemonic = PPC::LBARX; 9783 StoreMnemonic = PPC::STBCX; 9784 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9785 break; 9786 case 2: 9787 LoadMnemonic = PPC::LHARX; 9788 StoreMnemonic = PPC::STHCX; 9789 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9790 break; 9791 case 4: 9792 LoadMnemonic = PPC::LWARX; 9793 StoreMnemonic = PPC::STWCX; 9794 break; 9795 case 8: 9796 LoadMnemonic = PPC::LDARX; 9797 StoreMnemonic = PPC::STDCX; 9798 break; 9799 } 9800 9801 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9802 MachineFunction *F = BB->getParent(); 9803 MachineFunction::iterator It = ++BB->getIterator(); 9804 9805 unsigned dest = MI.getOperand(0).getReg(); 9806 unsigned ptrA = MI.getOperand(1).getReg(); 9807 unsigned ptrB = MI.getOperand(2).getReg(); 9808 unsigned incr = MI.getOperand(3).getReg(); 9809 DebugLoc dl = MI.getDebugLoc(); 9810 9811 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9812 MachineBasicBlock *loop2MBB = 9813 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9814 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9815 F->insert(It, loopMBB); 9816 if (CmpOpcode) 9817 F->insert(It, loop2MBB); 9818 F->insert(It, exitMBB); 9819 exitMBB->splice(exitMBB->begin(), BB, 9820 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9821 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9822 9823 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9824 unsigned TmpReg = (!BinOpcode) ? incr : 9825 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9826 : &PPC::GPRCRegClass); 9827 9828 // thisMBB: 9829 // ... 9830 // fallthrough --> loopMBB 9831 BB->addSuccessor(loopMBB); 9832 9833 // loopMBB: 9834 // l[wd]arx dest, ptr 9835 // add r0, dest, incr 9836 // st[wd]cx. r0, ptr 9837 // bne- loopMBB 9838 // fallthrough --> exitMBB 9839 9840 // For max/min... 9841 // loopMBB: 9842 // l[wd]arx dest, ptr 9843 // cmpl?[wd] incr, dest 9844 // bgt exitMBB 9845 // loop2MBB: 9846 // st[wd]cx. dest, ptr 9847 // bne- loopMBB 9848 // fallthrough --> exitMBB 9849 9850 BB = loopMBB; 9851 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9852 .addReg(ptrA).addReg(ptrB); 9853 if (BinOpcode) 9854 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9855 if (CmpOpcode) { 9856 // Signed comparisons of byte or halfword values must be sign-extended. 9857 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9858 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9859 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9860 ExtReg).addReg(dest); 9861 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9862 .addReg(incr).addReg(ExtReg); 9863 } else 9864 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9865 .addReg(incr).addReg(dest); 9866 9867 BuildMI(BB, dl, TII->get(PPC::BCC)) 9868 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9869 BB->addSuccessor(loop2MBB); 9870 BB->addSuccessor(exitMBB); 9871 BB = loop2MBB; 9872 } 9873 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9874 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9875 BuildMI(BB, dl, TII->get(PPC::BCC)) 9876 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9877 BB->addSuccessor(loopMBB); 9878 BB->addSuccessor(exitMBB); 9879 9880 // exitMBB: 9881 // ... 9882 BB = exitMBB; 9883 return BB; 9884 } 9885 9886 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 9887 MachineInstr &MI, MachineBasicBlock *BB, 9888 bool is8bit, // operation 9889 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 9890 // If we support part-word atomic mnemonics, just use them 9891 if (Subtarget.hasPartwordAtomics()) 9892 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 9893 CmpPred); 9894 9895 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9896 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9897 // In 64 bit mode we have to use 64 bits for addresses, even though the 9898 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9899 // registers without caring whether they're 32 or 64, but here we're 9900 // doing actual arithmetic on the addresses. 9901 bool is64bit = Subtarget.isPPC64(); 9902 bool isLittleEndian = Subtarget.isLittleEndian(); 9903 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9904 9905 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9906 MachineFunction *F = BB->getParent(); 9907 MachineFunction::iterator It = ++BB->getIterator(); 9908 9909 unsigned dest = MI.getOperand(0).getReg(); 9910 unsigned ptrA = MI.getOperand(1).getReg(); 9911 unsigned ptrB = MI.getOperand(2).getReg(); 9912 unsigned incr = MI.getOperand(3).getReg(); 9913 DebugLoc dl = MI.getDebugLoc(); 9914 9915 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9916 MachineBasicBlock *loop2MBB = 9917 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9918 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9919 F->insert(It, loopMBB); 9920 if (CmpOpcode) 9921 F->insert(It, loop2MBB); 9922 F->insert(It, exitMBB); 9923 exitMBB->splice(exitMBB->begin(), BB, 9924 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9925 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9926 9927 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9928 const TargetRegisterClass *RC = 9929 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9930 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 9931 9932 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9933 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 9934 unsigned ShiftReg = 9935 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 9936 unsigned Incr2Reg = RegInfo.createVirtualRegister(GPRC); 9937 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 9938 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 9939 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 9940 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 9941 unsigned Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 9942 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 9943 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 9944 unsigned Ptr1Reg; 9945 unsigned TmpReg = 9946 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 9947 9948 // thisMBB: 9949 // ... 9950 // fallthrough --> loopMBB 9951 BB->addSuccessor(loopMBB); 9952 9953 // The 4-byte load must be aligned, while a char or short may be 9954 // anywhere in the word. Hence all this nasty bookkeeping code. 9955 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9956 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9957 // xori shift, shift1, 24 [16] 9958 // rlwinm ptr, ptr1, 0, 0, 29 9959 // slw incr2, incr, shift 9960 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9961 // slw mask, mask2, shift 9962 // loopMBB: 9963 // lwarx tmpDest, ptr 9964 // add tmp, tmpDest, incr2 9965 // andc tmp2, tmpDest, mask 9966 // and tmp3, tmp, mask 9967 // or tmp4, tmp3, tmp2 9968 // stwcx. tmp4, ptr 9969 // bne- loopMBB 9970 // fallthrough --> exitMBB 9971 // srw dest, tmpDest, shift 9972 if (ptrA != ZeroReg) { 9973 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9974 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9975 .addReg(ptrA) 9976 .addReg(ptrB); 9977 } else { 9978 Ptr1Reg = ptrB; 9979 } 9980 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 9981 // mode. 9982 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 9983 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 9984 .addImm(3) 9985 .addImm(27) 9986 .addImm(is8bit ? 28 : 27); 9987 if (!isLittleEndian) 9988 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 9989 .addReg(Shift1Reg) 9990 .addImm(is8bit ? 24 : 16); 9991 if (is64bit) 9992 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9993 .addReg(Ptr1Reg) 9994 .addImm(0) 9995 .addImm(61); 9996 else 9997 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9998 .addReg(Ptr1Reg) 9999 .addImm(0) 10000 .addImm(0) 10001 .addImm(29); 10002 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10003 if (is8bit) 10004 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10005 else { 10006 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10007 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10008 .addReg(Mask3Reg) 10009 .addImm(65535); 10010 } 10011 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10012 .addReg(Mask2Reg) 10013 .addReg(ShiftReg); 10014 10015 BB = loopMBB; 10016 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10017 .addReg(ZeroReg) 10018 .addReg(PtrReg); 10019 if (BinOpcode) 10020 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10021 .addReg(Incr2Reg) 10022 .addReg(TmpDestReg); 10023 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10024 .addReg(TmpDestReg) 10025 .addReg(MaskReg); 10026 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10027 if (CmpOpcode) { 10028 // For unsigned comparisons, we can directly compare the shifted values. 10029 // For signed comparisons we shift and sign extend. 10030 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10031 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10032 .addReg(TmpDestReg) 10033 .addReg(MaskReg); 10034 unsigned ValueReg = SReg; 10035 unsigned CmpReg = Incr2Reg; 10036 if (CmpOpcode == PPC::CMPW) { 10037 ValueReg = RegInfo.createVirtualRegister(GPRC); 10038 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10039 .addReg(SReg) 10040 .addReg(ShiftReg); 10041 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10042 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10043 .addReg(ValueReg); 10044 ValueReg = ValueSReg; 10045 CmpReg = incr; 10046 } 10047 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10048 .addReg(CmpReg) 10049 .addReg(ValueReg); 10050 BuildMI(BB, dl, TII->get(PPC::BCC)) 10051 .addImm(CmpPred) 10052 .addReg(PPC::CR0) 10053 .addMBB(exitMBB); 10054 BB->addSuccessor(loop2MBB); 10055 BB->addSuccessor(exitMBB); 10056 BB = loop2MBB; 10057 } 10058 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10059 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10060 .addReg(Tmp4Reg) 10061 .addReg(ZeroReg) 10062 .addReg(PtrReg); 10063 BuildMI(BB, dl, TII->get(PPC::BCC)) 10064 .addImm(PPC::PRED_NE) 10065 .addReg(PPC::CR0) 10066 .addMBB(loopMBB); 10067 BB->addSuccessor(loopMBB); 10068 BB->addSuccessor(exitMBB); 10069 10070 // exitMBB: 10071 // ... 10072 BB = exitMBB; 10073 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10074 .addReg(TmpDestReg) 10075 .addReg(ShiftReg); 10076 return BB; 10077 } 10078 10079 llvm::MachineBasicBlock * 10080 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10081 MachineBasicBlock *MBB) const { 10082 DebugLoc DL = MI.getDebugLoc(); 10083 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10084 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10085 10086 MachineFunction *MF = MBB->getParent(); 10087 MachineRegisterInfo &MRI = MF->getRegInfo(); 10088 10089 const BasicBlock *BB = MBB->getBasicBlock(); 10090 MachineFunction::iterator I = ++MBB->getIterator(); 10091 10092 unsigned DstReg = MI.getOperand(0).getReg(); 10093 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10094 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10095 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10096 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10097 10098 MVT PVT = getPointerTy(MF->getDataLayout()); 10099 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10100 "Invalid Pointer Size!"); 10101 // For v = setjmp(buf), we generate 10102 // 10103 // thisMBB: 10104 // SjLjSetup mainMBB 10105 // bl mainMBB 10106 // v_restore = 1 10107 // b sinkMBB 10108 // 10109 // mainMBB: 10110 // buf[LabelOffset] = LR 10111 // v_main = 0 10112 // 10113 // sinkMBB: 10114 // v = phi(main, restore) 10115 // 10116 10117 MachineBasicBlock *thisMBB = MBB; 10118 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10119 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10120 MF->insert(I, mainMBB); 10121 MF->insert(I, sinkMBB); 10122 10123 MachineInstrBuilder MIB; 10124 10125 // Transfer the remainder of BB and its successor edges to sinkMBB. 10126 sinkMBB->splice(sinkMBB->begin(), MBB, 10127 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10128 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10129 10130 // Note that the structure of the jmp_buf used here is not compatible 10131 // with that used by libc, and is not designed to be. Specifically, it 10132 // stores only those 'reserved' registers that LLVM does not otherwise 10133 // understand how to spill. Also, by convention, by the time this 10134 // intrinsic is called, Clang has already stored the frame address in the 10135 // first slot of the buffer and stack address in the third. Following the 10136 // X86 target code, we'll store the jump address in the second slot. We also 10137 // need to save the TOC pointer (R2) to handle jumps between shared 10138 // libraries, and that will be stored in the fourth slot. The thread 10139 // identifier (R13) is not affected. 10140 10141 // thisMBB: 10142 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10143 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10144 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10145 10146 // Prepare IP either in reg. 10147 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10148 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10149 unsigned BufReg = MI.getOperand(1).getReg(); 10150 10151 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10152 setUsesTOCBasePtr(*MBB->getParent()); 10153 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10154 .addReg(PPC::X2) 10155 .addImm(TOCOffset) 10156 .addReg(BufReg) 10157 .cloneMemRefs(MI); 10158 } 10159 10160 // Naked functions never have a base pointer, and so we use r1. For all 10161 // other functions, this decision must be delayed until during PEI. 10162 unsigned BaseReg; 10163 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10164 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10165 else 10166 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10167 10168 MIB = BuildMI(*thisMBB, MI, DL, 10169 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10170 .addReg(BaseReg) 10171 .addImm(BPOffset) 10172 .addReg(BufReg) 10173 .cloneMemRefs(MI); 10174 10175 // Setup 10176 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10177 MIB.addRegMask(TRI->getNoPreservedMask()); 10178 10179 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10180 10181 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10182 .addMBB(mainMBB); 10183 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10184 10185 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10186 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10187 10188 // mainMBB: 10189 // mainDstReg = 0 10190 MIB = 10191 BuildMI(mainMBB, DL, 10192 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10193 10194 // Store IP 10195 if (Subtarget.isPPC64()) { 10196 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10197 .addReg(LabelReg) 10198 .addImm(LabelOffset) 10199 .addReg(BufReg); 10200 } else { 10201 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10202 .addReg(LabelReg) 10203 .addImm(LabelOffset) 10204 .addReg(BufReg); 10205 } 10206 MIB.cloneMemRefs(MI); 10207 10208 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10209 mainMBB->addSuccessor(sinkMBB); 10210 10211 // sinkMBB: 10212 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10213 TII->get(PPC::PHI), DstReg) 10214 .addReg(mainDstReg).addMBB(mainMBB) 10215 .addReg(restoreDstReg).addMBB(thisMBB); 10216 10217 MI.eraseFromParent(); 10218 return sinkMBB; 10219 } 10220 10221 MachineBasicBlock * 10222 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10223 MachineBasicBlock *MBB) const { 10224 DebugLoc DL = MI.getDebugLoc(); 10225 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10226 10227 MachineFunction *MF = MBB->getParent(); 10228 MachineRegisterInfo &MRI = MF->getRegInfo(); 10229 10230 MVT PVT = getPointerTy(MF->getDataLayout()); 10231 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10232 "Invalid Pointer Size!"); 10233 10234 const TargetRegisterClass *RC = 10235 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10236 unsigned Tmp = MRI.createVirtualRegister(RC); 10237 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10238 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10239 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10240 unsigned BP = 10241 (PVT == MVT::i64) 10242 ? PPC::X30 10243 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10244 : PPC::R30); 10245 10246 MachineInstrBuilder MIB; 10247 10248 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10249 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10250 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10251 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10252 10253 unsigned BufReg = MI.getOperand(0).getReg(); 10254 10255 // Reload FP (the jumped-to function may not have had a 10256 // frame pointer, and if so, then its r31 will be restored 10257 // as necessary). 10258 if (PVT == MVT::i64) { 10259 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10260 .addImm(0) 10261 .addReg(BufReg); 10262 } else { 10263 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10264 .addImm(0) 10265 .addReg(BufReg); 10266 } 10267 MIB.cloneMemRefs(MI); 10268 10269 // Reload IP 10270 if (PVT == MVT::i64) { 10271 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10272 .addImm(LabelOffset) 10273 .addReg(BufReg); 10274 } else { 10275 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10276 .addImm(LabelOffset) 10277 .addReg(BufReg); 10278 } 10279 MIB.cloneMemRefs(MI); 10280 10281 // Reload SP 10282 if (PVT == MVT::i64) { 10283 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10284 .addImm(SPOffset) 10285 .addReg(BufReg); 10286 } else { 10287 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10288 .addImm(SPOffset) 10289 .addReg(BufReg); 10290 } 10291 MIB.cloneMemRefs(MI); 10292 10293 // Reload BP 10294 if (PVT == MVT::i64) { 10295 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10296 .addImm(BPOffset) 10297 .addReg(BufReg); 10298 } else { 10299 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10300 .addImm(BPOffset) 10301 .addReg(BufReg); 10302 } 10303 MIB.cloneMemRefs(MI); 10304 10305 // Reload TOC 10306 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10307 setUsesTOCBasePtr(*MBB->getParent()); 10308 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10309 .addImm(TOCOffset) 10310 .addReg(BufReg) 10311 .cloneMemRefs(MI); 10312 } 10313 10314 // Jump 10315 BuildMI(*MBB, MI, DL, 10316 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10317 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10318 10319 MI.eraseFromParent(); 10320 return MBB; 10321 } 10322 10323 MachineBasicBlock * 10324 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10325 MachineBasicBlock *BB) const { 10326 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10327 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10328 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10329 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10330 // Call lowering should have added an r2 operand to indicate a dependence 10331 // on the TOC base pointer value. It can't however, because there is no 10332 // way to mark the dependence as implicit there, and so the stackmap code 10333 // will confuse it with a regular operand. Instead, add the dependence 10334 // here. 10335 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10336 } 10337 10338 return emitPatchPoint(MI, BB); 10339 } 10340 10341 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10342 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10343 return emitEHSjLjSetJmp(MI, BB); 10344 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10345 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10346 return emitEHSjLjLongJmp(MI, BB); 10347 } 10348 10349 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10350 10351 // To "insert" these instructions we actually have to insert their 10352 // control-flow patterns. 10353 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10354 MachineFunction::iterator It = ++BB->getIterator(); 10355 10356 MachineFunction *F = BB->getParent(); 10357 10358 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10359 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10360 MI.getOpcode() == PPC::SELECT_I8) { 10361 SmallVector<MachineOperand, 2> Cond; 10362 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10363 MI.getOpcode() == PPC::SELECT_CC_I8) 10364 Cond.push_back(MI.getOperand(4)); 10365 else 10366 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10367 Cond.push_back(MI.getOperand(1)); 10368 10369 DebugLoc dl = MI.getDebugLoc(); 10370 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10371 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10372 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10373 MI.getOpcode() == PPC::SELECT_CC_I8 || 10374 MI.getOpcode() == PPC::SELECT_CC_F4 || 10375 MI.getOpcode() == PPC::SELECT_CC_F8 || 10376 MI.getOpcode() == PPC::SELECT_CC_F16 || 10377 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10378 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10379 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10380 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10381 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10382 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10383 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10384 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10385 MI.getOpcode() == PPC::SELECT_CC_SPE || 10386 MI.getOpcode() == PPC::SELECT_I4 || 10387 MI.getOpcode() == PPC::SELECT_I8 || 10388 MI.getOpcode() == PPC::SELECT_F4 || 10389 MI.getOpcode() == PPC::SELECT_F8 || 10390 MI.getOpcode() == PPC::SELECT_F16 || 10391 MI.getOpcode() == PPC::SELECT_QFRC || 10392 MI.getOpcode() == PPC::SELECT_QSRC || 10393 MI.getOpcode() == PPC::SELECT_QBRC || 10394 MI.getOpcode() == PPC::SELECT_SPE || 10395 MI.getOpcode() == PPC::SELECT_SPE4 || 10396 MI.getOpcode() == PPC::SELECT_VRRC || 10397 MI.getOpcode() == PPC::SELECT_VSFRC || 10398 MI.getOpcode() == PPC::SELECT_VSSRC || 10399 MI.getOpcode() == PPC::SELECT_VSRC) { 10400 // The incoming instruction knows the destination vreg to set, the 10401 // condition code register to branch on, the true/false values to 10402 // select between, and a branch opcode to use. 10403 10404 // thisMBB: 10405 // ... 10406 // TrueVal = ... 10407 // cmpTY ccX, r1, r2 10408 // bCC copy1MBB 10409 // fallthrough --> copy0MBB 10410 MachineBasicBlock *thisMBB = BB; 10411 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10412 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10413 DebugLoc dl = MI.getDebugLoc(); 10414 F->insert(It, copy0MBB); 10415 F->insert(It, sinkMBB); 10416 10417 // Transfer the remainder of BB and its successor edges to sinkMBB. 10418 sinkMBB->splice(sinkMBB->begin(), BB, 10419 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10420 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10421 10422 // Next, add the true and fallthrough blocks as its successors. 10423 BB->addSuccessor(copy0MBB); 10424 BB->addSuccessor(sinkMBB); 10425 10426 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10427 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10428 MI.getOpcode() == PPC::SELECT_F16 || 10429 MI.getOpcode() == PPC::SELECT_SPE4 || 10430 MI.getOpcode() == PPC::SELECT_SPE || 10431 MI.getOpcode() == PPC::SELECT_QFRC || 10432 MI.getOpcode() == PPC::SELECT_QSRC || 10433 MI.getOpcode() == PPC::SELECT_QBRC || 10434 MI.getOpcode() == PPC::SELECT_VRRC || 10435 MI.getOpcode() == PPC::SELECT_VSFRC || 10436 MI.getOpcode() == PPC::SELECT_VSSRC || 10437 MI.getOpcode() == PPC::SELECT_VSRC) { 10438 BuildMI(BB, dl, TII->get(PPC::BC)) 10439 .addReg(MI.getOperand(1).getReg()) 10440 .addMBB(sinkMBB); 10441 } else { 10442 unsigned SelectPred = MI.getOperand(4).getImm(); 10443 BuildMI(BB, dl, TII->get(PPC::BCC)) 10444 .addImm(SelectPred) 10445 .addReg(MI.getOperand(1).getReg()) 10446 .addMBB(sinkMBB); 10447 } 10448 10449 // copy0MBB: 10450 // %FalseValue = ... 10451 // # fallthrough to sinkMBB 10452 BB = copy0MBB; 10453 10454 // Update machine-CFG edges 10455 BB->addSuccessor(sinkMBB); 10456 10457 // sinkMBB: 10458 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10459 // ... 10460 BB = sinkMBB; 10461 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10462 .addReg(MI.getOperand(3).getReg()) 10463 .addMBB(copy0MBB) 10464 .addReg(MI.getOperand(2).getReg()) 10465 .addMBB(thisMBB); 10466 } else if (MI.getOpcode() == PPC::ReadTB) { 10467 // To read the 64-bit time-base register on a 32-bit target, we read the 10468 // two halves. Should the counter have wrapped while it was being read, we 10469 // need to try again. 10470 // ... 10471 // readLoop: 10472 // mfspr Rx,TBU # load from TBU 10473 // mfspr Ry,TB # load from TB 10474 // mfspr Rz,TBU # load from TBU 10475 // cmpw crX,Rx,Rz # check if 'old'='new' 10476 // bne readLoop # branch if they're not equal 10477 // ... 10478 10479 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10480 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10481 DebugLoc dl = MI.getDebugLoc(); 10482 F->insert(It, readMBB); 10483 F->insert(It, sinkMBB); 10484 10485 // Transfer the remainder of BB and its successor edges to sinkMBB. 10486 sinkMBB->splice(sinkMBB->begin(), BB, 10487 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10488 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10489 10490 BB->addSuccessor(readMBB); 10491 BB = readMBB; 10492 10493 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10494 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10495 unsigned LoReg = MI.getOperand(0).getReg(); 10496 unsigned HiReg = MI.getOperand(1).getReg(); 10497 10498 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10499 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10500 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10501 10502 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10503 10504 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10505 .addReg(HiReg) 10506 .addReg(ReadAgainReg); 10507 BuildMI(BB, dl, TII->get(PPC::BCC)) 10508 .addImm(PPC::PRED_NE) 10509 .addReg(CmpReg) 10510 .addMBB(readMBB); 10511 10512 BB->addSuccessor(readMBB); 10513 BB->addSuccessor(sinkMBB); 10514 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10515 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10516 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10517 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10518 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10519 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10520 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10521 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10522 10523 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10524 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10525 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10526 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10527 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10528 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10529 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10530 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10531 10532 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10533 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10534 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10535 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10536 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10537 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10538 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10539 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10540 10541 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10542 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10543 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10544 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10545 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10546 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10547 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10548 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10549 10550 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10551 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10552 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10553 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10555 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10556 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10557 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10558 10559 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10560 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10561 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10562 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10564 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10565 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10566 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10567 10568 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10569 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10570 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10571 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10573 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10574 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10575 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10576 10577 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10578 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10579 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10580 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10581 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10582 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10583 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10584 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10585 10586 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10587 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10588 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10589 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10590 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10591 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10592 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10593 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10594 10595 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10596 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10597 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10598 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10599 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10600 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10601 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10602 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10603 10604 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10605 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10606 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10607 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10608 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10609 BB = EmitAtomicBinary(MI, BB, 4, 0); 10610 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10611 BB = EmitAtomicBinary(MI, BB, 8, 0); 10612 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10613 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10614 (Subtarget.hasPartwordAtomics() && 10615 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10616 (Subtarget.hasPartwordAtomics() && 10617 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10618 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10619 10620 auto LoadMnemonic = PPC::LDARX; 10621 auto StoreMnemonic = PPC::STDCX; 10622 switch (MI.getOpcode()) { 10623 default: 10624 llvm_unreachable("Compare and swap of unknown size"); 10625 case PPC::ATOMIC_CMP_SWAP_I8: 10626 LoadMnemonic = PPC::LBARX; 10627 StoreMnemonic = PPC::STBCX; 10628 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10629 break; 10630 case PPC::ATOMIC_CMP_SWAP_I16: 10631 LoadMnemonic = PPC::LHARX; 10632 StoreMnemonic = PPC::STHCX; 10633 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10634 break; 10635 case PPC::ATOMIC_CMP_SWAP_I32: 10636 LoadMnemonic = PPC::LWARX; 10637 StoreMnemonic = PPC::STWCX; 10638 break; 10639 case PPC::ATOMIC_CMP_SWAP_I64: 10640 LoadMnemonic = PPC::LDARX; 10641 StoreMnemonic = PPC::STDCX; 10642 break; 10643 } 10644 unsigned dest = MI.getOperand(0).getReg(); 10645 unsigned ptrA = MI.getOperand(1).getReg(); 10646 unsigned ptrB = MI.getOperand(2).getReg(); 10647 unsigned oldval = MI.getOperand(3).getReg(); 10648 unsigned newval = MI.getOperand(4).getReg(); 10649 DebugLoc dl = MI.getDebugLoc(); 10650 10651 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10652 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10653 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10654 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10655 F->insert(It, loop1MBB); 10656 F->insert(It, loop2MBB); 10657 F->insert(It, midMBB); 10658 F->insert(It, exitMBB); 10659 exitMBB->splice(exitMBB->begin(), BB, 10660 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10661 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10662 10663 // thisMBB: 10664 // ... 10665 // fallthrough --> loopMBB 10666 BB->addSuccessor(loop1MBB); 10667 10668 // loop1MBB: 10669 // l[bhwd]arx dest, ptr 10670 // cmp[wd] dest, oldval 10671 // bne- midMBB 10672 // loop2MBB: 10673 // st[bhwd]cx. newval, ptr 10674 // bne- loopMBB 10675 // b exitBB 10676 // midMBB: 10677 // st[bhwd]cx. dest, ptr 10678 // exitBB: 10679 BB = loop1MBB; 10680 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 10681 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10682 .addReg(oldval) 10683 .addReg(dest); 10684 BuildMI(BB, dl, TII->get(PPC::BCC)) 10685 .addImm(PPC::PRED_NE) 10686 .addReg(PPC::CR0) 10687 .addMBB(midMBB); 10688 BB->addSuccessor(loop2MBB); 10689 BB->addSuccessor(midMBB); 10690 10691 BB = loop2MBB; 10692 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10693 .addReg(newval) 10694 .addReg(ptrA) 10695 .addReg(ptrB); 10696 BuildMI(BB, dl, TII->get(PPC::BCC)) 10697 .addImm(PPC::PRED_NE) 10698 .addReg(PPC::CR0) 10699 .addMBB(loop1MBB); 10700 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10701 BB->addSuccessor(loop1MBB); 10702 BB->addSuccessor(exitMBB); 10703 10704 BB = midMBB; 10705 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10706 .addReg(dest) 10707 .addReg(ptrA) 10708 .addReg(ptrB); 10709 BB->addSuccessor(exitMBB); 10710 10711 // exitMBB: 10712 // ... 10713 BB = exitMBB; 10714 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10715 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10716 // We must use 64-bit registers for addresses when targeting 64-bit, 10717 // since we're actually doing arithmetic on them. Other registers 10718 // can be 32-bit. 10719 bool is64bit = Subtarget.isPPC64(); 10720 bool isLittleEndian = Subtarget.isLittleEndian(); 10721 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10722 10723 unsigned dest = MI.getOperand(0).getReg(); 10724 unsigned ptrA = MI.getOperand(1).getReg(); 10725 unsigned ptrB = MI.getOperand(2).getReg(); 10726 unsigned oldval = MI.getOperand(3).getReg(); 10727 unsigned newval = MI.getOperand(4).getReg(); 10728 DebugLoc dl = MI.getDebugLoc(); 10729 10730 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10731 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10732 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10733 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10734 F->insert(It, loop1MBB); 10735 F->insert(It, loop2MBB); 10736 F->insert(It, midMBB); 10737 F->insert(It, exitMBB); 10738 exitMBB->splice(exitMBB->begin(), BB, 10739 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10740 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10741 10742 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10743 const TargetRegisterClass *RC = 10744 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10745 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10746 10747 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10748 unsigned Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10749 unsigned ShiftReg = 10750 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10751 unsigned NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 10752 unsigned NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 10753 unsigned OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 10754 unsigned OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 10755 unsigned MaskReg = RegInfo.createVirtualRegister(GPRC); 10756 unsigned Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10757 unsigned Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10758 unsigned Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10759 unsigned Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10760 unsigned TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10761 unsigned Ptr1Reg; 10762 unsigned TmpReg = RegInfo.createVirtualRegister(GPRC); 10763 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10764 // thisMBB: 10765 // ... 10766 // fallthrough --> loopMBB 10767 BB->addSuccessor(loop1MBB); 10768 10769 // The 4-byte load must be aligned, while a char or short may be 10770 // anywhere in the word. Hence all this nasty bookkeeping code. 10771 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10772 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10773 // xori shift, shift1, 24 [16] 10774 // rlwinm ptr, ptr1, 0, 0, 29 10775 // slw newval2, newval, shift 10776 // slw oldval2, oldval,shift 10777 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10778 // slw mask, mask2, shift 10779 // and newval3, newval2, mask 10780 // and oldval3, oldval2, mask 10781 // loop1MBB: 10782 // lwarx tmpDest, ptr 10783 // and tmp, tmpDest, mask 10784 // cmpw tmp, oldval3 10785 // bne- midMBB 10786 // loop2MBB: 10787 // andc tmp2, tmpDest, mask 10788 // or tmp4, tmp2, newval3 10789 // stwcx. tmp4, ptr 10790 // bne- loop1MBB 10791 // b exitBB 10792 // midMBB: 10793 // stwcx. tmpDest, ptr 10794 // exitBB: 10795 // srw dest, tmpDest, shift 10796 if (ptrA != ZeroReg) { 10797 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10798 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10799 .addReg(ptrA) 10800 .addReg(ptrB); 10801 } else { 10802 Ptr1Reg = ptrB; 10803 } 10804 10805 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10806 // mode. 10807 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10808 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10809 .addImm(3) 10810 .addImm(27) 10811 .addImm(is8bit ? 28 : 27); 10812 if (!isLittleEndian) 10813 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10814 .addReg(Shift1Reg) 10815 .addImm(is8bit ? 24 : 16); 10816 if (is64bit) 10817 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10818 .addReg(Ptr1Reg) 10819 .addImm(0) 10820 .addImm(61); 10821 else 10822 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10823 .addReg(Ptr1Reg) 10824 .addImm(0) 10825 .addImm(0) 10826 .addImm(29); 10827 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10828 .addReg(newval) 10829 .addReg(ShiftReg); 10830 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10831 .addReg(oldval) 10832 .addReg(ShiftReg); 10833 if (is8bit) 10834 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10835 else { 10836 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10837 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10838 .addReg(Mask3Reg) 10839 .addImm(65535); 10840 } 10841 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10842 .addReg(Mask2Reg) 10843 .addReg(ShiftReg); 10844 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10845 .addReg(NewVal2Reg) 10846 .addReg(MaskReg); 10847 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10848 .addReg(OldVal2Reg) 10849 .addReg(MaskReg); 10850 10851 BB = loop1MBB; 10852 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10853 .addReg(ZeroReg) 10854 .addReg(PtrReg); 10855 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 10856 .addReg(TmpDestReg) 10857 .addReg(MaskReg); 10858 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10859 .addReg(TmpReg) 10860 .addReg(OldVal3Reg); 10861 BuildMI(BB, dl, TII->get(PPC::BCC)) 10862 .addImm(PPC::PRED_NE) 10863 .addReg(PPC::CR0) 10864 .addMBB(midMBB); 10865 BB->addSuccessor(loop2MBB); 10866 BB->addSuccessor(midMBB); 10867 10868 BB = loop2MBB; 10869 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10870 .addReg(TmpDestReg) 10871 .addReg(MaskReg); 10872 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 10873 .addReg(Tmp2Reg) 10874 .addReg(NewVal3Reg); 10875 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10876 .addReg(Tmp4Reg) 10877 .addReg(ZeroReg) 10878 .addReg(PtrReg); 10879 BuildMI(BB, dl, TII->get(PPC::BCC)) 10880 .addImm(PPC::PRED_NE) 10881 .addReg(PPC::CR0) 10882 .addMBB(loop1MBB); 10883 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10884 BB->addSuccessor(loop1MBB); 10885 BB->addSuccessor(exitMBB); 10886 10887 BB = midMBB; 10888 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10889 .addReg(TmpDestReg) 10890 .addReg(ZeroReg) 10891 .addReg(PtrReg); 10892 BB->addSuccessor(exitMBB); 10893 10894 // exitMBB: 10895 // ... 10896 BB = exitMBB; 10897 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10898 .addReg(TmpReg) 10899 .addReg(ShiftReg); 10900 } else if (MI.getOpcode() == PPC::FADDrtz) { 10901 // This pseudo performs an FADD with rounding mode temporarily forced 10902 // to round-to-zero. We emit this via custom inserter since the FPSCR 10903 // is not modeled at the SelectionDAG level. 10904 unsigned Dest = MI.getOperand(0).getReg(); 10905 unsigned Src1 = MI.getOperand(1).getReg(); 10906 unsigned Src2 = MI.getOperand(2).getReg(); 10907 DebugLoc dl = MI.getDebugLoc(); 10908 10909 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10910 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10911 10912 // Save FPSCR value. 10913 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10914 10915 // Set rounding mode to round-to-zero. 10916 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10917 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10918 10919 // Perform addition. 10920 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10921 10922 // Restore FPSCR value. 10923 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10924 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10925 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10926 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10927 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10928 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10929 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10930 ? PPC::ANDIo8 10931 : PPC::ANDIo; 10932 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10933 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10934 10935 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10936 unsigned Dest = RegInfo.createVirtualRegister( 10937 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 10938 10939 DebugLoc dl = MI.getDebugLoc(); 10940 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10941 .addReg(MI.getOperand(1).getReg()) 10942 .addImm(1); 10943 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10944 MI.getOperand(0).getReg()) 10945 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10946 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10947 DebugLoc Dl = MI.getDebugLoc(); 10948 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10949 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10950 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10951 return BB; 10952 } else if (MI.getOpcode() == PPC::SETRNDi) { 10953 DebugLoc dl = MI.getDebugLoc(); 10954 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 10955 10956 // Save FPSCR value. 10957 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 10958 10959 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 10960 // the following settings: 10961 // 00 Round to nearest 10962 // 01 Round to 0 10963 // 10 Round to +inf 10964 // 11 Round to -inf 10965 10966 // When the operand is immediate, using the two least significant bits of 10967 // the immediate to set the bits 62:63 of FPSCR. 10968 unsigned Mode = MI.getOperand(1).getImm(); 10969 BuildMI(*BB, MI, dl, TII->get(Mode & 1 ? PPC::MTFSB1 : PPC::MTFSB0)) 10970 .addImm(31); 10971 10972 BuildMI(*BB, MI, dl, TII->get(Mode & 2 ? PPC::MTFSB1 : PPC::MTFSB0)) 10973 .addImm(30); 10974 } else if (MI.getOpcode() == PPC::SETRND) { 10975 DebugLoc dl = MI.getDebugLoc(); 10976 10977 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 10978 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 10979 // If the target doesn't have DirectMove, we should use stack to do the 10980 // conversion, because the target doesn't have the instructions like mtvsrd 10981 // or mfvsrd to do this conversion directly. 10982 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 10983 if (Subtarget.hasDirectMove()) { 10984 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 10985 .addReg(SrcReg); 10986 } else { 10987 // Use stack to do the register copy. 10988 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 10989 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10990 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 10991 if (RC == &PPC::F8RCRegClass) { 10992 // Copy register from F8RCRegClass to G8RCRegclass. 10993 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 10994 "Unsupported RegClass."); 10995 10996 StoreOp = PPC::STFD; 10997 LoadOp = PPC::LD; 10998 } else { 10999 // Copy register from G8RCRegClass to F8RCRegclass. 11000 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11001 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11002 "Unsupported RegClass."); 11003 } 11004 11005 MachineFrameInfo &MFI = F->getFrameInfo(); 11006 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11007 11008 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11009 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11010 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11011 MFI.getObjectAlignment(FrameIdx)); 11012 11013 // Store the SrcReg into the stack. 11014 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11015 .addReg(SrcReg) 11016 .addImm(0) 11017 .addFrameIndex(FrameIdx) 11018 .addMemOperand(MMOStore); 11019 11020 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11021 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11022 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11023 MFI.getObjectAlignment(FrameIdx)); 11024 11025 // Load from the stack where SrcReg is stored, and save to DestReg, 11026 // so we have done the RegClass conversion from RegClass::SrcReg to 11027 // RegClass::DestReg. 11028 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11029 .addImm(0) 11030 .addFrameIndex(FrameIdx) 11031 .addMemOperand(MMOLoad); 11032 } 11033 }; 11034 11035 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11036 11037 // Save FPSCR value. 11038 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11039 11040 // When the operand is gprc register, use two least significant bits of the 11041 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11042 // 11043 // copy OldFPSCRTmpReg, OldFPSCRReg 11044 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11045 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11046 // copy NewFPSCRReg, NewFPSCRTmpReg 11047 // mtfsf 255, NewFPSCRReg 11048 MachineOperand SrcOp = MI.getOperand(1); 11049 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11050 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11051 11052 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11053 11054 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11055 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11056 11057 // The first operand of INSERT_SUBREG should be a register which has 11058 // subregisters, we only care about its RegClass, so we should use an 11059 // IMPLICIT_DEF register. 11060 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11061 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11062 .addReg(ImDefReg) 11063 .add(SrcOp) 11064 .addImm(1); 11065 11066 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11067 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11068 .addReg(OldFPSCRTmpReg) 11069 .addReg(ExtSrcReg) 11070 .addImm(0) 11071 .addImm(62); 11072 11073 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11074 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11075 11076 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11077 // bits of FPSCR. 11078 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11079 .addImm(255) 11080 .addReg(NewFPSCRReg) 11081 .addImm(0) 11082 .addImm(0); 11083 } else { 11084 llvm_unreachable("Unexpected instr type to insert"); 11085 } 11086 11087 MI.eraseFromParent(); // The pseudo instruction is gone now. 11088 return BB; 11089 } 11090 11091 //===----------------------------------------------------------------------===// 11092 // Target Optimization Hooks 11093 //===----------------------------------------------------------------------===// 11094 11095 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11096 // For the estimates, convergence is quadratic, so we essentially double the 11097 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11098 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11099 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11100 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11101 if (VT.getScalarType() == MVT::f64) 11102 RefinementSteps++; 11103 return RefinementSteps; 11104 } 11105 11106 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11107 int Enabled, int &RefinementSteps, 11108 bool &UseOneConstNR, 11109 bool Reciprocal) const { 11110 EVT VT = Operand.getValueType(); 11111 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11112 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11113 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11114 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11115 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11116 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11117 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11118 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11119 11120 UseOneConstNR = true; 11121 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11122 } 11123 return SDValue(); 11124 } 11125 11126 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11127 int Enabled, 11128 int &RefinementSteps) const { 11129 EVT VT = Operand.getValueType(); 11130 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11131 (VT == MVT::f64 && Subtarget.hasFRE()) || 11132 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11133 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11134 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11135 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11136 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11137 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11138 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11139 } 11140 return SDValue(); 11141 } 11142 11143 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11144 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11145 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11146 // enabled for division), this functionality is redundant with the default 11147 // combiner logic (once the division -> reciprocal/multiply transformation 11148 // has taken place). As a result, this matters more for older cores than for 11149 // newer ones. 11150 11151 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11152 // reciprocal if there are two or more FDIVs (for embedded cores with only 11153 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11154 switch (Subtarget.getDarwinDirective()) { 11155 default: 11156 return 3; 11157 case PPC::DIR_440: 11158 case PPC::DIR_A2: 11159 case PPC::DIR_E500: 11160 case PPC::DIR_E500mc: 11161 case PPC::DIR_E5500: 11162 return 2; 11163 } 11164 } 11165 11166 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11167 // collapsed, and so we need to look through chains of them. 11168 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11169 int64_t& Offset, SelectionDAG &DAG) { 11170 if (DAG.isBaseWithConstantOffset(Loc)) { 11171 Base = Loc.getOperand(0); 11172 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11173 11174 // The base might itself be a base plus an offset, and if so, accumulate 11175 // that as well. 11176 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11177 } 11178 } 11179 11180 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11181 unsigned Bytes, int Dist, 11182 SelectionDAG &DAG) { 11183 if (VT.getSizeInBits() / 8 != Bytes) 11184 return false; 11185 11186 SDValue BaseLoc = Base->getBasePtr(); 11187 if (Loc.getOpcode() == ISD::FrameIndex) { 11188 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11189 return false; 11190 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11191 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11192 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11193 int FS = MFI.getObjectSize(FI); 11194 int BFS = MFI.getObjectSize(BFI); 11195 if (FS != BFS || FS != (int)Bytes) return false; 11196 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11197 } 11198 11199 SDValue Base1 = Loc, Base2 = BaseLoc; 11200 int64_t Offset1 = 0, Offset2 = 0; 11201 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11202 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11203 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11204 return true; 11205 11206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11207 const GlobalValue *GV1 = nullptr; 11208 const GlobalValue *GV2 = nullptr; 11209 Offset1 = 0; 11210 Offset2 = 0; 11211 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11212 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11213 if (isGA1 && isGA2 && GV1 == GV2) 11214 return Offset1 == (Offset2 + Dist*Bytes); 11215 return false; 11216 } 11217 11218 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11219 // not enforce equality of the chain operands. 11220 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11221 unsigned Bytes, int Dist, 11222 SelectionDAG &DAG) { 11223 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11224 EVT VT = LS->getMemoryVT(); 11225 SDValue Loc = LS->getBasePtr(); 11226 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11227 } 11228 11229 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11230 EVT VT; 11231 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11232 default: return false; 11233 case Intrinsic::ppc_qpx_qvlfd: 11234 case Intrinsic::ppc_qpx_qvlfda: 11235 VT = MVT::v4f64; 11236 break; 11237 case Intrinsic::ppc_qpx_qvlfs: 11238 case Intrinsic::ppc_qpx_qvlfsa: 11239 VT = MVT::v4f32; 11240 break; 11241 case Intrinsic::ppc_qpx_qvlfcd: 11242 case Intrinsic::ppc_qpx_qvlfcda: 11243 VT = MVT::v2f64; 11244 break; 11245 case Intrinsic::ppc_qpx_qvlfcs: 11246 case Intrinsic::ppc_qpx_qvlfcsa: 11247 VT = MVT::v2f32; 11248 break; 11249 case Intrinsic::ppc_qpx_qvlfiwa: 11250 case Intrinsic::ppc_qpx_qvlfiwz: 11251 case Intrinsic::ppc_altivec_lvx: 11252 case Intrinsic::ppc_altivec_lvxl: 11253 case Intrinsic::ppc_vsx_lxvw4x: 11254 case Intrinsic::ppc_vsx_lxvw4x_be: 11255 VT = MVT::v4i32; 11256 break; 11257 case Intrinsic::ppc_vsx_lxvd2x: 11258 case Intrinsic::ppc_vsx_lxvd2x_be: 11259 VT = MVT::v2f64; 11260 break; 11261 case Intrinsic::ppc_altivec_lvebx: 11262 VT = MVT::i8; 11263 break; 11264 case Intrinsic::ppc_altivec_lvehx: 11265 VT = MVT::i16; 11266 break; 11267 case Intrinsic::ppc_altivec_lvewx: 11268 VT = MVT::i32; 11269 break; 11270 } 11271 11272 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11273 } 11274 11275 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11276 EVT VT; 11277 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11278 default: return false; 11279 case Intrinsic::ppc_qpx_qvstfd: 11280 case Intrinsic::ppc_qpx_qvstfda: 11281 VT = MVT::v4f64; 11282 break; 11283 case Intrinsic::ppc_qpx_qvstfs: 11284 case Intrinsic::ppc_qpx_qvstfsa: 11285 VT = MVT::v4f32; 11286 break; 11287 case Intrinsic::ppc_qpx_qvstfcd: 11288 case Intrinsic::ppc_qpx_qvstfcda: 11289 VT = MVT::v2f64; 11290 break; 11291 case Intrinsic::ppc_qpx_qvstfcs: 11292 case Intrinsic::ppc_qpx_qvstfcsa: 11293 VT = MVT::v2f32; 11294 break; 11295 case Intrinsic::ppc_qpx_qvstfiw: 11296 case Intrinsic::ppc_qpx_qvstfiwa: 11297 case Intrinsic::ppc_altivec_stvx: 11298 case Intrinsic::ppc_altivec_stvxl: 11299 case Intrinsic::ppc_vsx_stxvw4x: 11300 VT = MVT::v4i32; 11301 break; 11302 case Intrinsic::ppc_vsx_stxvd2x: 11303 VT = MVT::v2f64; 11304 break; 11305 case Intrinsic::ppc_vsx_stxvw4x_be: 11306 VT = MVT::v4i32; 11307 break; 11308 case Intrinsic::ppc_vsx_stxvd2x_be: 11309 VT = MVT::v2f64; 11310 break; 11311 case Intrinsic::ppc_altivec_stvebx: 11312 VT = MVT::i8; 11313 break; 11314 case Intrinsic::ppc_altivec_stvehx: 11315 VT = MVT::i16; 11316 break; 11317 case Intrinsic::ppc_altivec_stvewx: 11318 VT = MVT::i32; 11319 break; 11320 } 11321 11322 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11323 } 11324 11325 return false; 11326 } 11327 11328 // Return true is there is a nearyby consecutive load to the one provided 11329 // (regardless of alignment). We search up and down the chain, looking though 11330 // token factors and other loads (but nothing else). As a result, a true result 11331 // indicates that it is safe to create a new consecutive load adjacent to the 11332 // load provided. 11333 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11334 SDValue Chain = LD->getChain(); 11335 EVT VT = LD->getMemoryVT(); 11336 11337 SmallSet<SDNode *, 16> LoadRoots; 11338 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11339 SmallSet<SDNode *, 16> Visited; 11340 11341 // First, search up the chain, branching to follow all token-factor operands. 11342 // If we find a consecutive load, then we're done, otherwise, record all 11343 // nodes just above the top-level loads and token factors. 11344 while (!Queue.empty()) { 11345 SDNode *ChainNext = Queue.pop_back_val(); 11346 if (!Visited.insert(ChainNext).second) 11347 continue; 11348 11349 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11350 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11351 return true; 11352 11353 if (!Visited.count(ChainLD->getChain().getNode())) 11354 Queue.push_back(ChainLD->getChain().getNode()); 11355 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11356 for (const SDUse &O : ChainNext->ops()) 11357 if (!Visited.count(O.getNode())) 11358 Queue.push_back(O.getNode()); 11359 } else 11360 LoadRoots.insert(ChainNext); 11361 } 11362 11363 // Second, search down the chain, starting from the top-level nodes recorded 11364 // in the first phase. These top-level nodes are the nodes just above all 11365 // loads and token factors. Starting with their uses, recursively look though 11366 // all loads (just the chain uses) and token factors to find a consecutive 11367 // load. 11368 Visited.clear(); 11369 Queue.clear(); 11370 11371 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11372 IE = LoadRoots.end(); I != IE; ++I) { 11373 Queue.push_back(*I); 11374 11375 while (!Queue.empty()) { 11376 SDNode *LoadRoot = Queue.pop_back_val(); 11377 if (!Visited.insert(LoadRoot).second) 11378 continue; 11379 11380 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11381 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11382 return true; 11383 11384 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11385 UE = LoadRoot->use_end(); UI != UE; ++UI) 11386 if (((isa<MemSDNode>(*UI) && 11387 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11388 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11389 Queue.push_back(*UI); 11390 } 11391 } 11392 11393 return false; 11394 } 11395 11396 /// This function is called when we have proved that a SETCC node can be replaced 11397 /// by subtraction (and other supporting instructions) so that the result of 11398 /// comparison is kept in a GPR instead of CR. This function is purely for 11399 /// codegen purposes and has some flags to guide the codegen process. 11400 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11401 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11402 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11403 11404 // Zero extend the operands to the largest legal integer. Originally, they 11405 // must be of a strictly smaller size. 11406 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11407 DAG.getConstant(Size, DL, MVT::i32)); 11408 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11409 DAG.getConstant(Size, DL, MVT::i32)); 11410 11411 // Swap if needed. Depends on the condition code. 11412 if (Swap) 11413 std::swap(Op0, Op1); 11414 11415 // Subtract extended integers. 11416 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11417 11418 // Move the sign bit to the least significant position and zero out the rest. 11419 // Now the least significant bit carries the result of original comparison. 11420 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11421 DAG.getConstant(Size - 1, DL, MVT::i32)); 11422 auto Final = Shifted; 11423 11424 // Complement the result if needed. Based on the condition code. 11425 if (Complement) 11426 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11427 DAG.getConstant(1, DL, MVT::i64)); 11428 11429 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11430 } 11431 11432 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11433 DAGCombinerInfo &DCI) const { 11434 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11435 11436 SelectionDAG &DAG = DCI.DAG; 11437 SDLoc DL(N); 11438 11439 // Size of integers being compared has a critical role in the following 11440 // analysis, so we prefer to do this when all types are legal. 11441 if (!DCI.isAfterLegalizeDAG()) 11442 return SDValue(); 11443 11444 // If all users of SETCC extend its value to a legal integer type 11445 // then we replace SETCC with a subtraction 11446 for (SDNode::use_iterator UI = N->use_begin(), 11447 UE = N->use_end(); UI != UE; ++UI) { 11448 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11449 return SDValue(); 11450 } 11451 11452 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11453 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11454 11455 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11456 11457 if (OpSize < Size) { 11458 switch (CC) { 11459 default: break; 11460 case ISD::SETULT: 11461 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11462 case ISD::SETULE: 11463 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11464 case ISD::SETUGT: 11465 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11466 case ISD::SETUGE: 11467 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11468 } 11469 } 11470 11471 return SDValue(); 11472 } 11473 11474 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11475 DAGCombinerInfo &DCI) const { 11476 SelectionDAG &DAG = DCI.DAG; 11477 SDLoc dl(N); 11478 11479 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11480 // If we're tracking CR bits, we need to be careful that we don't have: 11481 // trunc(binary-ops(zext(x), zext(y))) 11482 // or 11483 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11484 // such that we're unnecessarily moving things into GPRs when it would be 11485 // better to keep them in CR bits. 11486 11487 // Note that trunc here can be an actual i1 trunc, or can be the effective 11488 // truncation that comes from a setcc or select_cc. 11489 if (N->getOpcode() == ISD::TRUNCATE && 11490 N->getValueType(0) != MVT::i1) 11491 return SDValue(); 11492 11493 if (N->getOperand(0).getValueType() != MVT::i32 && 11494 N->getOperand(0).getValueType() != MVT::i64) 11495 return SDValue(); 11496 11497 if (N->getOpcode() == ISD::SETCC || 11498 N->getOpcode() == ISD::SELECT_CC) { 11499 // If we're looking at a comparison, then we need to make sure that the 11500 // high bits (all except for the first) don't matter the result. 11501 ISD::CondCode CC = 11502 cast<CondCodeSDNode>(N->getOperand( 11503 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11504 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11505 11506 if (ISD::isSignedIntSetCC(CC)) { 11507 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11508 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11509 return SDValue(); 11510 } else if (ISD::isUnsignedIntSetCC(CC)) { 11511 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11512 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11513 !DAG.MaskedValueIsZero(N->getOperand(1), 11514 APInt::getHighBitsSet(OpBits, OpBits-1))) 11515 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11516 : SDValue()); 11517 } else { 11518 // This is neither a signed nor an unsigned comparison, just make sure 11519 // that the high bits are equal. 11520 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11521 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11522 11523 // We don't really care about what is known about the first bit (if 11524 // anything), so clear it in all masks prior to comparing them. 11525 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11526 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11527 11528 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11529 return SDValue(); 11530 } 11531 } 11532 11533 // We now know that the higher-order bits are irrelevant, we just need to 11534 // make sure that all of the intermediate operations are bit operations, and 11535 // all inputs are extensions. 11536 if (N->getOperand(0).getOpcode() != ISD::AND && 11537 N->getOperand(0).getOpcode() != ISD::OR && 11538 N->getOperand(0).getOpcode() != ISD::XOR && 11539 N->getOperand(0).getOpcode() != ISD::SELECT && 11540 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11541 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11542 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11543 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11544 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11545 return SDValue(); 11546 11547 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11548 N->getOperand(1).getOpcode() != ISD::AND && 11549 N->getOperand(1).getOpcode() != ISD::OR && 11550 N->getOperand(1).getOpcode() != ISD::XOR && 11551 N->getOperand(1).getOpcode() != ISD::SELECT && 11552 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11553 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11554 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11555 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11556 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11557 return SDValue(); 11558 11559 SmallVector<SDValue, 4> Inputs; 11560 SmallVector<SDValue, 8> BinOps, PromOps; 11561 SmallPtrSet<SDNode *, 16> Visited; 11562 11563 for (unsigned i = 0; i < 2; ++i) { 11564 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11565 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11566 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11567 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11568 isa<ConstantSDNode>(N->getOperand(i))) 11569 Inputs.push_back(N->getOperand(i)); 11570 else 11571 BinOps.push_back(N->getOperand(i)); 11572 11573 if (N->getOpcode() == ISD::TRUNCATE) 11574 break; 11575 } 11576 11577 // Visit all inputs, collect all binary operations (and, or, xor and 11578 // select) that are all fed by extensions. 11579 while (!BinOps.empty()) { 11580 SDValue BinOp = BinOps.back(); 11581 BinOps.pop_back(); 11582 11583 if (!Visited.insert(BinOp.getNode()).second) 11584 continue; 11585 11586 PromOps.push_back(BinOp); 11587 11588 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11589 // The condition of the select is not promoted. 11590 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11591 continue; 11592 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11593 continue; 11594 11595 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11596 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11597 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11598 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11599 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11600 Inputs.push_back(BinOp.getOperand(i)); 11601 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11602 BinOp.getOperand(i).getOpcode() == ISD::OR || 11603 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11604 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11605 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11606 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11607 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11608 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11609 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11610 BinOps.push_back(BinOp.getOperand(i)); 11611 } else { 11612 // We have an input that is not an extension or another binary 11613 // operation; we'll abort this transformation. 11614 return SDValue(); 11615 } 11616 } 11617 } 11618 11619 // Make sure that this is a self-contained cluster of operations (which 11620 // is not quite the same thing as saying that everything has only one 11621 // use). 11622 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11623 if (isa<ConstantSDNode>(Inputs[i])) 11624 continue; 11625 11626 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11627 UE = Inputs[i].getNode()->use_end(); 11628 UI != UE; ++UI) { 11629 SDNode *User = *UI; 11630 if (User != N && !Visited.count(User)) 11631 return SDValue(); 11632 11633 // Make sure that we're not going to promote the non-output-value 11634 // operand(s) or SELECT or SELECT_CC. 11635 // FIXME: Although we could sometimes handle this, and it does occur in 11636 // practice that one of the condition inputs to the select is also one of 11637 // the outputs, we currently can't deal with this. 11638 if (User->getOpcode() == ISD::SELECT) { 11639 if (User->getOperand(0) == Inputs[i]) 11640 return SDValue(); 11641 } else if (User->getOpcode() == ISD::SELECT_CC) { 11642 if (User->getOperand(0) == Inputs[i] || 11643 User->getOperand(1) == Inputs[i]) 11644 return SDValue(); 11645 } 11646 } 11647 } 11648 11649 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11650 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11651 UE = PromOps[i].getNode()->use_end(); 11652 UI != UE; ++UI) { 11653 SDNode *User = *UI; 11654 if (User != N && !Visited.count(User)) 11655 return SDValue(); 11656 11657 // Make sure that we're not going to promote the non-output-value 11658 // operand(s) or SELECT or SELECT_CC. 11659 // FIXME: Although we could sometimes handle this, and it does occur in 11660 // practice that one of the condition inputs to the select is also one of 11661 // the outputs, we currently can't deal with this. 11662 if (User->getOpcode() == ISD::SELECT) { 11663 if (User->getOperand(0) == PromOps[i]) 11664 return SDValue(); 11665 } else if (User->getOpcode() == ISD::SELECT_CC) { 11666 if (User->getOperand(0) == PromOps[i] || 11667 User->getOperand(1) == PromOps[i]) 11668 return SDValue(); 11669 } 11670 } 11671 } 11672 11673 // Replace all inputs with the extension operand. 11674 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11675 // Constants may have users outside the cluster of to-be-promoted nodes, 11676 // and so we need to replace those as we do the promotions. 11677 if (isa<ConstantSDNode>(Inputs[i])) 11678 continue; 11679 else 11680 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11681 } 11682 11683 std::list<HandleSDNode> PromOpHandles; 11684 for (auto &PromOp : PromOps) 11685 PromOpHandles.emplace_back(PromOp); 11686 11687 // Replace all operations (these are all the same, but have a different 11688 // (i1) return type). DAG.getNode will validate that the types of 11689 // a binary operator match, so go through the list in reverse so that 11690 // we've likely promoted both operands first. Any intermediate truncations or 11691 // extensions disappear. 11692 while (!PromOpHandles.empty()) { 11693 SDValue PromOp = PromOpHandles.back().getValue(); 11694 PromOpHandles.pop_back(); 11695 11696 if (PromOp.getOpcode() == ISD::TRUNCATE || 11697 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11698 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11699 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11700 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11701 PromOp.getOperand(0).getValueType() != MVT::i1) { 11702 // The operand is not yet ready (see comment below). 11703 PromOpHandles.emplace_front(PromOp); 11704 continue; 11705 } 11706 11707 SDValue RepValue = PromOp.getOperand(0); 11708 if (isa<ConstantSDNode>(RepValue)) 11709 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11710 11711 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11712 continue; 11713 } 11714 11715 unsigned C; 11716 switch (PromOp.getOpcode()) { 11717 default: C = 0; break; 11718 case ISD::SELECT: C = 1; break; 11719 case ISD::SELECT_CC: C = 2; break; 11720 } 11721 11722 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11723 PromOp.getOperand(C).getValueType() != MVT::i1) || 11724 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11725 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11726 // The to-be-promoted operands of this node have not yet been 11727 // promoted (this should be rare because we're going through the 11728 // list backward, but if one of the operands has several users in 11729 // this cluster of to-be-promoted nodes, it is possible). 11730 PromOpHandles.emplace_front(PromOp); 11731 continue; 11732 } 11733 11734 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11735 PromOp.getNode()->op_end()); 11736 11737 // If there are any constant inputs, make sure they're replaced now. 11738 for (unsigned i = 0; i < 2; ++i) 11739 if (isa<ConstantSDNode>(Ops[C+i])) 11740 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11741 11742 DAG.ReplaceAllUsesOfValueWith(PromOp, 11743 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11744 } 11745 11746 // Now we're left with the initial truncation itself. 11747 if (N->getOpcode() == ISD::TRUNCATE) 11748 return N->getOperand(0); 11749 11750 // Otherwise, this is a comparison. The operands to be compared have just 11751 // changed type (to i1), but everything else is the same. 11752 return SDValue(N, 0); 11753 } 11754 11755 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11756 DAGCombinerInfo &DCI) const { 11757 SelectionDAG &DAG = DCI.DAG; 11758 SDLoc dl(N); 11759 11760 // If we're tracking CR bits, we need to be careful that we don't have: 11761 // zext(binary-ops(trunc(x), trunc(y))) 11762 // or 11763 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11764 // such that we're unnecessarily moving things into CR bits that can more 11765 // efficiently stay in GPRs. Note that if we're not certain that the high 11766 // bits are set as required by the final extension, we still may need to do 11767 // some masking to get the proper behavior. 11768 11769 // This same functionality is important on PPC64 when dealing with 11770 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11771 // the return values of functions. Because it is so similar, it is handled 11772 // here as well. 11773 11774 if (N->getValueType(0) != MVT::i32 && 11775 N->getValueType(0) != MVT::i64) 11776 return SDValue(); 11777 11778 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11779 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11780 return SDValue(); 11781 11782 if (N->getOperand(0).getOpcode() != ISD::AND && 11783 N->getOperand(0).getOpcode() != ISD::OR && 11784 N->getOperand(0).getOpcode() != ISD::XOR && 11785 N->getOperand(0).getOpcode() != ISD::SELECT && 11786 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11787 return SDValue(); 11788 11789 SmallVector<SDValue, 4> Inputs; 11790 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11791 SmallPtrSet<SDNode *, 16> Visited; 11792 11793 // Visit all inputs, collect all binary operations (and, or, xor and 11794 // select) that are all fed by truncations. 11795 while (!BinOps.empty()) { 11796 SDValue BinOp = BinOps.back(); 11797 BinOps.pop_back(); 11798 11799 if (!Visited.insert(BinOp.getNode()).second) 11800 continue; 11801 11802 PromOps.push_back(BinOp); 11803 11804 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11805 // The condition of the select is not promoted. 11806 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11807 continue; 11808 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11809 continue; 11810 11811 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11812 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11813 Inputs.push_back(BinOp.getOperand(i)); 11814 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11815 BinOp.getOperand(i).getOpcode() == ISD::OR || 11816 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11817 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11818 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11819 BinOps.push_back(BinOp.getOperand(i)); 11820 } else { 11821 // We have an input that is not a truncation or another binary 11822 // operation; we'll abort this transformation. 11823 return SDValue(); 11824 } 11825 } 11826 } 11827 11828 // The operands of a select that must be truncated when the select is 11829 // promoted because the operand is actually part of the to-be-promoted set. 11830 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11831 11832 // Make sure that this is a self-contained cluster of operations (which 11833 // is not quite the same thing as saying that everything has only one 11834 // use). 11835 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11836 if (isa<ConstantSDNode>(Inputs[i])) 11837 continue; 11838 11839 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11840 UE = Inputs[i].getNode()->use_end(); 11841 UI != UE; ++UI) { 11842 SDNode *User = *UI; 11843 if (User != N && !Visited.count(User)) 11844 return SDValue(); 11845 11846 // If we're going to promote the non-output-value operand(s) or SELECT or 11847 // SELECT_CC, record them for truncation. 11848 if (User->getOpcode() == ISD::SELECT) { 11849 if (User->getOperand(0) == Inputs[i]) 11850 SelectTruncOp[0].insert(std::make_pair(User, 11851 User->getOperand(0).getValueType())); 11852 } else if (User->getOpcode() == ISD::SELECT_CC) { 11853 if (User->getOperand(0) == Inputs[i]) 11854 SelectTruncOp[0].insert(std::make_pair(User, 11855 User->getOperand(0).getValueType())); 11856 if (User->getOperand(1) == Inputs[i]) 11857 SelectTruncOp[1].insert(std::make_pair(User, 11858 User->getOperand(1).getValueType())); 11859 } 11860 } 11861 } 11862 11863 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11864 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11865 UE = PromOps[i].getNode()->use_end(); 11866 UI != UE; ++UI) { 11867 SDNode *User = *UI; 11868 if (User != N && !Visited.count(User)) 11869 return SDValue(); 11870 11871 // If we're going to promote the non-output-value operand(s) or SELECT or 11872 // SELECT_CC, record them for truncation. 11873 if (User->getOpcode() == ISD::SELECT) { 11874 if (User->getOperand(0) == PromOps[i]) 11875 SelectTruncOp[0].insert(std::make_pair(User, 11876 User->getOperand(0).getValueType())); 11877 } else if (User->getOpcode() == ISD::SELECT_CC) { 11878 if (User->getOperand(0) == PromOps[i]) 11879 SelectTruncOp[0].insert(std::make_pair(User, 11880 User->getOperand(0).getValueType())); 11881 if (User->getOperand(1) == PromOps[i]) 11882 SelectTruncOp[1].insert(std::make_pair(User, 11883 User->getOperand(1).getValueType())); 11884 } 11885 } 11886 } 11887 11888 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11889 bool ReallyNeedsExt = false; 11890 if (N->getOpcode() != ISD::ANY_EXTEND) { 11891 // If all of the inputs are not already sign/zero extended, then 11892 // we'll still need to do that at the end. 11893 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11894 if (isa<ConstantSDNode>(Inputs[i])) 11895 continue; 11896 11897 unsigned OpBits = 11898 Inputs[i].getOperand(0).getValueSizeInBits(); 11899 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11900 11901 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11902 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11903 APInt::getHighBitsSet(OpBits, 11904 OpBits-PromBits))) || 11905 (N->getOpcode() == ISD::SIGN_EXTEND && 11906 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11907 (OpBits-(PromBits-1)))) { 11908 ReallyNeedsExt = true; 11909 break; 11910 } 11911 } 11912 } 11913 11914 // Replace all inputs, either with the truncation operand, or a 11915 // truncation or extension to the final output type. 11916 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11917 // Constant inputs need to be replaced with the to-be-promoted nodes that 11918 // use them because they might have users outside of the cluster of 11919 // promoted nodes. 11920 if (isa<ConstantSDNode>(Inputs[i])) 11921 continue; 11922 11923 SDValue InSrc = Inputs[i].getOperand(0); 11924 if (Inputs[i].getValueType() == N->getValueType(0)) 11925 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11926 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11927 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11928 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11929 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11930 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11931 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11932 else 11933 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11934 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11935 } 11936 11937 std::list<HandleSDNode> PromOpHandles; 11938 for (auto &PromOp : PromOps) 11939 PromOpHandles.emplace_back(PromOp); 11940 11941 // Replace all operations (these are all the same, but have a different 11942 // (promoted) return type). DAG.getNode will validate that the types of 11943 // a binary operator match, so go through the list in reverse so that 11944 // we've likely promoted both operands first. 11945 while (!PromOpHandles.empty()) { 11946 SDValue PromOp = PromOpHandles.back().getValue(); 11947 PromOpHandles.pop_back(); 11948 11949 unsigned C; 11950 switch (PromOp.getOpcode()) { 11951 default: C = 0; break; 11952 case ISD::SELECT: C = 1; break; 11953 case ISD::SELECT_CC: C = 2; break; 11954 } 11955 11956 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11957 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11958 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11959 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11960 // The to-be-promoted operands of this node have not yet been 11961 // promoted (this should be rare because we're going through the 11962 // list backward, but if one of the operands has several users in 11963 // this cluster of to-be-promoted nodes, it is possible). 11964 PromOpHandles.emplace_front(PromOp); 11965 continue; 11966 } 11967 11968 // For SELECT and SELECT_CC nodes, we do a similar check for any 11969 // to-be-promoted comparison inputs. 11970 if (PromOp.getOpcode() == ISD::SELECT || 11971 PromOp.getOpcode() == ISD::SELECT_CC) { 11972 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11973 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11974 (SelectTruncOp[1].count(PromOp.getNode()) && 11975 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11976 PromOpHandles.emplace_front(PromOp); 11977 continue; 11978 } 11979 } 11980 11981 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11982 PromOp.getNode()->op_end()); 11983 11984 // If this node has constant inputs, then they'll need to be promoted here. 11985 for (unsigned i = 0; i < 2; ++i) { 11986 if (!isa<ConstantSDNode>(Ops[C+i])) 11987 continue; 11988 if (Ops[C+i].getValueType() == N->getValueType(0)) 11989 continue; 11990 11991 if (N->getOpcode() == ISD::SIGN_EXTEND) 11992 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11993 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11994 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11995 else 11996 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11997 } 11998 11999 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12000 // truncate them again to the original value type. 12001 if (PromOp.getOpcode() == ISD::SELECT || 12002 PromOp.getOpcode() == ISD::SELECT_CC) { 12003 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12004 if (SI0 != SelectTruncOp[0].end()) 12005 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12006 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12007 if (SI1 != SelectTruncOp[1].end()) 12008 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12009 } 12010 12011 DAG.ReplaceAllUsesOfValueWith(PromOp, 12012 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12013 } 12014 12015 // Now we're left with the initial extension itself. 12016 if (!ReallyNeedsExt) 12017 return N->getOperand(0); 12018 12019 // To zero extend, just mask off everything except for the first bit (in the 12020 // i1 case). 12021 if (N->getOpcode() == ISD::ZERO_EXTEND) 12022 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12023 DAG.getConstant(APInt::getLowBitsSet( 12024 N->getValueSizeInBits(0), PromBits), 12025 dl, N->getValueType(0))); 12026 12027 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12028 "Invalid extension type"); 12029 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12030 SDValue ShiftCst = 12031 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12032 return DAG.getNode( 12033 ISD::SRA, dl, N->getValueType(0), 12034 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12035 ShiftCst); 12036 } 12037 12038 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12039 DAGCombinerInfo &DCI) const { 12040 assert(N->getOpcode() == ISD::SETCC && 12041 "Should be called with a SETCC node"); 12042 12043 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12044 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12045 SDValue LHS = N->getOperand(0); 12046 SDValue RHS = N->getOperand(1); 12047 12048 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12049 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12050 LHS.hasOneUse()) 12051 std::swap(LHS, RHS); 12052 12053 // x == 0-y --> x+y == 0 12054 // x != 0-y --> x+y != 0 12055 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12056 RHS.hasOneUse()) { 12057 SDLoc DL(N); 12058 SelectionDAG &DAG = DCI.DAG; 12059 EVT VT = N->getValueType(0); 12060 EVT OpVT = LHS.getValueType(); 12061 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12062 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12063 } 12064 } 12065 12066 return DAGCombineTruncBoolExt(N, DCI); 12067 } 12068 12069 // Is this an extending load from an f32 to an f64? 12070 static bool isFPExtLoad(SDValue Op) { 12071 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12072 return LD->getExtensionType() == ISD::EXTLOAD && 12073 Op.getValueType() == MVT::f64; 12074 return false; 12075 } 12076 12077 /// Reduces the number of fp-to-int conversion when building a vector. 12078 /// 12079 /// If this vector is built out of floating to integer conversions, 12080 /// transform it to a vector built out of floating point values followed by a 12081 /// single floating to integer conversion of the vector. 12082 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12083 /// becomes (fptosi (build_vector ($A, $B, ...))) 12084 SDValue PPCTargetLowering:: 12085 combineElementTruncationToVectorTruncation(SDNode *N, 12086 DAGCombinerInfo &DCI) const { 12087 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12088 "Should be called with a BUILD_VECTOR node"); 12089 12090 SelectionDAG &DAG = DCI.DAG; 12091 SDLoc dl(N); 12092 12093 SDValue FirstInput = N->getOperand(0); 12094 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12095 "The input operand must be an fp-to-int conversion."); 12096 12097 // This combine happens after legalization so the fp_to_[su]i nodes are 12098 // already converted to PPCSISD nodes. 12099 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12100 if (FirstConversion == PPCISD::FCTIDZ || 12101 FirstConversion == PPCISD::FCTIDUZ || 12102 FirstConversion == PPCISD::FCTIWZ || 12103 FirstConversion == PPCISD::FCTIWUZ) { 12104 bool IsSplat = true; 12105 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12106 FirstConversion == PPCISD::FCTIWUZ; 12107 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12108 SmallVector<SDValue, 4> Ops; 12109 EVT TargetVT = N->getValueType(0); 12110 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12111 SDValue NextOp = N->getOperand(i); 12112 if (NextOp.getOpcode() != PPCISD::MFVSR) 12113 return SDValue(); 12114 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12115 if (NextConversion != FirstConversion) 12116 return SDValue(); 12117 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12118 // This is not valid if the input was originally double precision. It is 12119 // also not profitable to do unless this is an extending load in which 12120 // case doing this combine will allow us to combine consecutive loads. 12121 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12122 return SDValue(); 12123 if (N->getOperand(i) != FirstInput) 12124 IsSplat = false; 12125 } 12126 12127 // If this is a splat, we leave it as-is since there will be only a single 12128 // fp-to-int conversion followed by a splat of the integer. This is better 12129 // for 32-bit and smaller ints and neutral for 64-bit ints. 12130 if (IsSplat) 12131 return SDValue(); 12132 12133 // Now that we know we have the right type of node, get its operands 12134 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12135 SDValue In = N->getOperand(i).getOperand(0); 12136 if (Is32Bit) { 12137 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12138 // here, we know that all inputs are extending loads so this is safe). 12139 if (In.isUndef()) 12140 Ops.push_back(DAG.getUNDEF(SrcVT)); 12141 else { 12142 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12143 MVT::f32, In.getOperand(0), 12144 DAG.getIntPtrConstant(1, dl)); 12145 Ops.push_back(Trunc); 12146 } 12147 } else 12148 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12149 } 12150 12151 unsigned Opcode; 12152 if (FirstConversion == PPCISD::FCTIDZ || 12153 FirstConversion == PPCISD::FCTIWZ) 12154 Opcode = ISD::FP_TO_SINT; 12155 else 12156 Opcode = ISD::FP_TO_UINT; 12157 12158 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12159 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12160 return DAG.getNode(Opcode, dl, TargetVT, BV); 12161 } 12162 return SDValue(); 12163 } 12164 12165 /// Reduce the number of loads when building a vector. 12166 /// 12167 /// Building a vector out of multiple loads can be converted to a load 12168 /// of the vector type if the loads are consecutive. If the loads are 12169 /// consecutive but in descending order, a shuffle is added at the end 12170 /// to reorder the vector. 12171 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12172 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12173 "Should be called with a BUILD_VECTOR node"); 12174 12175 SDLoc dl(N); 12176 bool InputsAreConsecutiveLoads = true; 12177 bool InputsAreReverseConsecutive = true; 12178 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 12179 SDValue FirstInput = N->getOperand(0); 12180 bool IsRoundOfExtLoad = false; 12181 12182 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12183 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12184 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12185 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12186 } 12187 // Not a build vector of (possibly fp_rounded) loads. 12188 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12189 N->getNumOperands() == 1) 12190 return SDValue(); 12191 12192 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12193 // If any inputs are fp_round(extload), they all must be. 12194 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12195 return SDValue(); 12196 12197 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12198 N->getOperand(i); 12199 if (NextInput.getOpcode() != ISD::LOAD) 12200 return SDValue(); 12201 12202 SDValue PreviousInput = 12203 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12204 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12205 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12206 12207 // If any inputs are fp_round(extload), they all must be. 12208 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12209 return SDValue(); 12210 12211 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12212 InputsAreConsecutiveLoads = false; 12213 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12214 InputsAreReverseConsecutive = false; 12215 12216 // Exit early if the loads are neither consecutive nor reverse consecutive. 12217 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12218 return SDValue(); 12219 } 12220 12221 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12222 "The loads cannot be both consecutive and reverse consecutive."); 12223 12224 SDValue FirstLoadOp = 12225 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12226 SDValue LastLoadOp = 12227 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12228 N->getOperand(N->getNumOperands()-1); 12229 12230 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12231 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12232 if (InputsAreConsecutiveLoads) { 12233 assert(LD1 && "Input needs to be a LoadSDNode."); 12234 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12235 LD1->getBasePtr(), LD1->getPointerInfo(), 12236 LD1->getAlignment()); 12237 } 12238 if (InputsAreReverseConsecutive) { 12239 assert(LDL && "Input needs to be a LoadSDNode."); 12240 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12241 LDL->getBasePtr(), LDL->getPointerInfo(), 12242 LDL->getAlignment()); 12243 SmallVector<int, 16> Ops; 12244 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12245 Ops.push_back(i); 12246 12247 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12248 DAG.getUNDEF(N->getValueType(0)), Ops); 12249 } 12250 return SDValue(); 12251 } 12252 12253 // This function adds the required vector_shuffle needed to get 12254 // the elements of the vector extract in the correct position 12255 // as specified by the CorrectElems encoding. 12256 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12257 SDValue Input, uint64_t Elems, 12258 uint64_t CorrectElems) { 12259 SDLoc dl(N); 12260 12261 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12262 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12263 12264 // Knowing the element indices being extracted from the original 12265 // vector and the order in which they're being inserted, just put 12266 // them at element indices required for the instruction. 12267 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12268 if (DAG.getDataLayout().isLittleEndian()) 12269 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12270 else 12271 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12272 CorrectElems = CorrectElems >> 8; 12273 Elems = Elems >> 8; 12274 } 12275 12276 SDValue Shuffle = 12277 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12278 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12279 12280 EVT Ty = N->getValueType(0); 12281 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12282 return BV; 12283 } 12284 12285 // Look for build vector patterns where input operands come from sign 12286 // extended vector_extract elements of specific indices. If the correct indices 12287 // aren't used, add a vector shuffle to fix up the indices and create a new 12288 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12289 // during instruction selection. 12290 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12291 // This array encodes the indices that the vector sign extend instructions 12292 // extract from when extending from one type to another for both BE and LE. 12293 // The right nibble of each byte corresponds to the LE incides. 12294 // and the left nibble of each byte corresponds to the BE incides. 12295 // For example: 0x3074B8FC byte->word 12296 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12297 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12298 // For example: 0x000070F8 byte->double word 12299 // For LE: the allowed indices are: 0x0,0x8 12300 // For BE: the allowed indices are: 0x7,0xF 12301 uint64_t TargetElems[] = { 12302 0x3074B8FC, // b->w 12303 0x000070F8, // b->d 12304 0x10325476, // h->w 12305 0x00003074, // h->d 12306 0x00001032, // w->d 12307 }; 12308 12309 uint64_t Elems = 0; 12310 int Index; 12311 SDValue Input; 12312 12313 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12314 if (!Op) 12315 return false; 12316 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12317 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12318 return false; 12319 12320 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12321 // of the right width. 12322 SDValue Extract = Op.getOperand(0); 12323 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12324 Extract = Extract.getOperand(0); 12325 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12326 return false; 12327 12328 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12329 if (!ExtOp) 12330 return false; 12331 12332 Index = ExtOp->getZExtValue(); 12333 if (Input && Input != Extract.getOperand(0)) 12334 return false; 12335 12336 if (!Input) 12337 Input = Extract.getOperand(0); 12338 12339 Elems = Elems << 8; 12340 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12341 Elems |= Index; 12342 12343 return true; 12344 }; 12345 12346 // If the build vector operands aren't sign extended vector extracts, 12347 // of the same input vector, then return. 12348 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12349 if (!isSExtOfVecExtract(N->getOperand(i))) { 12350 return SDValue(); 12351 } 12352 } 12353 12354 // If the vector extract indicies are not correct, add the appropriate 12355 // vector_shuffle. 12356 int TgtElemArrayIdx; 12357 int InputSize = Input.getValueType().getScalarSizeInBits(); 12358 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12359 if (InputSize + OutputSize == 40) 12360 TgtElemArrayIdx = 0; 12361 else if (InputSize + OutputSize == 72) 12362 TgtElemArrayIdx = 1; 12363 else if (InputSize + OutputSize == 48) 12364 TgtElemArrayIdx = 2; 12365 else if (InputSize + OutputSize == 80) 12366 TgtElemArrayIdx = 3; 12367 else if (InputSize + OutputSize == 96) 12368 TgtElemArrayIdx = 4; 12369 else 12370 return SDValue(); 12371 12372 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12373 CorrectElems = DAG.getDataLayout().isLittleEndian() 12374 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12375 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12376 if (Elems != CorrectElems) { 12377 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12378 } 12379 12380 // Regular lowering will catch cases where a shuffle is not needed. 12381 return SDValue(); 12382 } 12383 12384 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12385 DAGCombinerInfo &DCI) const { 12386 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12387 "Should be called with a BUILD_VECTOR node"); 12388 12389 SelectionDAG &DAG = DCI.DAG; 12390 SDLoc dl(N); 12391 12392 if (!Subtarget.hasVSX()) 12393 return SDValue(); 12394 12395 // The target independent DAG combiner will leave a build_vector of 12396 // float-to-int conversions intact. We can generate MUCH better code for 12397 // a float-to-int conversion of a vector of floats. 12398 SDValue FirstInput = N->getOperand(0); 12399 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12400 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12401 if (Reduced) 12402 return Reduced; 12403 } 12404 12405 // If we're building a vector out of consecutive loads, just load that 12406 // vector type. 12407 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12408 if (Reduced) 12409 return Reduced; 12410 12411 // If we're building a vector out of extended elements from another vector 12412 // we have P9 vector integer extend instructions. The code assumes legal 12413 // input types (i.e. it can't handle things like v4i16) so do not run before 12414 // legalization. 12415 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12416 Reduced = combineBVOfVecSExt(N, DAG); 12417 if (Reduced) 12418 return Reduced; 12419 } 12420 12421 12422 if (N->getValueType(0) != MVT::v2f64) 12423 return SDValue(); 12424 12425 // Looking for: 12426 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12427 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12428 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12429 return SDValue(); 12430 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12431 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12432 return SDValue(); 12433 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12434 return SDValue(); 12435 12436 SDValue Ext1 = FirstInput.getOperand(0); 12437 SDValue Ext2 = N->getOperand(1).getOperand(0); 12438 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12439 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12440 return SDValue(); 12441 12442 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12443 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12444 if (!Ext1Op || !Ext2Op) 12445 return SDValue(); 12446 if (Ext1.getValueType() != MVT::i32 || 12447 Ext2.getValueType() != MVT::i32) 12448 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 12449 return SDValue(); 12450 12451 int FirstElem = Ext1Op->getZExtValue(); 12452 int SecondElem = Ext2Op->getZExtValue(); 12453 int SubvecIdx; 12454 if (FirstElem == 0 && SecondElem == 1) 12455 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12456 else if (FirstElem == 2 && SecondElem == 3) 12457 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12458 else 12459 return SDValue(); 12460 12461 SDValue SrcVec = Ext1.getOperand(0); 12462 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12463 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12464 return DAG.getNode(NodeType, dl, MVT::v2f64, 12465 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12466 } 12467 12468 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12469 DAGCombinerInfo &DCI) const { 12470 assert((N->getOpcode() == ISD::SINT_TO_FP || 12471 N->getOpcode() == ISD::UINT_TO_FP) && 12472 "Need an int -> FP conversion node here"); 12473 12474 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12475 return SDValue(); 12476 12477 SelectionDAG &DAG = DCI.DAG; 12478 SDLoc dl(N); 12479 SDValue Op(N, 0); 12480 12481 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12482 // from the hardware. 12483 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12484 return SDValue(); 12485 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12486 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12487 return SDValue(); 12488 12489 SDValue FirstOperand(Op.getOperand(0)); 12490 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12491 (FirstOperand.getValueType() == MVT::i8 || 12492 FirstOperand.getValueType() == MVT::i16); 12493 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12494 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12495 bool DstDouble = Op.getValueType() == MVT::f64; 12496 unsigned ConvOp = Signed ? 12497 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12498 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12499 SDValue WidthConst = 12500 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12501 dl, false); 12502 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12503 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12504 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12505 DAG.getVTList(MVT::f64, MVT::Other), 12506 Ops, MVT::i8, LDN->getMemOperand()); 12507 12508 // For signed conversion, we need to sign-extend the value in the VSR 12509 if (Signed) { 12510 SDValue ExtOps[] = { Ld, WidthConst }; 12511 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12512 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12513 } else 12514 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12515 } 12516 12517 12518 // For i32 intermediate values, unfortunately, the conversion functions 12519 // leave the upper 32 bits of the value are undefined. Within the set of 12520 // scalar instructions, we have no method for zero- or sign-extending the 12521 // value. Thus, we cannot handle i32 intermediate values here. 12522 if (Op.getOperand(0).getValueType() == MVT::i32) 12523 return SDValue(); 12524 12525 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12526 "UINT_TO_FP is supported only with FPCVT"); 12527 12528 // If we have FCFIDS, then use it when converting to single-precision. 12529 // Otherwise, convert to double-precision and then round. 12530 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12531 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12532 : PPCISD::FCFIDS) 12533 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12534 : PPCISD::FCFID); 12535 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12536 ? MVT::f32 12537 : MVT::f64; 12538 12539 // If we're converting from a float, to an int, and back to a float again, 12540 // then we don't need the store/load pair at all. 12541 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12542 Subtarget.hasFPCVT()) || 12543 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12544 SDValue Src = Op.getOperand(0).getOperand(0); 12545 if (Src.getValueType() == MVT::f32) { 12546 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12547 DCI.AddToWorklist(Src.getNode()); 12548 } else if (Src.getValueType() != MVT::f64) { 12549 // Make sure that we don't pick up a ppc_fp128 source value. 12550 return SDValue(); 12551 } 12552 12553 unsigned FCTOp = 12554 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12555 PPCISD::FCTIDUZ; 12556 12557 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12558 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12559 12560 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12561 FP = DAG.getNode(ISD::FP_ROUND, dl, 12562 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12563 DCI.AddToWorklist(FP.getNode()); 12564 } 12565 12566 return FP; 12567 } 12568 12569 return SDValue(); 12570 } 12571 12572 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12573 // builtins) into loads with swaps. 12574 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12575 DAGCombinerInfo &DCI) const { 12576 SelectionDAG &DAG = DCI.DAG; 12577 SDLoc dl(N); 12578 SDValue Chain; 12579 SDValue Base; 12580 MachineMemOperand *MMO; 12581 12582 switch (N->getOpcode()) { 12583 default: 12584 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12585 case ISD::LOAD: { 12586 LoadSDNode *LD = cast<LoadSDNode>(N); 12587 Chain = LD->getChain(); 12588 Base = LD->getBasePtr(); 12589 MMO = LD->getMemOperand(); 12590 // If the MMO suggests this isn't a load of a full vector, leave 12591 // things alone. For a built-in, we have to make the change for 12592 // correctness, so if there is a size problem that will be a bug. 12593 if (MMO->getSize() < 16) 12594 return SDValue(); 12595 break; 12596 } 12597 case ISD::INTRINSIC_W_CHAIN: { 12598 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12599 Chain = Intrin->getChain(); 12600 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12601 // us what we want. Get operand 2 instead. 12602 Base = Intrin->getOperand(2); 12603 MMO = Intrin->getMemOperand(); 12604 break; 12605 } 12606 } 12607 12608 MVT VecTy = N->getValueType(0).getSimpleVT(); 12609 12610 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12611 // aligned and the type is a vector with elements up to 4 bytes 12612 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12613 && VecTy.getScalarSizeInBits() <= 32 ) { 12614 return SDValue(); 12615 } 12616 12617 SDValue LoadOps[] = { Chain, Base }; 12618 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12619 DAG.getVTList(MVT::v2f64, MVT::Other), 12620 LoadOps, MVT::v2f64, MMO); 12621 12622 DCI.AddToWorklist(Load.getNode()); 12623 Chain = Load.getValue(1); 12624 SDValue Swap = DAG.getNode( 12625 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12626 DCI.AddToWorklist(Swap.getNode()); 12627 12628 // Add a bitcast if the resulting load type doesn't match v2f64. 12629 if (VecTy != MVT::v2f64) { 12630 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12631 DCI.AddToWorklist(N.getNode()); 12632 // Package {bitcast value, swap's chain} to match Load's shape. 12633 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12634 N, Swap.getValue(1)); 12635 } 12636 12637 return Swap; 12638 } 12639 12640 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12641 // builtins) into stores with swaps. 12642 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12643 DAGCombinerInfo &DCI) const { 12644 SelectionDAG &DAG = DCI.DAG; 12645 SDLoc dl(N); 12646 SDValue Chain; 12647 SDValue Base; 12648 unsigned SrcOpnd; 12649 MachineMemOperand *MMO; 12650 12651 switch (N->getOpcode()) { 12652 default: 12653 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12654 case ISD::STORE: { 12655 StoreSDNode *ST = cast<StoreSDNode>(N); 12656 Chain = ST->getChain(); 12657 Base = ST->getBasePtr(); 12658 MMO = ST->getMemOperand(); 12659 SrcOpnd = 1; 12660 // If the MMO suggests this isn't a store of a full vector, leave 12661 // things alone. For a built-in, we have to make the change for 12662 // correctness, so if there is a size problem that will be a bug. 12663 if (MMO->getSize() < 16) 12664 return SDValue(); 12665 break; 12666 } 12667 case ISD::INTRINSIC_VOID: { 12668 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12669 Chain = Intrin->getChain(); 12670 // Intrin->getBasePtr() oddly does not get what we want. 12671 Base = Intrin->getOperand(3); 12672 MMO = Intrin->getMemOperand(); 12673 SrcOpnd = 2; 12674 break; 12675 } 12676 } 12677 12678 SDValue Src = N->getOperand(SrcOpnd); 12679 MVT VecTy = Src.getValueType().getSimpleVT(); 12680 12681 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12682 // aligned and the type is a vector with elements up to 4 bytes 12683 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12684 && VecTy.getScalarSizeInBits() <= 32 ) { 12685 return SDValue(); 12686 } 12687 12688 // All stores are done as v2f64 and possible bit cast. 12689 if (VecTy != MVT::v2f64) { 12690 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12691 DCI.AddToWorklist(Src.getNode()); 12692 } 12693 12694 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12695 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12696 DCI.AddToWorklist(Swap.getNode()); 12697 Chain = Swap.getValue(1); 12698 SDValue StoreOps[] = { Chain, Swap, Base }; 12699 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12700 DAG.getVTList(MVT::Other), 12701 StoreOps, VecTy, MMO); 12702 DCI.AddToWorklist(Store.getNode()); 12703 return Store; 12704 } 12705 12706 // Handle DAG combine for STORE (FP_TO_INT F). 12707 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 12708 DAGCombinerInfo &DCI) const { 12709 12710 SelectionDAG &DAG = DCI.DAG; 12711 SDLoc dl(N); 12712 unsigned Opcode = N->getOperand(1).getOpcode(); 12713 12714 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 12715 && "Not a FP_TO_INT Instruction!"); 12716 12717 SDValue Val = N->getOperand(1).getOperand(0); 12718 EVT Op1VT = N->getOperand(1).getValueType(); 12719 EVT ResVT = Val.getValueType(); 12720 12721 // Floating point types smaller than 32 bits are not legal on Power. 12722 if (ResVT.getScalarSizeInBits() < 32) 12723 return SDValue(); 12724 12725 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 12726 bool ValidTypeForStoreFltAsInt = 12727 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 12728 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 12729 12730 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 12731 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 12732 return SDValue(); 12733 12734 // Extend f32 values to f64 12735 if (ResVT.getScalarSizeInBits() == 32) { 12736 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12737 DCI.AddToWorklist(Val.getNode()); 12738 } 12739 12740 // Set signed or unsigned conversion opcode. 12741 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 12742 PPCISD::FP_TO_SINT_IN_VSR : 12743 PPCISD::FP_TO_UINT_IN_VSR; 12744 12745 Val = DAG.getNode(ConvOpcode, 12746 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 12747 DCI.AddToWorklist(Val.getNode()); 12748 12749 // Set number of bytes being converted. 12750 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 12751 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 12752 DAG.getIntPtrConstant(ByteSize, dl, false), 12753 DAG.getValueType(Op1VT) }; 12754 12755 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 12756 DAG.getVTList(MVT::Other), Ops, 12757 cast<StoreSDNode>(N)->getMemoryVT(), 12758 cast<StoreSDNode>(N)->getMemOperand()); 12759 12760 DCI.AddToWorklist(Val.getNode()); 12761 return Val; 12762 } 12763 12764 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12765 DAGCombinerInfo &DCI) const { 12766 SelectionDAG &DAG = DCI.DAG; 12767 SDLoc dl(N); 12768 switch (N->getOpcode()) { 12769 default: break; 12770 case ISD::ADD: 12771 return combineADD(N, DCI); 12772 case ISD::SHL: 12773 return combineSHL(N, DCI); 12774 case ISD::SRA: 12775 return combineSRA(N, DCI); 12776 case ISD::SRL: 12777 return combineSRL(N, DCI); 12778 case ISD::MUL: 12779 return combineMUL(N, DCI); 12780 case PPCISD::SHL: 12781 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12782 return N->getOperand(0); 12783 break; 12784 case PPCISD::SRL: 12785 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12786 return N->getOperand(0); 12787 break; 12788 case PPCISD::SRA: 12789 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12790 if (C->isNullValue() || // 0 >>s V -> 0. 12791 C->isAllOnesValue()) // -1 >>s V -> -1. 12792 return N->getOperand(0); 12793 } 12794 break; 12795 case ISD::SIGN_EXTEND: 12796 case ISD::ZERO_EXTEND: 12797 case ISD::ANY_EXTEND: 12798 return DAGCombineExtBoolTrunc(N, DCI); 12799 case ISD::TRUNCATE: 12800 return combineTRUNCATE(N, DCI); 12801 case ISD::SETCC: 12802 if (SDValue CSCC = combineSetCC(N, DCI)) 12803 return CSCC; 12804 LLVM_FALLTHROUGH; 12805 case ISD::SELECT_CC: 12806 return DAGCombineTruncBoolExt(N, DCI); 12807 case ISD::SINT_TO_FP: 12808 case ISD::UINT_TO_FP: 12809 return combineFPToIntToFP(N, DCI); 12810 case ISD::STORE: { 12811 12812 EVT Op1VT = N->getOperand(1).getValueType(); 12813 unsigned Opcode = N->getOperand(1).getOpcode(); 12814 12815 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 12816 SDValue Val= combineStoreFPToInt(N, DCI); 12817 if (Val) 12818 return Val; 12819 } 12820 12821 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12822 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 12823 N->getOperand(1).getNode()->hasOneUse() && 12824 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 12825 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 12826 12827 // STBRX can only handle simple types and it makes no sense to store less 12828 // two bytes in byte-reversed order. 12829 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12830 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 12831 break; 12832 12833 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12834 // Do an any-extend to 32-bits if this is a half-word input. 12835 if (BSwapOp.getValueType() == MVT::i16) 12836 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12837 12838 // If the type of BSWAP operand is wider than stored memory width 12839 // it need to be shifted to the right side before STBRX. 12840 if (Op1VT.bitsGT(mVT)) { 12841 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12842 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12843 DAG.getConstant(Shift, dl, MVT::i32)); 12844 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12845 if (Op1VT == MVT::i64) 12846 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12847 } 12848 12849 SDValue Ops[] = { 12850 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12851 }; 12852 return 12853 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12854 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12855 cast<StoreSDNode>(N)->getMemOperand()); 12856 } 12857 12858 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 12859 // So it can increase the chance of CSE constant construction. 12860 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 12861 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 12862 // Need to sign-extended to 64-bits to handle negative values. 12863 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 12864 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 12865 MemVT.getSizeInBits()); 12866 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 12867 12868 // DAG.getTruncStore() can't be used here because it doesn't accept 12869 // the general (base + offset) addressing mode. 12870 // So we use UpdateNodeOperands and setTruncatingStore instead. 12871 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 12872 N->getOperand(3)); 12873 cast<StoreSDNode>(N)->setTruncatingStore(true); 12874 return SDValue(N, 0); 12875 } 12876 12877 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12878 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12879 if (Op1VT.isSimple()) { 12880 MVT StoreVT = Op1VT.getSimpleVT(); 12881 if (Subtarget.needsSwapsForVSXMemOps() && 12882 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12883 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12884 return expandVSXStoreForLE(N, DCI); 12885 } 12886 break; 12887 } 12888 case ISD::LOAD: { 12889 LoadSDNode *LD = cast<LoadSDNode>(N); 12890 EVT VT = LD->getValueType(0); 12891 12892 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12893 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12894 if (VT.isSimple()) { 12895 MVT LoadVT = VT.getSimpleVT(); 12896 if (Subtarget.needsSwapsForVSXMemOps() && 12897 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12898 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12899 return expandVSXLoadForLE(N, DCI); 12900 } 12901 12902 // We sometimes end up with a 64-bit integer load, from which we extract 12903 // two single-precision floating-point numbers. This happens with 12904 // std::complex<float>, and other similar structures, because of the way we 12905 // canonicalize structure copies. However, if we lack direct moves, 12906 // then the final bitcasts from the extracted integer values to the 12907 // floating-point numbers turn into store/load pairs. Even with direct moves, 12908 // just loading the two floating-point numbers is likely better. 12909 auto ReplaceTwoFloatLoad = [&]() { 12910 if (VT != MVT::i64) 12911 return false; 12912 12913 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12914 LD->isVolatile()) 12915 return false; 12916 12917 // We're looking for a sequence like this: 12918 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12919 // t16: i64 = srl t13, Constant:i32<32> 12920 // t17: i32 = truncate t16 12921 // t18: f32 = bitcast t17 12922 // t19: i32 = truncate t13 12923 // t20: f32 = bitcast t19 12924 12925 if (!LD->hasNUsesOfValue(2, 0)) 12926 return false; 12927 12928 auto UI = LD->use_begin(); 12929 while (UI.getUse().getResNo() != 0) ++UI; 12930 SDNode *Trunc = *UI++; 12931 while (UI.getUse().getResNo() != 0) ++UI; 12932 SDNode *RightShift = *UI; 12933 if (Trunc->getOpcode() != ISD::TRUNCATE) 12934 std::swap(Trunc, RightShift); 12935 12936 if (Trunc->getOpcode() != ISD::TRUNCATE || 12937 Trunc->getValueType(0) != MVT::i32 || 12938 !Trunc->hasOneUse()) 12939 return false; 12940 if (RightShift->getOpcode() != ISD::SRL || 12941 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12942 RightShift->getConstantOperandVal(1) != 32 || 12943 !RightShift->hasOneUse()) 12944 return false; 12945 12946 SDNode *Trunc2 = *RightShift->use_begin(); 12947 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12948 Trunc2->getValueType(0) != MVT::i32 || 12949 !Trunc2->hasOneUse()) 12950 return false; 12951 12952 SDNode *Bitcast = *Trunc->use_begin(); 12953 SDNode *Bitcast2 = *Trunc2->use_begin(); 12954 12955 if (Bitcast->getOpcode() != ISD::BITCAST || 12956 Bitcast->getValueType(0) != MVT::f32) 12957 return false; 12958 if (Bitcast2->getOpcode() != ISD::BITCAST || 12959 Bitcast2->getValueType(0) != MVT::f32) 12960 return false; 12961 12962 if (Subtarget.isLittleEndian()) 12963 std::swap(Bitcast, Bitcast2); 12964 12965 // Bitcast has the second float (in memory-layout order) and Bitcast2 12966 // has the first one. 12967 12968 SDValue BasePtr = LD->getBasePtr(); 12969 if (LD->isIndexed()) { 12970 assert(LD->getAddressingMode() == ISD::PRE_INC && 12971 "Non-pre-inc AM on PPC?"); 12972 BasePtr = 12973 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12974 LD->getOffset()); 12975 } 12976 12977 auto MMOFlags = 12978 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12979 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12980 LD->getPointerInfo(), LD->getAlignment(), 12981 MMOFlags, LD->getAAInfo()); 12982 SDValue AddPtr = 12983 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12984 BasePtr, DAG.getIntPtrConstant(4, dl)); 12985 SDValue FloatLoad2 = DAG.getLoad( 12986 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12987 LD->getPointerInfo().getWithOffset(4), 12988 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12989 12990 if (LD->isIndexed()) { 12991 // Note that DAGCombine should re-form any pre-increment load(s) from 12992 // what is produced here if that makes sense. 12993 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12994 } 12995 12996 DCI.CombineTo(Bitcast2, FloatLoad); 12997 DCI.CombineTo(Bitcast, FloatLoad2); 12998 12999 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13000 SDValue(FloatLoad2.getNode(), 1)); 13001 return true; 13002 }; 13003 13004 if (ReplaceTwoFloatLoad()) 13005 return SDValue(N, 0); 13006 13007 EVT MemVT = LD->getMemoryVT(); 13008 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13009 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13010 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13011 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13012 if (LD->isUnindexed() && VT.isVector() && 13013 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13014 // P8 and later hardware should just use LOAD. 13015 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13016 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13017 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13018 LD->getAlignment() >= ScalarABIAlignment)) && 13019 LD->getAlignment() < ABIAlignment) { 13020 // This is a type-legal unaligned Altivec or QPX load. 13021 SDValue Chain = LD->getChain(); 13022 SDValue Ptr = LD->getBasePtr(); 13023 bool isLittleEndian = Subtarget.isLittleEndian(); 13024 13025 // This implements the loading of unaligned vectors as described in 13026 // the venerable Apple Velocity Engine overview. Specifically: 13027 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13028 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13029 // 13030 // The general idea is to expand a sequence of one or more unaligned 13031 // loads into an alignment-based permutation-control instruction (lvsl 13032 // or lvsr), a series of regular vector loads (which always truncate 13033 // their input address to an aligned address), and a series of 13034 // permutations. The results of these permutations are the requested 13035 // loaded values. The trick is that the last "extra" load is not taken 13036 // from the address you might suspect (sizeof(vector) bytes after the 13037 // last requested load), but rather sizeof(vector) - 1 bytes after the 13038 // last requested vector. The point of this is to avoid a page fault if 13039 // the base address happened to be aligned. This works because if the 13040 // base address is aligned, then adding less than a full vector length 13041 // will cause the last vector in the sequence to be (re)loaded. 13042 // Otherwise, the next vector will be fetched as you might suspect was 13043 // necessary. 13044 13045 // We might be able to reuse the permutation generation from 13046 // a different base address offset from this one by an aligned amount. 13047 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13048 // optimization later. 13049 Intrinsic::ID Intr, IntrLD, IntrPerm; 13050 MVT PermCntlTy, PermTy, LDTy; 13051 if (Subtarget.hasAltivec()) { 13052 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13053 Intrinsic::ppc_altivec_lvsl; 13054 IntrLD = Intrinsic::ppc_altivec_lvx; 13055 IntrPerm = Intrinsic::ppc_altivec_vperm; 13056 PermCntlTy = MVT::v16i8; 13057 PermTy = MVT::v4i32; 13058 LDTy = MVT::v4i32; 13059 } else { 13060 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13061 Intrinsic::ppc_qpx_qvlpcls; 13062 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13063 Intrinsic::ppc_qpx_qvlfs; 13064 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13065 PermCntlTy = MVT::v4f64; 13066 PermTy = MVT::v4f64; 13067 LDTy = MemVT.getSimpleVT(); 13068 } 13069 13070 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13071 13072 // Create the new MMO for the new base load. It is like the original MMO, 13073 // but represents an area in memory almost twice the vector size centered 13074 // on the original address. If the address is unaligned, we might start 13075 // reading up to (sizeof(vector)-1) bytes below the address of the 13076 // original unaligned load. 13077 MachineFunction &MF = DAG.getMachineFunction(); 13078 MachineMemOperand *BaseMMO = 13079 MF.getMachineMemOperand(LD->getMemOperand(), 13080 -(long)MemVT.getStoreSize()+1, 13081 2*MemVT.getStoreSize()-1); 13082 13083 // Create the new base load. 13084 SDValue LDXIntID = 13085 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13086 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13087 SDValue BaseLoad = 13088 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13089 DAG.getVTList(PermTy, MVT::Other), 13090 BaseLoadOps, LDTy, BaseMMO); 13091 13092 // Note that the value of IncOffset (which is provided to the next 13093 // load's pointer info offset value, and thus used to calculate the 13094 // alignment), and the value of IncValue (which is actually used to 13095 // increment the pointer value) are different! This is because we 13096 // require the next load to appear to be aligned, even though it 13097 // is actually offset from the base pointer by a lesser amount. 13098 int IncOffset = VT.getSizeInBits() / 8; 13099 int IncValue = IncOffset; 13100 13101 // Walk (both up and down) the chain looking for another load at the real 13102 // (aligned) offset (the alignment of the other load does not matter in 13103 // this case). If found, then do not use the offset reduction trick, as 13104 // that will prevent the loads from being later combined (as they would 13105 // otherwise be duplicates). 13106 if (!findConsecutiveLoad(LD, DAG)) 13107 --IncValue; 13108 13109 SDValue Increment = 13110 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13111 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13112 13113 MachineMemOperand *ExtraMMO = 13114 MF.getMachineMemOperand(LD->getMemOperand(), 13115 1, 2*MemVT.getStoreSize()-1); 13116 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13117 SDValue ExtraLoad = 13118 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13119 DAG.getVTList(PermTy, MVT::Other), 13120 ExtraLoadOps, LDTy, ExtraMMO); 13121 13122 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13123 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13124 13125 // Because vperm has a big-endian bias, we must reverse the order 13126 // of the input vectors and complement the permute control vector 13127 // when generating little endian code. We have already handled the 13128 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13129 // and ExtraLoad here. 13130 SDValue Perm; 13131 if (isLittleEndian) 13132 Perm = BuildIntrinsicOp(IntrPerm, 13133 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13134 else 13135 Perm = BuildIntrinsicOp(IntrPerm, 13136 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13137 13138 if (VT != PermTy) 13139 Perm = Subtarget.hasAltivec() ? 13140 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13141 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13142 DAG.getTargetConstant(1, dl, MVT::i64)); 13143 // second argument is 1 because this rounding 13144 // is always exact. 13145 13146 // The output of the permutation is our loaded result, the TokenFactor is 13147 // our new chain. 13148 DCI.CombineTo(N, Perm, TF); 13149 return SDValue(N, 0); 13150 } 13151 } 13152 break; 13153 case ISD::INTRINSIC_WO_CHAIN: { 13154 bool isLittleEndian = Subtarget.isLittleEndian(); 13155 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13156 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13157 : Intrinsic::ppc_altivec_lvsl); 13158 if ((IID == Intr || 13159 IID == Intrinsic::ppc_qpx_qvlpcld || 13160 IID == Intrinsic::ppc_qpx_qvlpcls) && 13161 N->getOperand(1)->getOpcode() == ISD::ADD) { 13162 SDValue Add = N->getOperand(1); 13163 13164 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13165 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13166 13167 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13168 APInt::getAllOnesValue(Bits /* alignment */) 13169 .zext(Add.getScalarValueSizeInBits()))) { 13170 SDNode *BasePtr = Add->getOperand(0).getNode(); 13171 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13172 UE = BasePtr->use_end(); 13173 UI != UE; ++UI) { 13174 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13175 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13176 // We've found another LVSL/LVSR, and this address is an aligned 13177 // multiple of that one. The results will be the same, so use the 13178 // one we've just found instead. 13179 13180 return SDValue(*UI, 0); 13181 } 13182 } 13183 } 13184 13185 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13186 SDNode *BasePtr = Add->getOperand(0).getNode(); 13187 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13188 UE = BasePtr->use_end(); UI != UE; ++UI) { 13189 if (UI->getOpcode() == ISD::ADD && 13190 isa<ConstantSDNode>(UI->getOperand(1)) && 13191 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13192 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13193 (1ULL << Bits) == 0) { 13194 SDNode *OtherAdd = *UI; 13195 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13196 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13197 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13198 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13199 return SDValue(*VI, 0); 13200 } 13201 } 13202 } 13203 } 13204 } 13205 } 13206 13207 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13208 // Expose the vabsduw/h/b opportunity for down stream 13209 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13210 (IID == Intrinsic::ppc_altivec_vmaxsw || 13211 IID == Intrinsic::ppc_altivec_vmaxsh || 13212 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13213 SDValue V1 = N->getOperand(1); 13214 SDValue V2 = N->getOperand(2); 13215 if ((V1.getSimpleValueType() == MVT::v4i32 || 13216 V1.getSimpleValueType() == MVT::v8i16 || 13217 V1.getSimpleValueType() == MVT::v16i8) && 13218 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13219 // (0-a, a) 13220 if (V1.getOpcode() == ISD::SUB && 13221 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13222 V1.getOperand(1) == V2) { 13223 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13224 } 13225 // (a, 0-a) 13226 if (V2.getOpcode() == ISD::SUB && 13227 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13228 V2.getOperand(1) == V1) { 13229 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13230 } 13231 // (x-y, y-x) 13232 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13233 V1.getOperand(0) == V2.getOperand(1) && 13234 V1.getOperand(1) == V2.getOperand(0)) { 13235 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13236 } 13237 } 13238 } 13239 } 13240 13241 break; 13242 case ISD::INTRINSIC_W_CHAIN: 13243 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13244 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13245 if (Subtarget.needsSwapsForVSXMemOps()) { 13246 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13247 default: 13248 break; 13249 case Intrinsic::ppc_vsx_lxvw4x: 13250 case Intrinsic::ppc_vsx_lxvd2x: 13251 return expandVSXLoadForLE(N, DCI); 13252 } 13253 } 13254 break; 13255 case ISD::INTRINSIC_VOID: 13256 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13257 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13258 if (Subtarget.needsSwapsForVSXMemOps()) { 13259 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13260 default: 13261 break; 13262 case Intrinsic::ppc_vsx_stxvw4x: 13263 case Intrinsic::ppc_vsx_stxvd2x: 13264 return expandVSXStoreForLE(N, DCI); 13265 } 13266 } 13267 break; 13268 case ISD::BSWAP: 13269 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13270 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13271 N->getOperand(0).hasOneUse() && 13272 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13273 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13274 N->getValueType(0) == MVT::i64))) { 13275 SDValue Load = N->getOperand(0); 13276 LoadSDNode *LD = cast<LoadSDNode>(Load); 13277 // Create the byte-swapping load. 13278 SDValue Ops[] = { 13279 LD->getChain(), // Chain 13280 LD->getBasePtr(), // Ptr 13281 DAG.getValueType(N->getValueType(0)) // VT 13282 }; 13283 SDValue BSLoad = 13284 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13285 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13286 MVT::i64 : MVT::i32, MVT::Other), 13287 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13288 13289 // If this is an i16 load, insert the truncate. 13290 SDValue ResVal = BSLoad; 13291 if (N->getValueType(0) == MVT::i16) 13292 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13293 13294 // First, combine the bswap away. This makes the value produced by the 13295 // load dead. 13296 DCI.CombineTo(N, ResVal); 13297 13298 // Next, combine the load away, we give it a bogus result value but a real 13299 // chain result. The result value is dead because the bswap is dead. 13300 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13301 13302 // Return N so it doesn't get rechecked! 13303 return SDValue(N, 0); 13304 } 13305 break; 13306 case PPCISD::VCMP: 13307 // If a VCMPo node already exists with exactly the same operands as this 13308 // node, use its result instead of this node (VCMPo computes both a CR6 and 13309 // a normal output). 13310 // 13311 if (!N->getOperand(0).hasOneUse() && 13312 !N->getOperand(1).hasOneUse() && 13313 !N->getOperand(2).hasOneUse()) { 13314 13315 // Scan all of the users of the LHS, looking for VCMPo's that match. 13316 SDNode *VCMPoNode = nullptr; 13317 13318 SDNode *LHSN = N->getOperand(0).getNode(); 13319 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13320 UI != E; ++UI) 13321 if (UI->getOpcode() == PPCISD::VCMPo && 13322 UI->getOperand(1) == N->getOperand(1) && 13323 UI->getOperand(2) == N->getOperand(2) && 13324 UI->getOperand(0) == N->getOperand(0)) { 13325 VCMPoNode = *UI; 13326 break; 13327 } 13328 13329 // If there is no VCMPo node, or if the flag value has a single use, don't 13330 // transform this. 13331 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13332 break; 13333 13334 // Look at the (necessarily single) use of the flag value. If it has a 13335 // chain, this transformation is more complex. Note that multiple things 13336 // could use the value result, which we should ignore. 13337 SDNode *FlagUser = nullptr; 13338 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13339 FlagUser == nullptr; ++UI) { 13340 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13341 SDNode *User = *UI; 13342 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13343 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13344 FlagUser = User; 13345 break; 13346 } 13347 } 13348 } 13349 13350 // If the user is a MFOCRF instruction, we know this is safe. 13351 // Otherwise we give up for right now. 13352 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13353 return SDValue(VCMPoNode, 0); 13354 } 13355 break; 13356 case ISD::BRCOND: { 13357 SDValue Cond = N->getOperand(1); 13358 SDValue Target = N->getOperand(2); 13359 13360 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13361 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13362 Intrinsic::ppc_is_decremented_ctr_nonzero) { 13363 13364 // We now need to make the intrinsic dead (it cannot be instruction 13365 // selected). 13366 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13367 assert(Cond.getNode()->hasOneUse() && 13368 "Counter decrement has more than one use"); 13369 13370 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13371 N->getOperand(0), Target); 13372 } 13373 } 13374 break; 13375 case ISD::BR_CC: { 13376 // If this is a branch on an altivec predicate comparison, lower this so 13377 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13378 // lowering is done pre-legalize, because the legalizer lowers the predicate 13379 // compare down to code that is difficult to reassemble. 13380 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13381 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13382 13383 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13384 // value. If so, pass-through the AND to get to the intrinsic. 13385 if (LHS.getOpcode() == ISD::AND && 13386 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13387 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13388 Intrinsic::ppc_is_decremented_ctr_nonzero && 13389 isa<ConstantSDNode>(LHS.getOperand(1)) && 13390 !isNullConstant(LHS.getOperand(1))) 13391 LHS = LHS.getOperand(0); 13392 13393 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13394 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13395 Intrinsic::ppc_is_decremented_ctr_nonzero && 13396 isa<ConstantSDNode>(RHS)) { 13397 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13398 "Counter decrement comparison is not EQ or NE"); 13399 13400 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13401 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13402 (CC == ISD::SETNE && !Val); 13403 13404 // We now need to make the intrinsic dead (it cannot be instruction 13405 // selected). 13406 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13407 assert(LHS.getNode()->hasOneUse() && 13408 "Counter decrement has more than one use"); 13409 13410 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13411 N->getOperand(0), N->getOperand(4)); 13412 } 13413 13414 int CompareOpc; 13415 bool isDot; 13416 13417 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13418 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13419 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13420 assert(isDot && "Can't compare against a vector result!"); 13421 13422 // If this is a comparison against something other than 0/1, then we know 13423 // that the condition is never/always true. 13424 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13425 if (Val != 0 && Val != 1) { 13426 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13427 return N->getOperand(0); 13428 // Always !=, turn it into an unconditional branch. 13429 return DAG.getNode(ISD::BR, dl, MVT::Other, 13430 N->getOperand(0), N->getOperand(4)); 13431 } 13432 13433 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13434 13435 // Create the PPCISD altivec 'dot' comparison node. 13436 SDValue Ops[] = { 13437 LHS.getOperand(2), // LHS of compare 13438 LHS.getOperand(3), // RHS of compare 13439 DAG.getConstant(CompareOpc, dl, MVT::i32) 13440 }; 13441 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13442 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13443 13444 // Unpack the result based on how the target uses it. 13445 PPC::Predicate CompOpc; 13446 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13447 default: // Can't happen, don't crash on invalid number though. 13448 case 0: // Branch on the value of the EQ bit of CR6. 13449 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13450 break; 13451 case 1: // Branch on the inverted value of the EQ bit of CR6. 13452 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13453 break; 13454 case 2: // Branch on the value of the LT bit of CR6. 13455 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13456 break; 13457 case 3: // Branch on the inverted value of the LT bit of CR6. 13458 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13459 break; 13460 } 13461 13462 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13463 DAG.getConstant(CompOpc, dl, MVT::i32), 13464 DAG.getRegister(PPC::CR6, MVT::i32), 13465 N->getOperand(4), CompNode.getValue(1)); 13466 } 13467 break; 13468 } 13469 case ISD::BUILD_VECTOR: 13470 return DAGCombineBuildVector(N, DCI); 13471 case ISD::ABS: 13472 return combineABS(N, DCI); 13473 case ISD::VSELECT: 13474 return combineVSelect(N, DCI); 13475 } 13476 13477 return SDValue(); 13478 } 13479 13480 SDValue 13481 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13482 SelectionDAG &DAG, 13483 SmallVectorImpl<SDNode *> &Created) const { 13484 // fold (sdiv X, pow2) 13485 EVT VT = N->getValueType(0); 13486 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13487 return SDValue(); 13488 if ((VT != MVT::i32 && VT != MVT::i64) || 13489 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13490 return SDValue(); 13491 13492 SDLoc DL(N); 13493 SDValue N0 = N->getOperand(0); 13494 13495 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13496 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13497 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13498 13499 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13500 Created.push_back(Op.getNode()); 13501 13502 if (IsNegPow2) { 13503 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13504 Created.push_back(Op.getNode()); 13505 } 13506 13507 return Op; 13508 } 13509 13510 //===----------------------------------------------------------------------===// 13511 // Inline Assembly Support 13512 //===----------------------------------------------------------------------===// 13513 13514 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13515 KnownBits &Known, 13516 const APInt &DemandedElts, 13517 const SelectionDAG &DAG, 13518 unsigned Depth) const { 13519 Known.resetAll(); 13520 switch (Op.getOpcode()) { 13521 default: break; 13522 case PPCISD::LBRX: { 13523 // lhbrx is known to have the top bits cleared out. 13524 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13525 Known.Zero = 0xFFFF0000; 13526 break; 13527 } 13528 case ISD::INTRINSIC_WO_CHAIN: { 13529 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13530 default: break; 13531 case Intrinsic::ppc_altivec_vcmpbfp_p: 13532 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13533 case Intrinsic::ppc_altivec_vcmpequb_p: 13534 case Intrinsic::ppc_altivec_vcmpequh_p: 13535 case Intrinsic::ppc_altivec_vcmpequw_p: 13536 case Intrinsic::ppc_altivec_vcmpequd_p: 13537 case Intrinsic::ppc_altivec_vcmpgefp_p: 13538 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13539 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13540 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13541 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13542 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13543 case Intrinsic::ppc_altivec_vcmpgtub_p: 13544 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13545 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13546 case Intrinsic::ppc_altivec_vcmpgtud_p: 13547 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13548 break; 13549 } 13550 } 13551 } 13552 } 13553 13554 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13555 switch (Subtarget.getDarwinDirective()) { 13556 default: break; 13557 case PPC::DIR_970: 13558 case PPC::DIR_PWR4: 13559 case PPC::DIR_PWR5: 13560 case PPC::DIR_PWR5X: 13561 case PPC::DIR_PWR6: 13562 case PPC::DIR_PWR6X: 13563 case PPC::DIR_PWR7: 13564 case PPC::DIR_PWR8: 13565 case PPC::DIR_PWR9: { 13566 if (!ML) 13567 break; 13568 13569 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 13570 13571 // For small loops (between 5 and 8 instructions), align to a 32-byte 13572 // boundary so that the entire loop fits in one instruction-cache line. 13573 uint64_t LoopSize = 0; 13574 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 13575 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 13576 LoopSize += TII->getInstSizeInBytes(*J); 13577 if (LoopSize > 32) 13578 break; 13579 } 13580 13581 if (LoopSize > 16 && LoopSize <= 32) 13582 return 5; 13583 13584 break; 13585 } 13586 } 13587 13588 return TargetLowering::getPrefLoopAlignment(ML); 13589 } 13590 13591 /// getConstraintType - Given a constraint, return the type of 13592 /// constraint it is for this target. 13593 PPCTargetLowering::ConstraintType 13594 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 13595 if (Constraint.size() == 1) { 13596 switch (Constraint[0]) { 13597 default: break; 13598 case 'b': 13599 case 'r': 13600 case 'f': 13601 case 'd': 13602 case 'v': 13603 case 'y': 13604 return C_RegisterClass; 13605 case 'Z': 13606 // FIXME: While Z does indicate a memory constraint, it specifically 13607 // indicates an r+r address (used in conjunction with the 'y' modifier 13608 // in the replacement string). Currently, we're forcing the base 13609 // register to be r0 in the asm printer (which is interpreted as zero) 13610 // and forming the complete address in the second register. This is 13611 // suboptimal. 13612 return C_Memory; 13613 } 13614 } else if (Constraint == "wc") { // individual CR bits. 13615 return C_RegisterClass; 13616 } else if (Constraint == "wa" || Constraint == "wd" || 13617 Constraint == "wf" || Constraint == "ws" || 13618 Constraint == "wi") { 13619 return C_RegisterClass; // VSX registers. 13620 } 13621 return TargetLowering::getConstraintType(Constraint); 13622 } 13623 13624 /// Examine constraint type and operand type and determine a weight value. 13625 /// This object must already have been set up with the operand type 13626 /// and the current alternative constraint selected. 13627 TargetLowering::ConstraintWeight 13628 PPCTargetLowering::getSingleConstraintMatchWeight( 13629 AsmOperandInfo &info, const char *constraint) const { 13630 ConstraintWeight weight = CW_Invalid; 13631 Value *CallOperandVal = info.CallOperandVal; 13632 // If we don't have a value, we can't do a match, 13633 // but allow it at the lowest weight. 13634 if (!CallOperandVal) 13635 return CW_Default; 13636 Type *type = CallOperandVal->getType(); 13637 13638 // Look at the constraint type. 13639 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 13640 return CW_Register; // an individual CR bit. 13641 else if ((StringRef(constraint) == "wa" || 13642 StringRef(constraint) == "wd" || 13643 StringRef(constraint) == "wf") && 13644 type->isVectorTy()) 13645 return CW_Register; 13646 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 13647 return CW_Register; 13648 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 13649 return CW_Register; // just hold 64-bit integers data. 13650 13651 switch (*constraint) { 13652 default: 13653 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13654 break; 13655 case 'b': 13656 if (type->isIntegerTy()) 13657 weight = CW_Register; 13658 break; 13659 case 'f': 13660 if (type->isFloatTy()) 13661 weight = CW_Register; 13662 break; 13663 case 'd': 13664 if (type->isDoubleTy()) 13665 weight = CW_Register; 13666 break; 13667 case 'v': 13668 if (type->isVectorTy()) 13669 weight = CW_Register; 13670 break; 13671 case 'y': 13672 weight = CW_Register; 13673 break; 13674 case 'Z': 13675 weight = CW_Memory; 13676 break; 13677 } 13678 return weight; 13679 } 13680 13681 std::pair<unsigned, const TargetRegisterClass *> 13682 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 13683 StringRef Constraint, 13684 MVT VT) const { 13685 if (Constraint.size() == 1) { 13686 // GCC RS6000 Constraint Letters 13687 switch (Constraint[0]) { 13688 case 'b': // R1-R31 13689 if (VT == MVT::i64 && Subtarget.isPPC64()) 13690 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 13691 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 13692 case 'r': // R0-R31 13693 if (VT == MVT::i64 && Subtarget.isPPC64()) 13694 return std::make_pair(0U, &PPC::G8RCRegClass); 13695 return std::make_pair(0U, &PPC::GPRCRegClass); 13696 // 'd' and 'f' constraints are both defined to be "the floating point 13697 // registers", where one is for 32-bit and the other for 64-bit. We don't 13698 // really care overly much here so just give them all the same reg classes. 13699 case 'd': 13700 case 'f': 13701 if (Subtarget.hasSPE()) { 13702 if (VT == MVT::f32 || VT == MVT::i32) 13703 return std::make_pair(0U, &PPC::SPE4RCRegClass); 13704 if (VT == MVT::f64 || VT == MVT::i64) 13705 return std::make_pair(0U, &PPC::SPERCRegClass); 13706 } else { 13707 if (VT == MVT::f32 || VT == MVT::i32) 13708 return std::make_pair(0U, &PPC::F4RCRegClass); 13709 if (VT == MVT::f64 || VT == MVT::i64) 13710 return std::make_pair(0U, &PPC::F8RCRegClass); 13711 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13712 return std::make_pair(0U, &PPC::QFRCRegClass); 13713 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13714 return std::make_pair(0U, &PPC::QSRCRegClass); 13715 } 13716 break; 13717 case 'v': 13718 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13719 return std::make_pair(0U, &PPC::QFRCRegClass); 13720 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13721 return std::make_pair(0U, &PPC::QSRCRegClass); 13722 if (Subtarget.hasAltivec()) 13723 return std::make_pair(0U, &PPC::VRRCRegClass); 13724 break; 13725 case 'y': // crrc 13726 return std::make_pair(0U, &PPC::CRRCRegClass); 13727 } 13728 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13729 // An individual CR bit. 13730 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13731 } else if ((Constraint == "wa" || Constraint == "wd" || 13732 Constraint == "wf" || Constraint == "wi") && 13733 Subtarget.hasVSX()) { 13734 return std::make_pair(0U, &PPC::VSRCRegClass); 13735 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13736 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13737 return std::make_pair(0U, &PPC::VSSRCRegClass); 13738 else 13739 return std::make_pair(0U, &PPC::VSFRCRegClass); 13740 } 13741 13742 std::pair<unsigned, const TargetRegisterClass *> R = 13743 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13744 13745 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13746 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13747 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13748 // register. 13749 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13750 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13751 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13752 PPC::GPRCRegClass.contains(R.first)) 13753 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13754 PPC::sub_32, &PPC::G8RCRegClass), 13755 &PPC::G8RCRegClass); 13756 13757 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13758 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13759 R.first = PPC::CR0; 13760 R.second = &PPC::CRRCRegClass; 13761 } 13762 13763 return R; 13764 } 13765 13766 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13767 /// vector. If it is invalid, don't add anything to Ops. 13768 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13769 std::string &Constraint, 13770 std::vector<SDValue>&Ops, 13771 SelectionDAG &DAG) const { 13772 SDValue Result; 13773 13774 // Only support length 1 constraints. 13775 if (Constraint.length() > 1) return; 13776 13777 char Letter = Constraint[0]; 13778 switch (Letter) { 13779 default: break; 13780 case 'I': 13781 case 'J': 13782 case 'K': 13783 case 'L': 13784 case 'M': 13785 case 'N': 13786 case 'O': 13787 case 'P': { 13788 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13789 if (!CST) return; // Must be an immediate to match. 13790 SDLoc dl(Op); 13791 int64_t Value = CST->getSExtValue(); 13792 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13793 // numbers are printed as such. 13794 switch (Letter) { 13795 default: llvm_unreachable("Unknown constraint letter!"); 13796 case 'I': // "I" is a signed 16-bit constant. 13797 if (isInt<16>(Value)) 13798 Result = DAG.getTargetConstant(Value, dl, TCVT); 13799 break; 13800 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13801 if (isShiftedUInt<16, 16>(Value)) 13802 Result = DAG.getTargetConstant(Value, dl, TCVT); 13803 break; 13804 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13805 if (isShiftedInt<16, 16>(Value)) 13806 Result = DAG.getTargetConstant(Value, dl, TCVT); 13807 break; 13808 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13809 if (isUInt<16>(Value)) 13810 Result = DAG.getTargetConstant(Value, dl, TCVT); 13811 break; 13812 case 'M': // "M" is a constant that is greater than 31. 13813 if (Value > 31) 13814 Result = DAG.getTargetConstant(Value, dl, TCVT); 13815 break; 13816 case 'N': // "N" is a positive constant that is an exact power of two. 13817 if (Value > 0 && isPowerOf2_64(Value)) 13818 Result = DAG.getTargetConstant(Value, dl, TCVT); 13819 break; 13820 case 'O': // "O" is the constant zero. 13821 if (Value == 0) 13822 Result = DAG.getTargetConstant(Value, dl, TCVT); 13823 break; 13824 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13825 if (isInt<16>(-Value)) 13826 Result = DAG.getTargetConstant(Value, dl, TCVT); 13827 break; 13828 } 13829 break; 13830 } 13831 } 13832 13833 if (Result.getNode()) { 13834 Ops.push_back(Result); 13835 return; 13836 } 13837 13838 // Handle standard constraint letters. 13839 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13840 } 13841 13842 // isLegalAddressingMode - Return true if the addressing mode represented 13843 // by AM is legal for this target, for a load/store of the specified type. 13844 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13845 const AddrMode &AM, Type *Ty, 13846 unsigned AS, Instruction *I) const { 13847 // PPC does not allow r+i addressing modes for vectors! 13848 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13849 return false; 13850 13851 // PPC allows a sign-extended 16-bit immediate field. 13852 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13853 return false; 13854 13855 // No global is ever allowed as a base. 13856 if (AM.BaseGV) 13857 return false; 13858 13859 // PPC only support r+r, 13860 switch (AM.Scale) { 13861 case 0: // "r+i" or just "i", depending on HasBaseReg. 13862 break; 13863 case 1: 13864 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13865 return false; 13866 // Otherwise we have r+r or r+i. 13867 break; 13868 case 2: 13869 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13870 return false; 13871 // Allow 2*r as r+r. 13872 break; 13873 default: 13874 // No other scales are supported. 13875 return false; 13876 } 13877 13878 return true; 13879 } 13880 13881 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13882 SelectionDAG &DAG) const { 13883 MachineFunction &MF = DAG.getMachineFunction(); 13884 MachineFrameInfo &MFI = MF.getFrameInfo(); 13885 MFI.setReturnAddressIsTaken(true); 13886 13887 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13888 return SDValue(); 13889 13890 SDLoc dl(Op); 13891 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13892 13893 // Make sure the function does not optimize away the store of the RA to 13894 // the stack. 13895 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13896 FuncInfo->setLRStoreRequired(); 13897 bool isPPC64 = Subtarget.isPPC64(); 13898 auto PtrVT = getPointerTy(MF.getDataLayout()); 13899 13900 if (Depth > 0) { 13901 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13902 SDValue Offset = 13903 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13904 isPPC64 ? MVT::i64 : MVT::i32); 13905 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13906 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13907 MachinePointerInfo()); 13908 } 13909 13910 // Just load the return address off the stack. 13911 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13912 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13913 MachinePointerInfo()); 13914 } 13915 13916 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13917 SelectionDAG &DAG) const { 13918 SDLoc dl(Op); 13919 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13920 13921 MachineFunction &MF = DAG.getMachineFunction(); 13922 MachineFrameInfo &MFI = MF.getFrameInfo(); 13923 MFI.setFrameAddressIsTaken(true); 13924 13925 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13926 bool isPPC64 = PtrVT == MVT::i64; 13927 13928 // Naked functions never have a frame pointer, and so we use r1. For all 13929 // other functions, this decision must be delayed until during PEI. 13930 unsigned FrameReg; 13931 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 13932 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13933 else 13934 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13935 13936 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13937 PtrVT); 13938 while (Depth--) 13939 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13940 FrameAddr, MachinePointerInfo()); 13941 return FrameAddr; 13942 } 13943 13944 // FIXME? Maybe this could be a TableGen attribute on some registers and 13945 // this table could be generated automatically from RegInfo. 13946 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13947 SelectionDAG &DAG) const { 13948 bool isPPC64 = Subtarget.isPPC64(); 13949 bool isDarwinABI = Subtarget.isDarwinABI(); 13950 13951 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13952 (!isPPC64 && VT != MVT::i32)) 13953 report_fatal_error("Invalid register global variable type"); 13954 13955 bool is64Bit = isPPC64 && VT == MVT::i64; 13956 unsigned Reg = StringSwitch<unsigned>(RegName) 13957 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13958 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13959 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13960 (is64Bit ? PPC::X13 : PPC::R13)) 13961 .Default(0); 13962 13963 if (Reg) 13964 return Reg; 13965 report_fatal_error("Invalid register name global variable"); 13966 } 13967 13968 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 13969 // 32-bit SVR4 ABI access everything as got-indirect. 13970 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 13971 return true; 13972 13973 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 13974 // If it is small or large code model, module locals are accessed 13975 // indirectly by loading their address from .toc/.got. The difference 13976 // is that for large code model we have ADDISTocHa + LDtocL and for 13977 // small code model we simply have LDtoc. 13978 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 13979 return true; 13980 13981 // JumpTable and BlockAddress are accessed as got-indirect. 13982 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 13983 return true; 13984 13985 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 13986 const GlobalValue *GV = G->getGlobal(); 13987 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 13988 // The NLP flag indicates that a global access has to use an 13989 // extra indirection. 13990 if (GVFlags & PPCII::MO_NLP_FLAG) 13991 return true; 13992 } 13993 13994 return false; 13995 } 13996 13997 bool 13998 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13999 // The PowerPC target isn't yet aware of offsets. 14000 return false; 14001 } 14002 14003 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14004 const CallInst &I, 14005 MachineFunction &MF, 14006 unsigned Intrinsic) const { 14007 switch (Intrinsic) { 14008 case Intrinsic::ppc_qpx_qvlfd: 14009 case Intrinsic::ppc_qpx_qvlfs: 14010 case Intrinsic::ppc_qpx_qvlfcd: 14011 case Intrinsic::ppc_qpx_qvlfcs: 14012 case Intrinsic::ppc_qpx_qvlfiwa: 14013 case Intrinsic::ppc_qpx_qvlfiwz: 14014 case Intrinsic::ppc_altivec_lvx: 14015 case Intrinsic::ppc_altivec_lvxl: 14016 case Intrinsic::ppc_altivec_lvebx: 14017 case Intrinsic::ppc_altivec_lvehx: 14018 case Intrinsic::ppc_altivec_lvewx: 14019 case Intrinsic::ppc_vsx_lxvd2x: 14020 case Intrinsic::ppc_vsx_lxvw4x: { 14021 EVT VT; 14022 switch (Intrinsic) { 14023 case Intrinsic::ppc_altivec_lvebx: 14024 VT = MVT::i8; 14025 break; 14026 case Intrinsic::ppc_altivec_lvehx: 14027 VT = MVT::i16; 14028 break; 14029 case Intrinsic::ppc_altivec_lvewx: 14030 VT = MVT::i32; 14031 break; 14032 case Intrinsic::ppc_vsx_lxvd2x: 14033 VT = MVT::v2f64; 14034 break; 14035 case Intrinsic::ppc_qpx_qvlfd: 14036 VT = MVT::v4f64; 14037 break; 14038 case Intrinsic::ppc_qpx_qvlfs: 14039 VT = MVT::v4f32; 14040 break; 14041 case Intrinsic::ppc_qpx_qvlfcd: 14042 VT = MVT::v2f64; 14043 break; 14044 case Intrinsic::ppc_qpx_qvlfcs: 14045 VT = MVT::v2f32; 14046 break; 14047 default: 14048 VT = MVT::v4i32; 14049 break; 14050 } 14051 14052 Info.opc = ISD::INTRINSIC_W_CHAIN; 14053 Info.memVT = VT; 14054 Info.ptrVal = I.getArgOperand(0); 14055 Info.offset = -VT.getStoreSize()+1; 14056 Info.size = 2*VT.getStoreSize()-1; 14057 Info.align = 1; 14058 Info.flags = MachineMemOperand::MOLoad; 14059 return true; 14060 } 14061 case Intrinsic::ppc_qpx_qvlfda: 14062 case Intrinsic::ppc_qpx_qvlfsa: 14063 case Intrinsic::ppc_qpx_qvlfcda: 14064 case Intrinsic::ppc_qpx_qvlfcsa: 14065 case Intrinsic::ppc_qpx_qvlfiwaa: 14066 case Intrinsic::ppc_qpx_qvlfiwza: { 14067 EVT VT; 14068 switch (Intrinsic) { 14069 case Intrinsic::ppc_qpx_qvlfda: 14070 VT = MVT::v4f64; 14071 break; 14072 case Intrinsic::ppc_qpx_qvlfsa: 14073 VT = MVT::v4f32; 14074 break; 14075 case Intrinsic::ppc_qpx_qvlfcda: 14076 VT = MVT::v2f64; 14077 break; 14078 case Intrinsic::ppc_qpx_qvlfcsa: 14079 VT = MVT::v2f32; 14080 break; 14081 default: 14082 VT = MVT::v4i32; 14083 break; 14084 } 14085 14086 Info.opc = ISD::INTRINSIC_W_CHAIN; 14087 Info.memVT = VT; 14088 Info.ptrVal = I.getArgOperand(0); 14089 Info.offset = 0; 14090 Info.size = VT.getStoreSize(); 14091 Info.align = 1; 14092 Info.flags = MachineMemOperand::MOLoad; 14093 return true; 14094 } 14095 case Intrinsic::ppc_qpx_qvstfd: 14096 case Intrinsic::ppc_qpx_qvstfs: 14097 case Intrinsic::ppc_qpx_qvstfcd: 14098 case Intrinsic::ppc_qpx_qvstfcs: 14099 case Intrinsic::ppc_qpx_qvstfiw: 14100 case Intrinsic::ppc_altivec_stvx: 14101 case Intrinsic::ppc_altivec_stvxl: 14102 case Intrinsic::ppc_altivec_stvebx: 14103 case Intrinsic::ppc_altivec_stvehx: 14104 case Intrinsic::ppc_altivec_stvewx: 14105 case Intrinsic::ppc_vsx_stxvd2x: 14106 case Intrinsic::ppc_vsx_stxvw4x: { 14107 EVT VT; 14108 switch (Intrinsic) { 14109 case Intrinsic::ppc_altivec_stvebx: 14110 VT = MVT::i8; 14111 break; 14112 case Intrinsic::ppc_altivec_stvehx: 14113 VT = MVT::i16; 14114 break; 14115 case Intrinsic::ppc_altivec_stvewx: 14116 VT = MVT::i32; 14117 break; 14118 case Intrinsic::ppc_vsx_stxvd2x: 14119 VT = MVT::v2f64; 14120 break; 14121 case Intrinsic::ppc_qpx_qvstfd: 14122 VT = MVT::v4f64; 14123 break; 14124 case Intrinsic::ppc_qpx_qvstfs: 14125 VT = MVT::v4f32; 14126 break; 14127 case Intrinsic::ppc_qpx_qvstfcd: 14128 VT = MVT::v2f64; 14129 break; 14130 case Intrinsic::ppc_qpx_qvstfcs: 14131 VT = MVT::v2f32; 14132 break; 14133 default: 14134 VT = MVT::v4i32; 14135 break; 14136 } 14137 14138 Info.opc = ISD::INTRINSIC_VOID; 14139 Info.memVT = VT; 14140 Info.ptrVal = I.getArgOperand(1); 14141 Info.offset = -VT.getStoreSize()+1; 14142 Info.size = 2*VT.getStoreSize()-1; 14143 Info.align = 1; 14144 Info.flags = MachineMemOperand::MOStore; 14145 return true; 14146 } 14147 case Intrinsic::ppc_qpx_qvstfda: 14148 case Intrinsic::ppc_qpx_qvstfsa: 14149 case Intrinsic::ppc_qpx_qvstfcda: 14150 case Intrinsic::ppc_qpx_qvstfcsa: 14151 case Intrinsic::ppc_qpx_qvstfiwa: { 14152 EVT VT; 14153 switch (Intrinsic) { 14154 case Intrinsic::ppc_qpx_qvstfda: 14155 VT = MVT::v4f64; 14156 break; 14157 case Intrinsic::ppc_qpx_qvstfsa: 14158 VT = MVT::v4f32; 14159 break; 14160 case Intrinsic::ppc_qpx_qvstfcda: 14161 VT = MVT::v2f64; 14162 break; 14163 case Intrinsic::ppc_qpx_qvstfcsa: 14164 VT = MVT::v2f32; 14165 break; 14166 default: 14167 VT = MVT::v4i32; 14168 break; 14169 } 14170 14171 Info.opc = ISD::INTRINSIC_VOID; 14172 Info.memVT = VT; 14173 Info.ptrVal = I.getArgOperand(1); 14174 Info.offset = 0; 14175 Info.size = VT.getStoreSize(); 14176 Info.align = 1; 14177 Info.flags = MachineMemOperand::MOStore; 14178 return true; 14179 } 14180 default: 14181 break; 14182 } 14183 14184 return false; 14185 } 14186 14187 /// getOptimalMemOpType - Returns the target specific optimal type for load 14188 /// and store operations as a result of memset, memcpy, and memmove 14189 /// lowering. If DstAlign is zero that means it's safe to destination 14190 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14191 /// means there isn't a need to check it against alignment requirement, 14192 /// probably because the source does not need to be loaded. If 'IsMemset' is 14193 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14194 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14195 /// source is constant so it does not need to be loaded. 14196 /// It returns EVT::Other if the type should be determined using generic 14197 /// target-independent logic. 14198 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 14199 unsigned DstAlign, unsigned SrcAlign, 14200 bool IsMemset, bool ZeroMemset, 14201 bool MemcpyStrSrc, 14202 MachineFunction &MF) const { 14203 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14204 const Function &F = MF.getFunction(); 14205 // When expanding a memset, require at least two QPX instructions to cover 14206 // the cost of loading the value to be stored from the constant pool. 14207 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14208 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14209 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 14210 return MVT::v4f64; 14211 } 14212 14213 // We should use Altivec/VSX loads and stores when available. For unaligned 14214 // addresses, unaligned VSX loads are only fast starting with the P8. 14215 if (Subtarget.hasAltivec() && Size >= 16 && 14216 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14217 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14218 return MVT::v4i32; 14219 } 14220 14221 if (Subtarget.isPPC64()) { 14222 return MVT::i64; 14223 } 14224 14225 return MVT::i32; 14226 } 14227 14228 /// Returns true if it is beneficial to convert a load of a constant 14229 /// to just the constant itself. 14230 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14231 Type *Ty) const { 14232 assert(Ty->isIntegerTy()); 14233 14234 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14235 return !(BitSize == 0 || BitSize > 64); 14236 } 14237 14238 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14239 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14240 return false; 14241 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14242 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14243 return NumBits1 == 64 && NumBits2 == 32; 14244 } 14245 14246 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14247 if (!VT1.isInteger() || !VT2.isInteger()) 14248 return false; 14249 unsigned NumBits1 = VT1.getSizeInBits(); 14250 unsigned NumBits2 = VT2.getSizeInBits(); 14251 return NumBits1 == 64 && NumBits2 == 32; 14252 } 14253 14254 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14255 // Generally speaking, zexts are not free, but they are free when they can be 14256 // folded with other operations. 14257 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14258 EVT MemVT = LD->getMemoryVT(); 14259 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14260 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14261 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14262 LD->getExtensionType() == ISD::ZEXTLOAD)) 14263 return true; 14264 } 14265 14266 // FIXME: Add other cases... 14267 // - 32-bit shifts with a zext to i64 14268 // - zext after ctlz, bswap, etc. 14269 // - zext after and by a constant mask 14270 14271 return TargetLowering::isZExtFree(Val, VT2); 14272 } 14273 14274 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14275 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14276 "invalid fpext types"); 14277 // Extending to float128 is not free. 14278 if (DestVT == MVT::f128) 14279 return false; 14280 return true; 14281 } 14282 14283 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14284 return isInt<16>(Imm) || isUInt<16>(Imm); 14285 } 14286 14287 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14288 return isInt<16>(Imm) || isUInt<16>(Imm); 14289 } 14290 14291 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14292 unsigned, 14293 unsigned, 14294 bool *Fast) const { 14295 if (DisablePPCUnaligned) 14296 return false; 14297 14298 // PowerPC supports unaligned memory access for simple non-vector types. 14299 // Although accessing unaligned addresses is not as efficient as accessing 14300 // aligned addresses, it is generally more efficient than manual expansion, 14301 // and generally only traps for software emulation when crossing page 14302 // boundaries. 14303 14304 if (!VT.isSimple()) 14305 return false; 14306 14307 if (VT.getSimpleVT().isVector()) { 14308 if (Subtarget.hasVSX()) { 14309 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14310 VT != MVT::v4f32 && VT != MVT::v4i32) 14311 return false; 14312 } else { 14313 return false; 14314 } 14315 } 14316 14317 if (VT == MVT::ppcf128) 14318 return false; 14319 14320 if (Fast) 14321 *Fast = true; 14322 14323 return true; 14324 } 14325 14326 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14327 VT = VT.getScalarType(); 14328 14329 if (!VT.isSimple()) 14330 return false; 14331 14332 switch (VT.getSimpleVT().SimpleTy) { 14333 case MVT::f32: 14334 case MVT::f64: 14335 return true; 14336 case MVT::f128: 14337 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14338 default: 14339 break; 14340 } 14341 14342 return false; 14343 } 14344 14345 const MCPhysReg * 14346 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14347 // LR is a callee-save register, but we must treat it as clobbered by any call 14348 // site. Hence we include LR in the scratch registers, which are in turn added 14349 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14350 // to CTR, which is used by any indirect call. 14351 static const MCPhysReg ScratchRegs[] = { 14352 PPC::X12, PPC::LR8, PPC::CTR8, 0 14353 }; 14354 14355 return ScratchRegs; 14356 } 14357 14358 unsigned PPCTargetLowering::getExceptionPointerRegister( 14359 const Constant *PersonalityFn) const { 14360 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14361 } 14362 14363 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14364 const Constant *PersonalityFn) const { 14365 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14366 } 14367 14368 bool 14369 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14370 EVT VT , unsigned DefinedValues) const { 14371 if (VT == MVT::v2i64) 14372 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14373 14374 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14375 return true; 14376 14377 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14378 } 14379 14380 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14381 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14382 return TargetLowering::getSchedulingPreference(N); 14383 14384 return Sched::ILP; 14385 } 14386 14387 // Create a fast isel object. 14388 FastISel * 14389 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14390 const TargetLibraryInfo *LibInfo) const { 14391 return PPC::createFastISel(FuncInfo, LibInfo); 14392 } 14393 14394 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14395 if (Subtarget.isDarwinABI()) return; 14396 if (!Subtarget.isPPC64()) return; 14397 14398 // Update IsSplitCSR in PPCFunctionInfo 14399 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14400 PFI->setIsSplitCSR(true); 14401 } 14402 14403 void PPCTargetLowering::insertCopiesSplitCSR( 14404 MachineBasicBlock *Entry, 14405 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14406 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14407 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14408 if (!IStart) 14409 return; 14410 14411 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14412 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14413 MachineBasicBlock::iterator MBBI = Entry->begin(); 14414 for (const MCPhysReg *I = IStart; *I; ++I) { 14415 const TargetRegisterClass *RC = nullptr; 14416 if (PPC::G8RCRegClass.contains(*I)) 14417 RC = &PPC::G8RCRegClass; 14418 else if (PPC::F8RCRegClass.contains(*I)) 14419 RC = &PPC::F8RCRegClass; 14420 else if (PPC::CRRCRegClass.contains(*I)) 14421 RC = &PPC::CRRCRegClass; 14422 else if (PPC::VRRCRegClass.contains(*I)) 14423 RC = &PPC::VRRCRegClass; 14424 else 14425 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14426 14427 unsigned NewVR = MRI->createVirtualRegister(RC); 14428 // Create copy from CSR to a virtual register. 14429 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14430 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14431 // nounwind. If we want to generalize this later, we may need to emit 14432 // CFI pseudo-instructions. 14433 assert(Entry->getParent()->getFunction().hasFnAttribute( 14434 Attribute::NoUnwind) && 14435 "Function should be nounwind in insertCopiesSplitCSR!"); 14436 Entry->addLiveIn(*I); 14437 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14438 .addReg(*I); 14439 14440 // Insert the copy-back instructions right before the terminator 14441 for (auto *Exit : Exits) 14442 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14443 TII->get(TargetOpcode::COPY), *I) 14444 .addReg(NewVR); 14445 } 14446 } 14447 14448 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14449 bool PPCTargetLowering::useLoadStackGuardNode() const { 14450 if (!Subtarget.isTargetLinux()) 14451 return TargetLowering::useLoadStackGuardNode(); 14452 return true; 14453 } 14454 14455 // Override to disable global variable loading on Linux. 14456 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14457 if (!Subtarget.isTargetLinux()) 14458 return TargetLowering::insertSSPDeclarations(M); 14459 } 14460 14461 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14462 bool ForCodeSize) const { 14463 if (!VT.isSimple() || !Subtarget.hasVSX()) 14464 return false; 14465 14466 switch(VT.getSimpleVT().SimpleTy) { 14467 default: 14468 // For FP types that are currently not supported by PPC backend, return 14469 // false. Examples: f16, f80. 14470 return false; 14471 case MVT::f32: 14472 case MVT::f64: 14473 case MVT::ppcf128: 14474 return Imm.isPosZero(); 14475 } 14476 } 14477 14478 // For vector shift operation op, fold 14479 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14480 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14481 SelectionDAG &DAG) { 14482 SDValue N0 = N->getOperand(0); 14483 SDValue N1 = N->getOperand(1); 14484 EVT VT = N0.getValueType(); 14485 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14486 unsigned Opcode = N->getOpcode(); 14487 unsigned TargetOpcode; 14488 14489 switch (Opcode) { 14490 default: 14491 llvm_unreachable("Unexpected shift operation"); 14492 case ISD::SHL: 14493 TargetOpcode = PPCISD::SHL; 14494 break; 14495 case ISD::SRL: 14496 TargetOpcode = PPCISD::SRL; 14497 break; 14498 case ISD::SRA: 14499 TargetOpcode = PPCISD::SRA; 14500 break; 14501 } 14502 14503 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14504 N1->getOpcode() == ISD::AND) 14505 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14506 if (Mask->getZExtValue() == OpSizeInBits - 1) 14507 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14508 14509 return SDValue(); 14510 } 14511 14512 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14513 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14514 return Value; 14515 14516 SDValue N0 = N->getOperand(0); 14517 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14518 if (!Subtarget.isISA3_0() || 14519 N0.getOpcode() != ISD::SIGN_EXTEND || 14520 N0.getOperand(0).getValueType() != MVT::i32 || 14521 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14522 return SDValue(); 14523 14524 // We can't save an operation here if the value is already extended, and 14525 // the existing shift is easier to combine. 14526 SDValue ExtsSrc = N0.getOperand(0); 14527 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14528 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14529 return SDValue(); 14530 14531 SDLoc DL(N0); 14532 SDValue ShiftBy = SDValue(CN1, 0); 14533 // We want the shift amount to be i32 on the extswli, but the shift could 14534 // have an i64. 14535 if (ShiftBy.getValueType() == MVT::i64) 14536 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14537 14538 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14539 ShiftBy); 14540 } 14541 14542 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14543 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14544 return Value; 14545 14546 return SDValue(); 14547 } 14548 14549 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14550 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14551 return Value; 14552 14553 return SDValue(); 14554 } 14555 14556 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14557 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14558 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14559 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14560 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14561 const PPCSubtarget &Subtarget) { 14562 if (!Subtarget.isPPC64()) 14563 return SDValue(); 14564 14565 SDValue LHS = N->getOperand(0); 14566 SDValue RHS = N->getOperand(1); 14567 14568 auto isZextOfCompareWithConstant = [](SDValue Op) { 14569 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 14570 Op.getValueType() != MVT::i64) 14571 return false; 14572 14573 SDValue Cmp = Op.getOperand(0); 14574 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 14575 Cmp.getOperand(0).getValueType() != MVT::i64) 14576 return false; 14577 14578 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 14579 int64_t NegConstant = 0 - Constant->getSExtValue(); 14580 // Due to the limitations of the addi instruction, 14581 // -C is required to be [-32768, 32767]. 14582 return isInt<16>(NegConstant); 14583 } 14584 14585 return false; 14586 }; 14587 14588 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 14589 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 14590 14591 // If there is a pattern, canonicalize a zext operand to the RHS. 14592 if (LHSHasPattern && !RHSHasPattern) 14593 std::swap(LHS, RHS); 14594 else if (!LHSHasPattern && !RHSHasPattern) 14595 return SDValue(); 14596 14597 SDLoc DL(N); 14598 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 14599 SDValue Cmp = RHS.getOperand(0); 14600 SDValue Z = Cmp.getOperand(0); 14601 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 14602 14603 assert(Constant && "Constant Should not be a null pointer."); 14604 int64_t NegConstant = 0 - Constant->getSExtValue(); 14605 14606 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 14607 default: break; 14608 case ISD::SETNE: { 14609 // when C == 0 14610 // --> addze X, (addic Z, -1).carry 14611 // / 14612 // add X, (zext(setne Z, C))-- 14613 // \ when -32768 <= -C <= 32767 && C != 0 14614 // --> addze X, (addic (addi Z, -C), -1).carry 14615 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14616 DAG.getConstant(NegConstant, DL, MVT::i64)); 14617 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14618 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14619 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 14620 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14621 SDValue(Addc.getNode(), 1)); 14622 } 14623 case ISD::SETEQ: { 14624 // when C == 0 14625 // --> addze X, (subfic Z, 0).carry 14626 // / 14627 // add X, (zext(sete Z, C))-- 14628 // \ when -32768 <= -C <= 32767 && C != 0 14629 // --> addze X, (subfic (addi Z, -C), 0).carry 14630 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 14631 DAG.getConstant(NegConstant, DL, MVT::i64)); 14632 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 14633 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 14634 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 14635 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 14636 SDValue(Subc.getNode(), 1)); 14637 } 14638 } 14639 14640 return SDValue(); 14641 } 14642 14643 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 14644 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 14645 return Value; 14646 14647 return SDValue(); 14648 } 14649 14650 // Detect TRUNCATE operations on bitcasts of float128 values. 14651 // What we are looking for here is the situtation where we extract a subset 14652 // of bits from a 128 bit float. 14653 // This can be of two forms: 14654 // 1) BITCAST of f128 feeding TRUNCATE 14655 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 14656 // The reason this is required is because we do not have a legal i128 type 14657 // and so we want to prevent having to store the f128 and then reload part 14658 // of it. 14659 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 14660 DAGCombinerInfo &DCI) const { 14661 // If we are using CRBits then try that first. 14662 if (Subtarget.useCRBits()) { 14663 // Check if CRBits did anything and return that if it did. 14664 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 14665 return CRTruncValue; 14666 } 14667 14668 SDLoc dl(N); 14669 SDValue Op0 = N->getOperand(0); 14670 14671 // Looking for a truncate of i128 to i64. 14672 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 14673 return SDValue(); 14674 14675 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 14676 14677 // SRL feeding TRUNCATE. 14678 if (Op0.getOpcode() == ISD::SRL) { 14679 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 14680 // The right shift has to be by 64 bits. 14681 if (!ConstNode || ConstNode->getZExtValue() != 64) 14682 return SDValue(); 14683 14684 // Switch the element number to extract. 14685 EltToExtract = EltToExtract ? 0 : 1; 14686 // Update Op0 past the SRL. 14687 Op0 = Op0.getOperand(0); 14688 } 14689 14690 // BITCAST feeding a TRUNCATE possibly via SRL. 14691 if (Op0.getOpcode() == ISD::BITCAST && 14692 Op0.getValueType() == MVT::i128 && 14693 Op0.getOperand(0).getValueType() == MVT::f128) { 14694 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 14695 return DCI.DAG.getNode( 14696 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 14697 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 14698 } 14699 return SDValue(); 14700 } 14701 14702 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 14703 SelectionDAG &DAG = DCI.DAG; 14704 14705 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 14706 if (!ConstOpOrElement) 14707 return SDValue(); 14708 14709 // An imul is usually smaller than the alternative sequence for legal type. 14710 if (DAG.getMachineFunction().getFunction().hasMinSize() && 14711 isOperationLegal(ISD::MUL, N->getValueType(0))) 14712 return SDValue(); 14713 14714 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 14715 switch (this->Subtarget.getDarwinDirective()) { 14716 default: 14717 // TODO: enhance the condition for subtarget before pwr8 14718 return false; 14719 case PPC::DIR_PWR8: 14720 // type mul add shl 14721 // scalar 4 1 1 14722 // vector 7 2 2 14723 return true; 14724 case PPC::DIR_PWR9: 14725 // type mul add shl 14726 // scalar 5 2 2 14727 // vector 7 2 2 14728 14729 // The cycle RATIO of related operations are showed as a table above. 14730 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 14731 // scalar and vector type. For 2 instrs patterns, add/sub + shl 14732 // are 4, it is always profitable; but for 3 instrs patterns 14733 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 14734 // So we should only do it for vector type. 14735 return IsAddOne && IsNeg ? VT.isVector() : true; 14736 } 14737 }; 14738 14739 EVT VT = N->getValueType(0); 14740 SDLoc DL(N); 14741 14742 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 14743 bool IsNeg = MulAmt.isNegative(); 14744 APInt MulAmtAbs = MulAmt.abs(); 14745 14746 if ((MulAmtAbs - 1).isPowerOf2()) { 14747 // (mul x, 2^N + 1) => (add (shl x, N), x) 14748 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 14749 14750 if (!IsProfitable(IsNeg, true, VT)) 14751 return SDValue(); 14752 14753 SDValue Op0 = N->getOperand(0); 14754 SDValue Op1 = 14755 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14756 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 14757 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 14758 14759 if (!IsNeg) 14760 return Res; 14761 14762 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 14763 } else if ((MulAmtAbs + 1).isPowerOf2()) { 14764 // (mul x, 2^N - 1) => (sub (shl x, N), x) 14765 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 14766 14767 if (!IsProfitable(IsNeg, false, VT)) 14768 return SDValue(); 14769 14770 SDValue Op0 = N->getOperand(0); 14771 SDValue Op1 = 14772 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 14773 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 14774 14775 if (!IsNeg) 14776 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 14777 else 14778 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 14779 14780 } else { 14781 return SDValue(); 14782 } 14783 } 14784 14785 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 14786 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 14787 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 14788 return false; 14789 14790 // If not a tail call then no need to proceed. 14791 if (!CI->isTailCall()) 14792 return false; 14793 14794 // If tail calls are disabled for the caller then we are done. 14795 const Function *Caller = CI->getParent()->getParent(); 14796 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 14797 if (Attr.getValueAsString() == "true") 14798 return false; 14799 14800 // If sibling calls have been disabled and tail-calls aren't guaranteed 14801 // there is no reason to duplicate. 14802 auto &TM = getTargetMachine(); 14803 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 14804 return false; 14805 14806 // Can't tail call a function called indirectly, or if it has variadic args. 14807 const Function *Callee = CI->getCalledFunction(); 14808 if (!Callee || Callee->isVarArg()) 14809 return false; 14810 14811 // Make sure the callee and caller calling conventions are eligible for tco. 14812 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 14813 CI->getCallingConv())) 14814 return false; 14815 14816 // If the function is local then we have a good chance at tail-calling it 14817 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 14818 } 14819 14820 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 14821 if (!Subtarget.hasVSX()) 14822 return false; 14823 if (Subtarget.hasP9Vector() && VT == MVT::f128) 14824 return true; 14825 return VT == MVT::f32 || VT == MVT::f64 || 14826 VT == MVT::v4f32 || VT == MVT::v2f64; 14827 } 14828 14829 bool PPCTargetLowering:: 14830 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 14831 const Value *Mask = AndI.getOperand(1); 14832 // If the mask is suitable for andi. or andis. we should sink the and. 14833 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 14834 // Can't handle constants wider than 64-bits. 14835 if (CI->getBitWidth() > 64) 14836 return false; 14837 int64_t ConstVal = CI->getZExtValue(); 14838 return isUInt<16>(ConstVal) || 14839 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 14840 } 14841 14842 // For non-constant masks, we can always use the record-form and. 14843 return true; 14844 } 14845 14846 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 14847 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 14848 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 14849 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 14850 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 14851 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 14852 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 14853 assert(Subtarget.hasP9Altivec() && 14854 "Only combine this when P9 altivec supported!"); 14855 EVT VT = N->getValueType(0); 14856 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14857 return SDValue(); 14858 14859 SelectionDAG &DAG = DCI.DAG; 14860 SDLoc dl(N); 14861 if (N->getOperand(0).getOpcode() == ISD::SUB) { 14862 // Even for signed integers, if it's known to be positive (as signed 14863 // integer) due to zero-extended inputs. 14864 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 14865 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 14866 if ((SubOpcd0 == ISD::ZERO_EXTEND || 14867 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 14868 (SubOpcd1 == ISD::ZERO_EXTEND || 14869 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 14870 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14871 N->getOperand(0)->getOperand(0), 14872 N->getOperand(0)->getOperand(1), 14873 DAG.getTargetConstant(0, dl, MVT::i32)); 14874 } 14875 14876 // For type v4i32, it can be optimized with xvnegsp + vabsduw 14877 if (N->getOperand(0).getValueType() == MVT::v4i32 && 14878 N->getOperand(0).hasOneUse()) { 14879 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 14880 N->getOperand(0)->getOperand(0), 14881 N->getOperand(0)->getOperand(1), 14882 DAG.getTargetConstant(1, dl, MVT::i32)); 14883 } 14884 } 14885 14886 return SDValue(); 14887 } 14888 14889 // For type v4i32/v8ii16/v16i8, transform 14890 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 14891 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 14892 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 14893 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 14894 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 14895 DAGCombinerInfo &DCI) const { 14896 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 14897 assert(Subtarget.hasP9Altivec() && 14898 "Only combine this when P9 altivec supported!"); 14899 14900 SelectionDAG &DAG = DCI.DAG; 14901 SDLoc dl(N); 14902 SDValue Cond = N->getOperand(0); 14903 SDValue TrueOpnd = N->getOperand(1); 14904 SDValue FalseOpnd = N->getOperand(2); 14905 EVT VT = N->getOperand(1).getValueType(); 14906 14907 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 14908 FalseOpnd.getOpcode() != ISD::SUB) 14909 return SDValue(); 14910 14911 // ABSD only available for type v4i32/v8i16/v16i8 14912 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 14913 return SDValue(); 14914 14915 // At least to save one more dependent computation 14916 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 14917 return SDValue(); 14918 14919 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 14920 14921 // Can only handle unsigned comparison here 14922 switch (CC) { 14923 default: 14924 return SDValue(); 14925 case ISD::SETUGT: 14926 case ISD::SETUGE: 14927 break; 14928 case ISD::SETULT: 14929 case ISD::SETULE: 14930 std::swap(TrueOpnd, FalseOpnd); 14931 break; 14932 } 14933 14934 SDValue CmpOpnd1 = Cond.getOperand(0); 14935 SDValue CmpOpnd2 = Cond.getOperand(1); 14936 14937 // SETCC CmpOpnd1 CmpOpnd2 cond 14938 // TrueOpnd = CmpOpnd1 - CmpOpnd2 14939 // FalseOpnd = CmpOpnd2 - CmpOpnd1 14940 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 14941 TrueOpnd.getOperand(1) == CmpOpnd2 && 14942 FalseOpnd.getOperand(0) == CmpOpnd2 && 14943 FalseOpnd.getOperand(1) == CmpOpnd1) { 14944 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 14945 CmpOpnd1, CmpOpnd2, 14946 DAG.getTargetConstant(0, dl, MVT::i32)); 14947 } 14948 14949 return SDValue(); 14950 } 14951