1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/MachineValueType.h" 51 #include "llvm/CodeGen/RuntimeLibcalls.h" 52 #include "llvm/CodeGen/SelectionDAG.h" 53 #include "llvm/CodeGen/SelectionDAGNodes.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/CallSite.h" 56 #include "llvm/IR/CallingConv.h" 57 #include "llvm/IR/Constant.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/Function.h" 63 #include "llvm/IR/GlobalValue.h" 64 #include "llvm/IR/IRBuilder.h" 65 #include "llvm/IR/Instructions.h" 66 #include "llvm/IR/Intrinsics.h" 67 #include "llvm/IR/Module.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/Value.h" 71 #include "llvm/MC/MCExpr.h" 72 #include "llvm/MC/MCRegisterInfo.h" 73 #include "llvm/Support/AtomicOrdering.h" 74 #include "llvm/Support/BranchProbability.h" 75 #include "llvm/Support/Casting.h" 76 #include "llvm/Support/CodeGen.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Compiler.h" 79 #include "llvm/Support/Debug.h" 80 #include "llvm/Support/ErrorHandling.h" 81 #include "llvm/Support/Format.h" 82 #include "llvm/Support/KnownBits.h" 83 #include "llvm/Support/MathExtras.h" 84 #include "llvm/Support/raw_ostream.h" 85 #include "llvm/Target/TargetInstrInfo.h" 86 #include "llvm/Target/TargetLowering.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include "llvm/Target/TargetRegisterInfo.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 116 117 // FIXME: Remove this once the bug has been fixed! 118 extern cl::opt<bool> ANDIGlueBug; 119 120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 121 const PPCSubtarget &STI) 122 : TargetLowering(TM), Subtarget(STI) { 123 // Use _setjmp/_longjmp instead of setjmp/longjmp. 124 setUseUnderscoreSetJmp(true); 125 setUseUnderscoreLongJmp(true); 126 127 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 128 // arguments are at least 4/8 bytes aligned. 129 bool isPPC64 = Subtarget.isPPC64(); 130 setMinStackArgumentAlignment(isPPC64 ? 8:4); 131 132 // Set up the register classes. 133 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 134 if (!useSoftFloat()) { 135 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 136 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 137 } 138 139 // Match BITREVERSE to customized fast code sequence in the td file. 140 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 141 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 142 143 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 144 for (MVT VT : MVT::integer_valuetypes()) { 145 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 146 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 147 } 148 149 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 150 151 // PowerPC has pre-inc load and store's. 152 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 153 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 154 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 155 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 156 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 157 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 158 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 159 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 160 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 161 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 162 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 163 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 164 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 165 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 166 167 if (Subtarget.useCRBits()) { 168 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 169 170 if (isPPC64 || Subtarget.hasFPCVT()) { 171 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 172 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 173 isPPC64 ? MVT::i64 : MVT::i32); 174 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 175 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 176 isPPC64 ? MVT::i64 : MVT::i32); 177 } else { 178 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 179 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 180 } 181 182 // PowerPC does not support direct load/store of condition registers. 183 setOperationAction(ISD::LOAD, MVT::i1, Custom); 184 setOperationAction(ISD::STORE, MVT::i1, Custom); 185 186 // FIXME: Remove this once the ANDI glue bug is fixed: 187 if (ANDIGlueBug) 188 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 189 190 for (MVT VT : MVT::integer_valuetypes()) { 191 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 192 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 193 setTruncStoreAction(VT, MVT::i1, Expand); 194 } 195 196 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 197 } 198 199 // This is used in the ppcf128->int sequence. Note it has different semantics 200 // from FP_ROUND: that rounds to nearest, this rounds to zero. 201 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 202 203 // We do not currently implement these libm ops for PowerPC. 204 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 205 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 206 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 207 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 208 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 209 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 210 211 // PowerPC has no SREM/UREM instructions unless we are on P9 212 // On P9 we may use a hardware instruction to compute the remainder. 213 // The instructions are not legalized directly because in the cases where the 214 // result of both the remainder and the division is required it is more 215 // efficient to compute the remainder from the result of the division rather 216 // than use the remainder instruction. 217 if (Subtarget.isISA3_0()) { 218 setOperationAction(ISD::SREM, MVT::i32, Custom); 219 setOperationAction(ISD::UREM, MVT::i32, Custom); 220 setOperationAction(ISD::SREM, MVT::i64, Custom); 221 setOperationAction(ISD::UREM, MVT::i64, Custom); 222 } else { 223 setOperationAction(ISD::SREM, MVT::i32, Expand); 224 setOperationAction(ISD::UREM, MVT::i32, Expand); 225 setOperationAction(ISD::SREM, MVT::i64, Expand); 226 setOperationAction(ISD::UREM, MVT::i64, Expand); 227 } 228 229 if (Subtarget.hasP9Vector()) { 230 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 231 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 232 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 233 } 234 235 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 236 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 237 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 238 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 239 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 240 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 241 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 242 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 243 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 244 245 // We don't support sin/cos/sqrt/fmod/pow 246 setOperationAction(ISD::FSIN , MVT::f64, Expand); 247 setOperationAction(ISD::FCOS , MVT::f64, Expand); 248 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 249 setOperationAction(ISD::FREM , MVT::f64, Expand); 250 setOperationAction(ISD::FPOW , MVT::f64, Expand); 251 setOperationAction(ISD::FMA , MVT::f64, Legal); 252 setOperationAction(ISD::FSIN , MVT::f32, Expand); 253 setOperationAction(ISD::FCOS , MVT::f32, Expand); 254 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 255 setOperationAction(ISD::FREM , MVT::f32, Expand); 256 setOperationAction(ISD::FPOW , MVT::f32, Expand); 257 setOperationAction(ISD::FMA , MVT::f32, Legal); 258 259 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 260 261 // If we're enabling GP optimizations, use hardware square root 262 if (!Subtarget.hasFSQRT() && 263 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 264 Subtarget.hasFRE())) 265 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 266 267 if (!Subtarget.hasFSQRT() && 268 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 269 Subtarget.hasFRES())) 270 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 271 272 if (Subtarget.hasFCPSGN()) { 273 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 274 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 275 } else { 276 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 277 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 278 } 279 280 if (Subtarget.hasFPRND()) { 281 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 282 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 283 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 284 setOperationAction(ISD::FROUND, MVT::f64, Legal); 285 286 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 287 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 288 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 289 setOperationAction(ISD::FROUND, MVT::f32, Legal); 290 } 291 292 // PowerPC does not have BSWAP 293 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 294 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 295 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 296 if (Subtarget.isISA3_0()) { 297 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 298 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 299 } else { 300 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 301 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 302 } 303 304 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 305 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 306 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 307 } else { 308 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 309 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 310 } 311 312 // PowerPC does not have ROTR 313 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 314 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 315 316 if (!Subtarget.useCRBits()) { 317 // PowerPC does not have Select 318 setOperationAction(ISD::SELECT, MVT::i32, Expand); 319 setOperationAction(ISD::SELECT, MVT::i64, Expand); 320 setOperationAction(ISD::SELECT, MVT::f32, Expand); 321 setOperationAction(ISD::SELECT, MVT::f64, Expand); 322 } 323 324 // PowerPC wants to turn select_cc of FP into fsel when possible. 325 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 326 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 327 328 // PowerPC wants to optimize integer setcc a bit 329 if (!Subtarget.useCRBits()) 330 setOperationAction(ISD::SETCC, MVT::i32, Custom); 331 332 // PowerPC does not have BRCOND which requires SetCC 333 if (!Subtarget.useCRBits()) 334 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 335 336 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 337 338 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 339 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 340 341 // PowerPC does not have [U|S]INT_TO_FP 342 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 343 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 344 345 if (Subtarget.hasDirectMove() && isPPC64) { 346 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 347 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 348 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 349 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 350 } else { 351 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 352 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 353 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 354 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 355 } 356 357 // We cannot sextinreg(i1). Expand to shifts. 358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 359 360 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 361 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 362 // support continuation, user-level threading, and etc.. As a result, no 363 // other SjLj exception interfaces are implemented and please don't build 364 // your own exception handling based on them. 365 // LLVM/Clang supports zero-cost DWARF exception handling. 366 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 367 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 368 369 // We want to legalize GlobalAddress and ConstantPool nodes into the 370 // appropriate instructions to materialize the address. 371 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 372 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 373 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 374 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 375 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 376 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 377 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 378 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 379 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 380 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 381 382 // TRAP is legal. 383 setOperationAction(ISD::TRAP, MVT::Other, Legal); 384 385 // TRAMPOLINE is custom lowered. 386 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 387 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 388 389 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 390 setOperationAction(ISD::VASTART , MVT::Other, Custom); 391 392 if (Subtarget.isSVR4ABI()) { 393 if (isPPC64) { 394 // VAARG always uses double-word chunks, so promote anything smaller. 395 setOperationAction(ISD::VAARG, MVT::i1, Promote); 396 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 397 setOperationAction(ISD::VAARG, MVT::i8, Promote); 398 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 399 setOperationAction(ISD::VAARG, MVT::i16, Promote); 400 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 401 setOperationAction(ISD::VAARG, MVT::i32, Promote); 402 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 403 setOperationAction(ISD::VAARG, MVT::Other, Expand); 404 } else { 405 // VAARG is custom lowered with the 32-bit SVR4 ABI. 406 setOperationAction(ISD::VAARG, MVT::Other, Custom); 407 setOperationAction(ISD::VAARG, MVT::i64, Custom); 408 } 409 } else 410 setOperationAction(ISD::VAARG, MVT::Other, Expand); 411 412 if (Subtarget.isSVR4ABI() && !isPPC64) 413 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 414 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 415 else 416 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 417 418 // Use the default implementation. 419 setOperationAction(ISD::VAEND , MVT::Other, Expand); 420 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 421 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 422 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 423 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 424 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 425 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 426 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 427 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 428 429 // We want to custom lower some of our intrinsics. 430 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 431 432 // To handle counter-based loop conditions. 433 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 434 435 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 436 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 437 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 438 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 439 440 // Comparisons that require checking two conditions. 441 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 442 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 443 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 444 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 445 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 446 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 447 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 448 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 449 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 450 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 451 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 452 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 453 454 if (Subtarget.has64BitSupport()) { 455 // They also have instructions for converting between i64 and fp. 456 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 457 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 458 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 459 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 460 // This is just the low 32 bits of a (signed) fp->i64 conversion. 461 // We cannot do this with Promote because i64 is not a legal type. 462 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 463 464 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 465 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 466 } else { 467 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 468 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 469 } 470 471 // With the instructions enabled under FPCVT, we can do everything. 472 if (Subtarget.hasFPCVT()) { 473 if (Subtarget.has64BitSupport()) { 474 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 475 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 476 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 477 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 478 } 479 480 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 481 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 482 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 483 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 484 } 485 486 if (Subtarget.use64BitRegs()) { 487 // 64-bit PowerPC implementations can support i64 types directly 488 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 489 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 490 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 491 // 64-bit PowerPC wants to expand i128 shifts itself. 492 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 493 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 494 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 495 } else { 496 // 32-bit PowerPC wants to expand i64 shifts itself. 497 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 498 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 499 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 500 } 501 502 if (Subtarget.hasAltivec()) { 503 // First set operation action for all vector types to expand. Then we 504 // will selectively turn on ones that can be effectively codegen'd. 505 for (MVT VT : MVT::vector_valuetypes()) { 506 // add/sub are legal for all supported vector VT's. 507 setOperationAction(ISD::ADD, VT, Legal); 508 setOperationAction(ISD::SUB, VT, Legal); 509 510 // Vector instructions introduced in P8 511 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 512 setOperationAction(ISD::CTPOP, VT, Legal); 513 setOperationAction(ISD::CTLZ, VT, Legal); 514 } 515 else { 516 setOperationAction(ISD::CTPOP, VT, Expand); 517 setOperationAction(ISD::CTLZ, VT, Expand); 518 } 519 520 // Vector instructions introduced in P9 521 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 522 setOperationAction(ISD::CTTZ, VT, Legal); 523 else 524 setOperationAction(ISD::CTTZ, VT, Expand); 525 526 // We promote all shuffles to v16i8. 527 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 528 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 529 530 // We promote all non-typed operations to v4i32. 531 setOperationAction(ISD::AND , VT, Promote); 532 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 533 setOperationAction(ISD::OR , VT, Promote); 534 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 535 setOperationAction(ISD::XOR , VT, Promote); 536 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 537 setOperationAction(ISD::LOAD , VT, Promote); 538 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 539 setOperationAction(ISD::SELECT, VT, Promote); 540 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 541 setOperationAction(ISD::SELECT_CC, VT, Promote); 542 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 543 setOperationAction(ISD::STORE, VT, Promote); 544 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 545 546 // No other operations are legal. 547 setOperationAction(ISD::MUL , VT, Expand); 548 setOperationAction(ISD::SDIV, VT, Expand); 549 setOperationAction(ISD::SREM, VT, Expand); 550 setOperationAction(ISD::UDIV, VT, Expand); 551 setOperationAction(ISD::UREM, VT, Expand); 552 setOperationAction(ISD::FDIV, VT, Expand); 553 setOperationAction(ISD::FREM, VT, Expand); 554 setOperationAction(ISD::FNEG, VT, Expand); 555 setOperationAction(ISD::FSQRT, VT, Expand); 556 setOperationAction(ISD::FLOG, VT, Expand); 557 setOperationAction(ISD::FLOG10, VT, Expand); 558 setOperationAction(ISD::FLOG2, VT, Expand); 559 setOperationAction(ISD::FEXP, VT, Expand); 560 setOperationAction(ISD::FEXP2, VT, Expand); 561 setOperationAction(ISD::FSIN, VT, Expand); 562 setOperationAction(ISD::FCOS, VT, Expand); 563 setOperationAction(ISD::FABS, VT, Expand); 564 setOperationAction(ISD::FFLOOR, VT, Expand); 565 setOperationAction(ISD::FCEIL, VT, Expand); 566 setOperationAction(ISD::FTRUNC, VT, Expand); 567 setOperationAction(ISD::FRINT, VT, Expand); 568 setOperationAction(ISD::FNEARBYINT, VT, Expand); 569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 570 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 571 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 572 setOperationAction(ISD::MULHU, VT, Expand); 573 setOperationAction(ISD::MULHS, VT, Expand); 574 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 575 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 576 setOperationAction(ISD::UDIVREM, VT, Expand); 577 setOperationAction(ISD::SDIVREM, VT, Expand); 578 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 579 setOperationAction(ISD::FPOW, VT, Expand); 580 setOperationAction(ISD::BSWAP, VT, Expand); 581 setOperationAction(ISD::VSELECT, VT, Expand); 582 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 583 setOperationAction(ISD::ROTL, VT, Expand); 584 setOperationAction(ISD::ROTR, VT, Expand); 585 586 for (MVT InnerVT : MVT::vector_valuetypes()) { 587 setTruncStoreAction(VT, InnerVT, Expand); 588 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 589 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 590 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 591 } 592 } 593 594 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 595 // with merges, splats, etc. 596 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 597 598 setOperationAction(ISD::AND , MVT::v4i32, Legal); 599 setOperationAction(ISD::OR , MVT::v4i32, Legal); 600 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 601 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 602 setOperationAction(ISD::SELECT, MVT::v4i32, 603 Subtarget.useCRBits() ? Legal : Expand); 604 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 605 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 606 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 607 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 608 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 609 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 610 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 611 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 612 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 613 614 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 615 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 616 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 617 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 618 619 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 620 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 621 622 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 623 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 624 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 625 } 626 627 if (Subtarget.hasP8Altivec()) 628 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 629 else 630 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 631 632 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 633 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 634 635 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 637 638 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 639 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 640 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 641 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 642 643 // Altivec does not contain unordered floating-point compare instructions 644 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 645 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 646 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 647 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 648 649 if (Subtarget.hasVSX()) { 650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 652 if (Subtarget.hasP8Vector()) { 653 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 654 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 655 } 656 if (Subtarget.hasDirectMove() && isPPC64) { 657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 658 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 659 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 661 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 664 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 665 } 666 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 667 668 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 669 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 670 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 671 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 672 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 673 674 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 675 676 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 677 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 678 679 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 680 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 681 682 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 683 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 684 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 685 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 686 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 687 688 // Share the Altivec comparison restrictions. 689 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 690 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 691 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 692 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 693 694 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 695 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 696 697 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 698 699 if (Subtarget.hasP8Vector()) 700 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 701 702 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 703 704 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 705 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 706 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 707 708 if (Subtarget.hasP8Altivec()) { 709 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 710 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 711 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 712 713 // 128 bit shifts can be accomplished via 3 instructions for SHL and 714 // SRL, but not for SRA because of the instructions available: 715 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 716 // doing 717 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 718 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 719 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 720 721 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 722 } 723 else { 724 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 725 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 726 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 727 728 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 729 730 // VSX v2i64 only supports non-arithmetic operations. 731 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 732 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 733 } 734 735 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 736 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 737 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 738 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 739 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 741 742 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 743 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 744 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 745 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 746 747 // Vector operation legalization checks the result type of 748 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 749 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 750 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 751 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 752 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 753 754 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 755 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 756 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 757 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 758 759 if (Subtarget.hasDirectMove()) 760 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 761 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 762 763 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 764 } 765 766 if (Subtarget.hasP8Altivec()) { 767 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 768 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 769 } 770 771 if (Subtarget.hasP9Vector()) { 772 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 774 775 // 128 bit shifts can be accomplished via 3 instructions for SHL and 776 // SRL, but not for SRA because of the instructions available: 777 // VS{RL} and VS{RL}O. 778 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 779 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 780 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 781 } 782 } 783 784 if (Subtarget.hasQPX()) { 785 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 786 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 787 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 788 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 789 790 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 791 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 792 793 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 794 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 795 796 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 797 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 798 799 if (!Subtarget.useCRBits()) 800 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 801 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 802 803 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 804 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 805 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 806 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 807 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 808 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 809 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 810 811 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 812 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 813 814 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 815 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 816 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 817 818 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 819 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 820 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 821 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 822 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 823 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 824 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 825 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 826 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 827 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 828 829 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 830 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 831 832 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 833 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 834 835 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 836 837 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 838 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 839 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 840 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 841 842 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 843 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 844 845 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 846 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 847 848 if (!Subtarget.useCRBits()) 849 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 850 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 851 852 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 853 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 854 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 855 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 856 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 857 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 858 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 859 860 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 861 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 862 863 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 864 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 865 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 866 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 867 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 868 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 869 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 870 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 871 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 872 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 873 874 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 875 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 876 877 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 878 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 879 880 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 881 882 setOperationAction(ISD::AND , MVT::v4i1, Legal); 883 setOperationAction(ISD::OR , MVT::v4i1, Legal); 884 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 885 886 if (!Subtarget.useCRBits()) 887 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 888 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 889 890 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 891 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 892 893 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 894 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 895 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 896 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 897 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 899 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 900 901 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 902 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 903 904 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 905 906 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 907 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 908 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 909 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 910 911 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 912 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 913 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 914 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 915 916 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 917 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 918 919 // These need to set FE_INEXACT, and so cannot be vectorized here. 920 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 921 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 922 923 if (TM.Options.UnsafeFPMath) { 924 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 925 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 926 927 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 928 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 929 } else { 930 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 931 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 932 933 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 934 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 935 } 936 } 937 938 if (Subtarget.has64BitSupport()) 939 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 940 941 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 942 943 if (!isPPC64) { 944 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 945 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 946 } 947 948 setBooleanContents(ZeroOrOneBooleanContent); 949 950 if (Subtarget.hasAltivec()) { 951 // Altivec instructions set fields to all zeros or all ones. 952 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 953 } 954 955 if (!isPPC64) { 956 // These libcalls are not available in 32-bit. 957 setLibcallName(RTLIB::SHL_I128, nullptr); 958 setLibcallName(RTLIB::SRL_I128, nullptr); 959 setLibcallName(RTLIB::SRA_I128, nullptr); 960 } 961 962 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 963 964 // We have target-specific dag combine patterns for the following nodes: 965 setTargetDAGCombine(ISD::SHL); 966 setTargetDAGCombine(ISD::SRA); 967 setTargetDAGCombine(ISD::SRL); 968 setTargetDAGCombine(ISD::SINT_TO_FP); 969 setTargetDAGCombine(ISD::BUILD_VECTOR); 970 if (Subtarget.hasFPCVT()) 971 setTargetDAGCombine(ISD::UINT_TO_FP); 972 setTargetDAGCombine(ISD::LOAD); 973 setTargetDAGCombine(ISD::STORE); 974 setTargetDAGCombine(ISD::BR_CC); 975 if (Subtarget.useCRBits()) 976 setTargetDAGCombine(ISD::BRCOND); 977 setTargetDAGCombine(ISD::BSWAP); 978 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 979 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 980 setTargetDAGCombine(ISD::INTRINSIC_VOID); 981 982 setTargetDAGCombine(ISD::SIGN_EXTEND); 983 setTargetDAGCombine(ISD::ZERO_EXTEND); 984 setTargetDAGCombine(ISD::ANY_EXTEND); 985 986 if (Subtarget.useCRBits()) { 987 setTargetDAGCombine(ISD::TRUNCATE); 988 setTargetDAGCombine(ISD::SETCC); 989 setTargetDAGCombine(ISD::SELECT_CC); 990 } 991 992 // Use reciprocal estimates. 993 if (TM.Options.UnsafeFPMath) { 994 setTargetDAGCombine(ISD::FDIV); 995 setTargetDAGCombine(ISD::FSQRT); 996 } 997 998 // Darwin long double math library functions have $LDBL128 appended. 999 if (Subtarget.isDarwin()) { 1000 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1001 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1002 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1003 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1004 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1005 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1006 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1007 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1008 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1009 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1010 } 1011 1012 // With 32 condition bits, we don't need to sink (and duplicate) compares 1013 // aggressively in CodeGenPrep. 1014 if (Subtarget.useCRBits()) { 1015 setHasMultipleConditionRegisters(); 1016 setJumpIsExpensive(); 1017 } 1018 1019 setMinFunctionAlignment(2); 1020 if (Subtarget.isDarwin()) 1021 setPrefFunctionAlignment(4); 1022 1023 switch (Subtarget.getDarwinDirective()) { 1024 default: break; 1025 case PPC::DIR_970: 1026 case PPC::DIR_A2: 1027 case PPC::DIR_E500mc: 1028 case PPC::DIR_E5500: 1029 case PPC::DIR_PWR4: 1030 case PPC::DIR_PWR5: 1031 case PPC::DIR_PWR5X: 1032 case PPC::DIR_PWR6: 1033 case PPC::DIR_PWR6X: 1034 case PPC::DIR_PWR7: 1035 case PPC::DIR_PWR8: 1036 case PPC::DIR_PWR9: 1037 setPrefFunctionAlignment(4); 1038 setPrefLoopAlignment(4); 1039 break; 1040 } 1041 1042 if (Subtarget.enableMachineScheduler()) 1043 setSchedulingPreference(Sched::Source); 1044 else 1045 setSchedulingPreference(Sched::Hybrid); 1046 1047 computeRegisterProperties(STI.getRegisterInfo()); 1048 1049 // The Freescale cores do better with aggressive inlining of memcpy and 1050 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1051 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1052 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1053 MaxStoresPerMemset = 32; 1054 MaxStoresPerMemsetOptSize = 16; 1055 MaxStoresPerMemcpy = 32; 1056 MaxStoresPerMemcpyOptSize = 8; 1057 MaxStoresPerMemmove = 32; 1058 MaxStoresPerMemmoveOptSize = 8; 1059 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1060 // The A2 also benefits from (very) aggressive inlining of memcpy and 1061 // friends. The overhead of a the function call, even when warm, can be 1062 // over one hundred cycles. 1063 MaxStoresPerMemset = 128; 1064 MaxStoresPerMemcpy = 128; 1065 MaxStoresPerMemmove = 128; 1066 MaxLoadsPerMemcmp = 128; 1067 } else { 1068 MaxLoadsPerMemcmp = 8; 1069 MaxLoadsPerMemcmpOptSize = 4; 1070 } 1071 } 1072 1073 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1074 /// the desired ByVal argument alignment. 1075 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1076 unsigned MaxMaxAlign) { 1077 if (MaxAlign == MaxMaxAlign) 1078 return; 1079 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1080 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1081 MaxAlign = 32; 1082 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1083 MaxAlign = 16; 1084 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1085 unsigned EltAlign = 0; 1086 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1087 if (EltAlign > MaxAlign) 1088 MaxAlign = EltAlign; 1089 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1090 for (auto *EltTy : STy->elements()) { 1091 unsigned EltAlign = 0; 1092 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1093 if (EltAlign > MaxAlign) 1094 MaxAlign = EltAlign; 1095 if (MaxAlign == MaxMaxAlign) 1096 break; 1097 } 1098 } 1099 } 1100 1101 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1102 /// function arguments in the caller parameter area. 1103 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1104 const DataLayout &DL) const { 1105 // Darwin passes everything on 4 byte boundary. 1106 if (Subtarget.isDarwin()) 1107 return 4; 1108 1109 // 16byte and wider vectors are passed on 16byte boundary. 1110 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1111 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1112 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1113 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1114 return Align; 1115 } 1116 1117 bool PPCTargetLowering::useSoftFloat() const { 1118 return Subtarget.useSoftFloat(); 1119 } 1120 1121 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1122 switch ((PPCISD::NodeType)Opcode) { 1123 case PPCISD::FIRST_NUMBER: break; 1124 case PPCISD::FSEL: return "PPCISD::FSEL"; 1125 case PPCISD::FCFID: return "PPCISD::FCFID"; 1126 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1127 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1128 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1129 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1130 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1131 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1132 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1133 case PPCISD::FRE: return "PPCISD::FRE"; 1134 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1135 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1136 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1137 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1138 case PPCISD::VPERM: return "PPCISD::VPERM"; 1139 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1140 case PPCISD::XXINSERT: return "PPCISD::XXINSERT"; 1141 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1142 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1143 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1144 case PPCISD::CMPB: return "PPCISD::CMPB"; 1145 case PPCISD::Hi: return "PPCISD::Hi"; 1146 case PPCISD::Lo: return "PPCISD::Lo"; 1147 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1148 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1149 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1150 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1151 case PPCISD::SRL: return "PPCISD::SRL"; 1152 case PPCISD::SRA: return "PPCISD::SRA"; 1153 case PPCISD::SHL: return "PPCISD::SHL"; 1154 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1155 case PPCISD::CALL: return "PPCISD::CALL"; 1156 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1157 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1158 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1159 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1160 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1161 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1162 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1163 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1164 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1165 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1166 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1167 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1168 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1169 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1170 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1171 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1172 case PPCISD::VCMP: return "PPCISD::VCMP"; 1173 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1174 case PPCISD::LBRX: return "PPCISD::LBRX"; 1175 case PPCISD::STBRX: return "PPCISD::STBRX"; 1176 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1177 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1178 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1179 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1180 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1181 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1182 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1183 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1184 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1185 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1186 case PPCISD::BDZ: return "PPCISD::BDZ"; 1187 case PPCISD::MFFS: return "PPCISD::MFFS"; 1188 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1189 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1190 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1191 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1192 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1193 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1194 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1195 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1196 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1197 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1198 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1199 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1200 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1201 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1202 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1203 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1204 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1205 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1206 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1207 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1208 case PPCISD::SC: return "PPCISD::SC"; 1209 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1210 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1211 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1212 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1213 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1214 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1215 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1216 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1217 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1218 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1219 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1220 } 1221 return nullptr; 1222 } 1223 1224 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1225 EVT VT) const { 1226 if (!VT.isVector()) 1227 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1228 1229 if (Subtarget.hasQPX()) 1230 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1231 1232 return VT.changeVectorElementTypeToInteger(); 1233 } 1234 1235 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1236 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1237 return true; 1238 } 1239 1240 //===----------------------------------------------------------------------===// 1241 // Node matching predicates, for use by the tblgen matching code. 1242 //===----------------------------------------------------------------------===// 1243 1244 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1245 static bool isFloatingPointZero(SDValue Op) { 1246 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1247 return CFP->getValueAPF().isZero(); 1248 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1249 // Maybe this has already been legalized into the constant pool? 1250 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1251 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1252 return CFP->getValueAPF().isZero(); 1253 } 1254 return false; 1255 } 1256 1257 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1258 /// true if Op is undef or if it matches the specified value. 1259 static bool isConstantOrUndef(int Op, int Val) { 1260 return Op < 0 || Op == Val; 1261 } 1262 1263 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1264 /// VPKUHUM instruction. 1265 /// The ShuffleKind distinguishes between big-endian operations with 1266 /// two different inputs (0), either-endian operations with two identical 1267 /// inputs (1), and little-endian operations with two different inputs (2). 1268 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1269 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1270 SelectionDAG &DAG) { 1271 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1272 if (ShuffleKind == 0) { 1273 if (IsLE) 1274 return false; 1275 for (unsigned i = 0; i != 16; ++i) 1276 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1277 return false; 1278 } else if (ShuffleKind == 2) { 1279 if (!IsLE) 1280 return false; 1281 for (unsigned i = 0; i != 16; ++i) 1282 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1283 return false; 1284 } else if (ShuffleKind == 1) { 1285 unsigned j = IsLE ? 0 : 1; 1286 for (unsigned i = 0; i != 8; ++i) 1287 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1288 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1289 return false; 1290 } 1291 return true; 1292 } 1293 1294 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1295 /// VPKUWUM instruction. 1296 /// The ShuffleKind distinguishes between big-endian operations with 1297 /// two different inputs (0), either-endian operations with two identical 1298 /// inputs (1), and little-endian operations with two different inputs (2). 1299 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1300 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1301 SelectionDAG &DAG) { 1302 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1303 if (ShuffleKind == 0) { 1304 if (IsLE) 1305 return false; 1306 for (unsigned i = 0; i != 16; i += 2) 1307 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1308 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1309 return false; 1310 } else if (ShuffleKind == 2) { 1311 if (!IsLE) 1312 return false; 1313 for (unsigned i = 0; i != 16; i += 2) 1314 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1315 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1316 return false; 1317 } else if (ShuffleKind == 1) { 1318 unsigned j = IsLE ? 0 : 2; 1319 for (unsigned i = 0; i != 8; i += 2) 1320 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1321 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1322 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1323 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1324 return false; 1325 } 1326 return true; 1327 } 1328 1329 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1330 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1331 /// current subtarget. 1332 /// 1333 /// The ShuffleKind distinguishes between big-endian operations with 1334 /// two different inputs (0), either-endian operations with two identical 1335 /// inputs (1), and little-endian operations with two different inputs (2). 1336 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1337 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1338 SelectionDAG &DAG) { 1339 const PPCSubtarget& Subtarget = 1340 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1341 if (!Subtarget.hasP8Vector()) 1342 return false; 1343 1344 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1345 if (ShuffleKind == 0) { 1346 if (IsLE) 1347 return false; 1348 for (unsigned i = 0; i != 16; i += 4) 1349 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1350 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1351 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1352 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1353 return false; 1354 } else if (ShuffleKind == 2) { 1355 if (!IsLE) 1356 return false; 1357 for (unsigned i = 0; i != 16; i += 4) 1358 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1359 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1360 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1361 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1362 return false; 1363 } else if (ShuffleKind == 1) { 1364 unsigned j = IsLE ? 0 : 4; 1365 for (unsigned i = 0; i != 8; i += 4) 1366 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1367 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1368 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1369 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1370 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1371 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1372 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1373 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1374 return false; 1375 } 1376 return true; 1377 } 1378 1379 /// isVMerge - Common function, used to match vmrg* shuffles. 1380 /// 1381 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1382 unsigned LHSStart, unsigned RHSStart) { 1383 if (N->getValueType(0) != MVT::v16i8) 1384 return false; 1385 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1386 "Unsupported merge size!"); 1387 1388 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1389 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1390 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1391 LHSStart+j+i*UnitSize) || 1392 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1393 RHSStart+j+i*UnitSize)) 1394 return false; 1395 } 1396 return true; 1397 } 1398 1399 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1400 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1401 /// The ShuffleKind distinguishes between big-endian merges with two 1402 /// different inputs (0), either-endian merges with two identical inputs (1), 1403 /// and little-endian merges with two different inputs (2). For the latter, 1404 /// the input operands are swapped (see PPCInstrAltivec.td). 1405 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1406 unsigned ShuffleKind, SelectionDAG &DAG) { 1407 if (DAG.getDataLayout().isLittleEndian()) { 1408 if (ShuffleKind == 1) // unary 1409 return isVMerge(N, UnitSize, 0, 0); 1410 else if (ShuffleKind == 2) // swapped 1411 return isVMerge(N, UnitSize, 0, 16); 1412 else 1413 return false; 1414 } else { 1415 if (ShuffleKind == 1) // unary 1416 return isVMerge(N, UnitSize, 8, 8); 1417 else if (ShuffleKind == 0) // normal 1418 return isVMerge(N, UnitSize, 8, 24); 1419 else 1420 return false; 1421 } 1422 } 1423 1424 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1425 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1426 /// The ShuffleKind distinguishes between big-endian merges with two 1427 /// different inputs (0), either-endian merges with two identical inputs (1), 1428 /// and little-endian merges with two different inputs (2). For the latter, 1429 /// the input operands are swapped (see PPCInstrAltivec.td). 1430 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1431 unsigned ShuffleKind, SelectionDAG &DAG) { 1432 if (DAG.getDataLayout().isLittleEndian()) { 1433 if (ShuffleKind == 1) // unary 1434 return isVMerge(N, UnitSize, 8, 8); 1435 else if (ShuffleKind == 2) // swapped 1436 return isVMerge(N, UnitSize, 8, 24); 1437 else 1438 return false; 1439 } else { 1440 if (ShuffleKind == 1) // unary 1441 return isVMerge(N, UnitSize, 0, 0); 1442 else if (ShuffleKind == 0) // normal 1443 return isVMerge(N, UnitSize, 0, 16); 1444 else 1445 return false; 1446 } 1447 } 1448 1449 /** 1450 * \brief Common function used to match vmrgew and vmrgow shuffles 1451 * 1452 * The indexOffset determines whether to look for even or odd words in 1453 * the shuffle mask. This is based on the of the endianness of the target 1454 * machine. 1455 * - Little Endian: 1456 * - Use offset of 0 to check for odd elements 1457 * - Use offset of 4 to check for even elements 1458 * - Big Endian: 1459 * - Use offset of 0 to check for even elements 1460 * - Use offset of 4 to check for odd elements 1461 * A detailed description of the vector element ordering for little endian and 1462 * big endian can be found at 1463 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1464 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1465 * compiler differences mean to you 1466 * 1467 * The mask to the shuffle vector instruction specifies the indices of the 1468 * elements from the two input vectors to place in the result. The elements are 1469 * numbered in array-access order, starting with the first vector. These vectors 1470 * are always of type v16i8, thus each vector will contain 16 elements of size 1471 * 8. More info on the shuffle vector can be found in the 1472 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1473 * Language Reference. 1474 * 1475 * The RHSStartValue indicates whether the same input vectors are used (unary) 1476 * or two different input vectors are used, based on the following: 1477 * - If the instruction uses the same vector for both inputs, the range of the 1478 * indices will be 0 to 15. In this case, the RHSStart value passed should 1479 * be 0. 1480 * - If the instruction has two different vectors then the range of the 1481 * indices will be 0 to 31. In this case, the RHSStart value passed should 1482 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1483 * to 31 specify elements in the second vector). 1484 * 1485 * \param[in] N The shuffle vector SD Node to analyze 1486 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1487 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1488 * vector to the shuffle_vector instruction 1489 * \return true iff this shuffle vector represents an even or odd word merge 1490 */ 1491 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1492 unsigned RHSStartValue) { 1493 if (N->getValueType(0) != MVT::v16i8) 1494 return false; 1495 1496 for (unsigned i = 0; i < 2; ++i) 1497 for (unsigned j = 0; j < 4; ++j) 1498 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1499 i*RHSStartValue+j+IndexOffset) || 1500 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1501 i*RHSStartValue+j+IndexOffset+8)) 1502 return false; 1503 return true; 1504 } 1505 1506 /** 1507 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1508 * vmrgow instructions. 1509 * 1510 * \param[in] N The shuffle vector SD Node to analyze 1511 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1512 * \param[in] ShuffleKind Identify the type of merge: 1513 * - 0 = big-endian merge with two different inputs; 1514 * - 1 = either-endian merge with two identical inputs; 1515 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1516 * little-endian merges). 1517 * \param[in] DAG The current SelectionDAG 1518 * \return true iff this shuffle mask 1519 */ 1520 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1521 unsigned ShuffleKind, SelectionDAG &DAG) { 1522 if (DAG.getDataLayout().isLittleEndian()) { 1523 unsigned indexOffset = CheckEven ? 4 : 0; 1524 if (ShuffleKind == 1) // Unary 1525 return isVMerge(N, indexOffset, 0); 1526 else if (ShuffleKind == 2) // swapped 1527 return isVMerge(N, indexOffset, 16); 1528 else 1529 return false; 1530 } 1531 else { 1532 unsigned indexOffset = CheckEven ? 0 : 4; 1533 if (ShuffleKind == 1) // Unary 1534 return isVMerge(N, indexOffset, 0); 1535 else if (ShuffleKind == 0) // Normal 1536 return isVMerge(N, indexOffset, 16); 1537 else 1538 return false; 1539 } 1540 return false; 1541 } 1542 1543 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1544 /// amount, otherwise return -1. 1545 /// The ShuffleKind distinguishes between big-endian operations with two 1546 /// different inputs (0), either-endian operations with two identical inputs 1547 /// (1), and little-endian operations with two different inputs (2). For the 1548 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1549 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1550 SelectionDAG &DAG) { 1551 if (N->getValueType(0) != MVT::v16i8) 1552 return -1; 1553 1554 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1555 1556 // Find the first non-undef value in the shuffle mask. 1557 unsigned i; 1558 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1559 /*search*/; 1560 1561 if (i == 16) return -1; // all undef. 1562 1563 // Otherwise, check to see if the rest of the elements are consecutively 1564 // numbered from this value. 1565 unsigned ShiftAmt = SVOp->getMaskElt(i); 1566 if (ShiftAmt < i) return -1; 1567 1568 ShiftAmt -= i; 1569 bool isLE = DAG.getDataLayout().isLittleEndian(); 1570 1571 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1572 // Check the rest of the elements to see if they are consecutive. 1573 for (++i; i != 16; ++i) 1574 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1575 return -1; 1576 } else if (ShuffleKind == 1) { 1577 // Check the rest of the elements to see if they are consecutive. 1578 for (++i; i != 16; ++i) 1579 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1580 return -1; 1581 } else 1582 return -1; 1583 1584 if (isLE) 1585 ShiftAmt = 16 - ShiftAmt; 1586 1587 return ShiftAmt; 1588 } 1589 1590 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1591 /// specifies a splat of a single element that is suitable for input to 1592 /// VSPLTB/VSPLTH/VSPLTW. 1593 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1594 assert(N->getValueType(0) == MVT::v16i8 && 1595 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1596 1597 // The consecutive indices need to specify an element, not part of two 1598 // different elements. So abandon ship early if this isn't the case. 1599 if (N->getMaskElt(0) % EltSize != 0) 1600 return false; 1601 1602 // This is a splat operation if each element of the permute is the same, and 1603 // if the value doesn't reference the second vector. 1604 unsigned ElementBase = N->getMaskElt(0); 1605 1606 // FIXME: Handle UNDEF elements too! 1607 if (ElementBase >= 16) 1608 return false; 1609 1610 // Check that the indices are consecutive, in the case of a multi-byte element 1611 // splatted with a v16i8 mask. 1612 for (unsigned i = 1; i != EltSize; ++i) 1613 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1614 return false; 1615 1616 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1617 if (N->getMaskElt(i) < 0) continue; 1618 for (unsigned j = 0; j != EltSize; ++j) 1619 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1620 return false; 1621 } 1622 return true; 1623 } 1624 1625 /// Check that the mask is shuffling N byte elements. Within each N byte 1626 /// element of the mask, the indices could be either in increasing or 1627 /// decreasing order as long as they are consecutive. 1628 /// \param[in] N the shuffle vector SD Node to analyze 1629 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1630 /// Word/DoubleWord/QuadWord). 1631 /// \param[in] StepLen the delta indices number among the N byte element, if 1632 /// the mask is in increasing/decreasing order then it is 1/-1. 1633 /// \return true iff the mask is shuffling N byte elements. 1634 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1635 int StepLen) { 1636 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1637 "Unexpected element width."); 1638 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1639 1640 unsigned NumOfElem = 16 / Width; 1641 unsigned MaskVal[16]; // Width is never greater than 16 1642 for (unsigned i = 0; i < NumOfElem; ++i) { 1643 MaskVal[0] = N->getMaskElt(i * Width); 1644 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1645 return false; 1646 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1647 return false; 1648 } 1649 1650 for (unsigned int j = 1; j < Width; ++j) { 1651 MaskVal[j] = N->getMaskElt(i * Width + j); 1652 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1653 return false; 1654 } 1655 } 1656 } 1657 1658 return true; 1659 } 1660 1661 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1662 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1663 if (!isNByteElemShuffleMask(N, 4, 1)) 1664 return false; 1665 1666 // Now we look at mask elements 0,4,8,12 1667 unsigned M0 = N->getMaskElt(0) / 4; 1668 unsigned M1 = N->getMaskElt(4) / 4; 1669 unsigned M2 = N->getMaskElt(8) / 4; 1670 unsigned M3 = N->getMaskElt(12) / 4; 1671 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1672 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1673 1674 // Below, let H and L be arbitrary elements of the shuffle mask 1675 // where H is in the range [4,7] and L is in the range [0,3]. 1676 // H, 1, 2, 3 or L, 5, 6, 7 1677 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1678 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1679 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1680 InsertAtByte = IsLE ? 12 : 0; 1681 Swap = M0 < 4; 1682 return true; 1683 } 1684 // 0, H, 2, 3 or 4, L, 6, 7 1685 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1686 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1687 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1688 InsertAtByte = IsLE ? 8 : 4; 1689 Swap = M1 < 4; 1690 return true; 1691 } 1692 // 0, 1, H, 3 or 4, 5, L, 7 1693 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1694 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1695 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1696 InsertAtByte = IsLE ? 4 : 8; 1697 Swap = M2 < 4; 1698 return true; 1699 } 1700 // 0, 1, 2, H or 4, 5, 6, L 1701 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1702 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1703 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1704 InsertAtByte = IsLE ? 0 : 12; 1705 Swap = M3 < 4; 1706 return true; 1707 } 1708 1709 // If both vector operands for the shuffle are the same vector, the mask will 1710 // contain only elements from the first one and the second one will be undef. 1711 if (N->getOperand(1).isUndef()) { 1712 ShiftElts = 0; 1713 Swap = true; 1714 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1715 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1716 InsertAtByte = IsLE ? 12 : 0; 1717 return true; 1718 } 1719 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1720 InsertAtByte = IsLE ? 8 : 4; 1721 return true; 1722 } 1723 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1724 InsertAtByte = IsLE ? 4 : 8; 1725 return true; 1726 } 1727 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1728 InsertAtByte = IsLE ? 0 : 12; 1729 return true; 1730 } 1731 } 1732 1733 return false; 1734 } 1735 1736 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1737 bool &Swap, bool IsLE) { 1738 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1739 // Ensure each byte index of the word is consecutive. 1740 if (!isNByteElemShuffleMask(N, 4, 1)) 1741 return false; 1742 1743 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1744 unsigned M0 = N->getMaskElt(0) / 4; 1745 unsigned M1 = N->getMaskElt(4) / 4; 1746 unsigned M2 = N->getMaskElt(8) / 4; 1747 unsigned M3 = N->getMaskElt(12) / 4; 1748 1749 // If both vector operands for the shuffle are the same vector, the mask will 1750 // contain only elements from the first one and the second one will be undef. 1751 if (N->getOperand(1).isUndef()) { 1752 assert(M0 < 4 && "Indexing into an undef vector?"); 1753 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1754 return false; 1755 1756 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1757 Swap = false; 1758 return true; 1759 } 1760 1761 // Ensure each word index of the ShuffleVector Mask is consecutive. 1762 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1763 return false; 1764 1765 if (IsLE) { 1766 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1767 // Input vectors don't need to be swapped if the leading element 1768 // of the result is one of the 3 left elements of the second vector 1769 // (or if there is no shift to be done at all). 1770 Swap = false; 1771 ShiftElts = (8 - M0) % 8; 1772 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1773 // Input vectors need to be swapped if the leading element 1774 // of the result is one of the 3 left elements of the first vector 1775 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1776 Swap = true; 1777 ShiftElts = (4 - M0) % 4; 1778 } 1779 1780 return true; 1781 } else { // BE 1782 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1783 // Input vectors don't need to be swapped if the leading element 1784 // of the result is one of the 4 elements of the first vector. 1785 Swap = false; 1786 ShiftElts = M0; 1787 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1788 // Input vectors need to be swapped if the leading element 1789 // of the result is one of the 4 elements of the right vector. 1790 Swap = true; 1791 ShiftElts = M0 - 4; 1792 } 1793 1794 return true; 1795 } 1796 } 1797 1798 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1799 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1800 1801 if (!isNByteElemShuffleMask(N, Width, -1)) 1802 return false; 1803 1804 for (int i = 0; i < 16; i += Width) 1805 if (N->getMaskElt(i) != i + Width - 1) 1806 return false; 1807 1808 return true; 1809 } 1810 1811 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1812 return isXXBRShuffleMaskHelper(N, 2); 1813 } 1814 1815 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1816 return isXXBRShuffleMaskHelper(N, 4); 1817 } 1818 1819 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1820 return isXXBRShuffleMaskHelper(N, 8); 1821 } 1822 1823 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1824 return isXXBRShuffleMaskHelper(N, 16); 1825 } 1826 1827 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1828 /// if the inputs to the instruction should be swapped and set \p DM to the 1829 /// value for the immediate. 1830 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1831 /// AND element 0 of the result comes from the first input (LE) or second input 1832 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1833 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1834 /// mask. 1835 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1836 bool &Swap, bool IsLE) { 1837 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1838 1839 // Ensure each byte index of the double word is consecutive. 1840 if (!isNByteElemShuffleMask(N, 8, 1)) 1841 return false; 1842 1843 unsigned M0 = N->getMaskElt(0) / 8; 1844 unsigned M1 = N->getMaskElt(8) / 8; 1845 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1846 1847 // If both vector operands for the shuffle are the same vector, the mask will 1848 // contain only elements from the first one and the second one will be undef. 1849 if (N->getOperand(1).isUndef()) { 1850 if ((M0 | M1) < 2) { 1851 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1852 Swap = false; 1853 return true; 1854 } else 1855 return false; 1856 } 1857 1858 if (IsLE) { 1859 if (M0 > 1 && M1 < 2) { 1860 Swap = false; 1861 } else if (M0 < 2 && M1 > 1) { 1862 M0 = (M0 + 2) % 4; 1863 M1 = (M1 + 2) % 4; 1864 Swap = true; 1865 } else 1866 return false; 1867 1868 // Note: if control flow comes here that means Swap is already set above 1869 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 1870 return true; 1871 } else { // BE 1872 if (M0 < 2 && M1 > 1) { 1873 Swap = false; 1874 } else if (M0 > 1 && M1 < 2) { 1875 M0 = (M0 + 2) % 4; 1876 M1 = (M1 + 2) % 4; 1877 Swap = true; 1878 } else 1879 return false; 1880 1881 // Note: if control flow comes here that means Swap is already set above 1882 DM = (M0 << 1) + (M1 & 1); 1883 return true; 1884 } 1885 } 1886 1887 1888 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1889 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1890 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1891 SelectionDAG &DAG) { 1892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1893 assert(isSplatShuffleMask(SVOp, EltSize)); 1894 if (DAG.getDataLayout().isLittleEndian()) 1895 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1896 else 1897 return SVOp->getMaskElt(0) / EltSize; 1898 } 1899 1900 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1901 /// by using a vspltis[bhw] instruction of the specified element size, return 1902 /// the constant being splatted. The ByteSize field indicates the number of 1903 /// bytes of each element [124] -> [bhw]. 1904 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1905 SDValue OpVal(nullptr, 0); 1906 1907 // If ByteSize of the splat is bigger than the element size of the 1908 // build_vector, then we have a case where we are checking for a splat where 1909 // multiple elements of the buildvector are folded together into a single 1910 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1911 unsigned EltSize = 16/N->getNumOperands(); 1912 if (EltSize < ByteSize) { 1913 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1914 SDValue UniquedVals[4]; 1915 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1916 1917 // See if all of the elements in the buildvector agree across. 1918 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1919 if (N->getOperand(i).isUndef()) continue; 1920 // If the element isn't a constant, bail fully out. 1921 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1922 1923 if (!UniquedVals[i&(Multiple-1)].getNode()) 1924 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1925 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1926 return SDValue(); // no match. 1927 } 1928 1929 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1930 // either constant or undef values that are identical for each chunk. See 1931 // if these chunks can form into a larger vspltis*. 1932 1933 // Check to see if all of the leading entries are either 0 or -1. If 1934 // neither, then this won't fit into the immediate field. 1935 bool LeadingZero = true; 1936 bool LeadingOnes = true; 1937 for (unsigned i = 0; i != Multiple-1; ++i) { 1938 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1939 1940 LeadingZero &= isNullConstant(UniquedVals[i]); 1941 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1942 } 1943 // Finally, check the least significant entry. 1944 if (LeadingZero) { 1945 if (!UniquedVals[Multiple-1].getNode()) 1946 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1947 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1948 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1949 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1950 } 1951 if (LeadingOnes) { 1952 if (!UniquedVals[Multiple-1].getNode()) 1953 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1954 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1955 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1956 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1957 } 1958 1959 return SDValue(); 1960 } 1961 1962 // Check to see if this buildvec has a single non-undef value in its elements. 1963 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1964 if (N->getOperand(i).isUndef()) continue; 1965 if (!OpVal.getNode()) 1966 OpVal = N->getOperand(i); 1967 else if (OpVal != N->getOperand(i)) 1968 return SDValue(); 1969 } 1970 1971 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1972 1973 unsigned ValSizeInBytes = EltSize; 1974 uint64_t Value = 0; 1975 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1976 Value = CN->getZExtValue(); 1977 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1978 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1979 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1980 } 1981 1982 // If the splat value is larger than the element value, then we can never do 1983 // this splat. The only case that we could fit the replicated bits into our 1984 // immediate field for would be zero, and we prefer to use vxor for it. 1985 if (ValSizeInBytes < ByteSize) return SDValue(); 1986 1987 // If the element value is larger than the splat value, check if it consists 1988 // of a repeated bit pattern of size ByteSize. 1989 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 1990 return SDValue(); 1991 1992 // Properly sign extend the value. 1993 int MaskVal = SignExtend32(Value, ByteSize * 8); 1994 1995 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 1996 if (MaskVal == 0) return SDValue(); 1997 1998 // Finally, if this value fits in a 5 bit sext field, return it 1999 if (SignExtend32<5>(MaskVal) == MaskVal) 2000 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2001 return SDValue(); 2002 } 2003 2004 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2005 /// amount, otherwise return -1. 2006 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2007 EVT VT = N->getValueType(0); 2008 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2009 return -1; 2010 2011 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2012 2013 // Find the first non-undef value in the shuffle mask. 2014 unsigned i; 2015 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2016 /*search*/; 2017 2018 if (i == 4) return -1; // all undef. 2019 2020 // Otherwise, check to see if the rest of the elements are consecutively 2021 // numbered from this value. 2022 unsigned ShiftAmt = SVOp->getMaskElt(i); 2023 if (ShiftAmt < i) return -1; 2024 ShiftAmt -= i; 2025 2026 // Check the rest of the elements to see if they are consecutive. 2027 for (++i; i != 4; ++i) 2028 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2029 return -1; 2030 2031 return ShiftAmt; 2032 } 2033 2034 //===----------------------------------------------------------------------===// 2035 // Addressing Mode Selection 2036 //===----------------------------------------------------------------------===// 2037 2038 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2039 /// or 64-bit immediate, and if the value can be accurately represented as a 2040 /// sign extension from a 16-bit value. If so, this returns true and the 2041 /// immediate. 2042 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2043 if (!isa<ConstantSDNode>(N)) 2044 return false; 2045 2046 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2047 if (N->getValueType(0) == MVT::i32) 2048 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2049 else 2050 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2051 } 2052 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2053 return isIntS16Immediate(Op.getNode(), Imm); 2054 } 2055 2056 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2057 /// can be represented as an indexed [r+r] operation. Returns false if it 2058 /// can be more efficiently represented with [r+imm]. 2059 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2060 SDValue &Index, 2061 SelectionDAG &DAG) const { 2062 int16_t imm = 0; 2063 if (N.getOpcode() == ISD::ADD) { 2064 if (isIntS16Immediate(N.getOperand(1), imm)) 2065 return false; // r+i 2066 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2067 return false; // r+i 2068 2069 Base = N.getOperand(0); 2070 Index = N.getOperand(1); 2071 return true; 2072 } else if (N.getOpcode() == ISD::OR) { 2073 if (isIntS16Immediate(N.getOperand(1), imm)) 2074 return false; // r+i can fold it if we can. 2075 2076 // If this is an or of disjoint bitfields, we can codegen this as an add 2077 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2078 // disjoint. 2079 KnownBits LHSKnown, RHSKnown; 2080 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2081 2082 if (LHSKnown.Zero.getBoolValue()) { 2083 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2084 // If all of the bits are known zero on the LHS or RHS, the add won't 2085 // carry. 2086 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2087 Base = N.getOperand(0); 2088 Index = N.getOperand(1); 2089 return true; 2090 } 2091 } 2092 } 2093 2094 return false; 2095 } 2096 2097 // If we happen to be doing an i64 load or store into a stack slot that has 2098 // less than a 4-byte alignment, then the frame-index elimination may need to 2099 // use an indexed load or store instruction (because the offset may not be a 2100 // multiple of 4). The extra register needed to hold the offset comes from the 2101 // register scavenger, and it is possible that the scavenger will need to use 2102 // an emergency spill slot. As a result, we need to make sure that a spill slot 2103 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2104 // stack slot. 2105 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2106 // FIXME: This does not handle the LWA case. 2107 if (VT != MVT::i64) 2108 return; 2109 2110 // NOTE: We'll exclude negative FIs here, which come from argument 2111 // lowering, because there are no known test cases triggering this problem 2112 // using packed structures (or similar). We can remove this exclusion if 2113 // we find such a test case. The reason why this is so test-case driven is 2114 // because this entire 'fixup' is only to prevent crashes (from the 2115 // register scavenger) on not-really-valid inputs. For example, if we have: 2116 // %a = alloca i1 2117 // %b = bitcast i1* %a to i64* 2118 // store i64* a, i64 b 2119 // then the store should really be marked as 'align 1', but is not. If it 2120 // were marked as 'align 1' then the indexed form would have been 2121 // instruction-selected initially, and the problem this 'fixup' is preventing 2122 // won't happen regardless. 2123 if (FrameIdx < 0) 2124 return; 2125 2126 MachineFunction &MF = DAG.getMachineFunction(); 2127 MachineFrameInfo &MFI = MF.getFrameInfo(); 2128 2129 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2130 if (Align >= 4) 2131 return; 2132 2133 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2134 FuncInfo->setHasNonRISpills(); 2135 } 2136 2137 /// Returns true if the address N can be represented by a base register plus 2138 /// a signed 16-bit displacement [r+imm], and if it is not better 2139 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2140 /// displacements that are multiples of that value. 2141 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2142 SDValue &Base, 2143 SelectionDAG &DAG, 2144 unsigned Alignment) const { 2145 // FIXME dl should come from parent load or store, not from address 2146 SDLoc dl(N); 2147 // If this can be more profitably realized as r+r, fail. 2148 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2149 return false; 2150 2151 if (N.getOpcode() == ISD::ADD) { 2152 int16_t imm = 0; 2153 if (isIntS16Immediate(N.getOperand(1), imm) && 2154 (!Alignment || (imm % Alignment) == 0)) { 2155 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2156 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2157 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2158 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2159 } else { 2160 Base = N.getOperand(0); 2161 } 2162 return true; // [r+i] 2163 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2164 // Match LOAD (ADD (X, Lo(G))). 2165 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2166 && "Cannot handle constant offsets yet!"); 2167 Disp = N.getOperand(1).getOperand(0); // The global address. 2168 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2169 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2170 Disp.getOpcode() == ISD::TargetConstantPool || 2171 Disp.getOpcode() == ISD::TargetJumpTable); 2172 Base = N.getOperand(0); 2173 return true; // [&g+r] 2174 } 2175 } else if (N.getOpcode() == ISD::OR) { 2176 int16_t imm = 0; 2177 if (isIntS16Immediate(N.getOperand(1), imm) && 2178 (!Alignment || (imm % Alignment) == 0)) { 2179 // If this is an or of disjoint bitfields, we can codegen this as an add 2180 // (for better address arithmetic) if the LHS and RHS of the OR are 2181 // provably disjoint. 2182 KnownBits LHSKnown; 2183 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2184 2185 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2186 // If all of the bits are known zero on the LHS or RHS, the add won't 2187 // carry. 2188 if (FrameIndexSDNode *FI = 2189 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2190 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2191 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2192 } else { 2193 Base = N.getOperand(0); 2194 } 2195 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2196 return true; 2197 } 2198 } 2199 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2200 // Loading from a constant address. 2201 2202 // If this address fits entirely in a 16-bit sext immediate field, codegen 2203 // this as "d, 0" 2204 int16_t Imm; 2205 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2206 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2207 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2208 CN->getValueType(0)); 2209 return true; 2210 } 2211 2212 // Handle 32-bit sext immediates with LIS + addr mode. 2213 if ((CN->getValueType(0) == MVT::i32 || 2214 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2215 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2216 int Addr = (int)CN->getZExtValue(); 2217 2218 // Otherwise, break this down into an LIS + disp. 2219 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2220 2221 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2222 MVT::i32); 2223 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2224 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2225 return true; 2226 } 2227 } 2228 2229 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2230 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2231 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2232 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2233 } else 2234 Base = N; 2235 return true; // [r+0] 2236 } 2237 2238 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2239 /// represented as an indexed [r+r] operation. 2240 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2241 SDValue &Index, 2242 SelectionDAG &DAG) const { 2243 // Check to see if we can easily represent this as an [r+r] address. This 2244 // will fail if it thinks that the address is more profitably represented as 2245 // reg+imm, e.g. where imm = 0. 2246 if (SelectAddressRegReg(N, Base, Index, DAG)) 2247 return true; 2248 2249 // If the address is the result of an add, we will utilize the fact that the 2250 // address calculation includes an implicit add. However, we can reduce 2251 // register pressure if we do not materialize a constant just for use as the 2252 // index register. We only get rid of the add if it is not an add of a 2253 // value and a 16-bit signed constant and both have a single use. 2254 int16_t imm = 0; 2255 if (N.getOpcode() == ISD::ADD && 2256 (!isIntS16Immediate(N.getOperand(1), imm) || 2257 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2258 Base = N.getOperand(0); 2259 Index = N.getOperand(1); 2260 return true; 2261 } 2262 2263 // Otherwise, do it the hard way, using R0 as the base register. 2264 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2265 N.getValueType()); 2266 Index = N; 2267 return true; 2268 } 2269 2270 /// getPreIndexedAddressParts - returns true by value, base pointer and 2271 /// offset pointer and addressing mode by reference if the node's address 2272 /// can be legally represented as pre-indexed load / store address. 2273 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2274 SDValue &Offset, 2275 ISD::MemIndexedMode &AM, 2276 SelectionDAG &DAG) const { 2277 if (DisablePPCPreinc) return false; 2278 2279 bool isLoad = true; 2280 SDValue Ptr; 2281 EVT VT; 2282 unsigned Alignment; 2283 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2284 Ptr = LD->getBasePtr(); 2285 VT = LD->getMemoryVT(); 2286 Alignment = LD->getAlignment(); 2287 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2288 Ptr = ST->getBasePtr(); 2289 VT = ST->getMemoryVT(); 2290 Alignment = ST->getAlignment(); 2291 isLoad = false; 2292 } else 2293 return false; 2294 2295 // PowerPC doesn't have preinc load/store instructions for vectors (except 2296 // for QPX, which does have preinc r+r forms). 2297 if (VT.isVector()) { 2298 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2299 return false; 2300 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2301 AM = ISD::PRE_INC; 2302 return true; 2303 } 2304 } 2305 2306 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2307 // Common code will reject creating a pre-inc form if the base pointer 2308 // is a frame index, or if N is a store and the base pointer is either 2309 // the same as or a predecessor of the value being stored. Check for 2310 // those situations here, and try with swapped Base/Offset instead. 2311 bool Swap = false; 2312 2313 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2314 Swap = true; 2315 else if (!isLoad) { 2316 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2317 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2318 Swap = true; 2319 } 2320 2321 if (Swap) 2322 std::swap(Base, Offset); 2323 2324 AM = ISD::PRE_INC; 2325 return true; 2326 } 2327 2328 // LDU/STU can only handle immediates that are a multiple of 4. 2329 if (VT != MVT::i64) { 2330 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2331 return false; 2332 } else { 2333 // LDU/STU need an address with at least 4-byte alignment. 2334 if (Alignment < 4) 2335 return false; 2336 2337 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2338 return false; 2339 } 2340 2341 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2342 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2343 // sext i32 to i64 when addr mode is r+i. 2344 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2345 LD->getExtensionType() == ISD::SEXTLOAD && 2346 isa<ConstantSDNode>(Offset)) 2347 return false; 2348 } 2349 2350 AM = ISD::PRE_INC; 2351 return true; 2352 } 2353 2354 //===----------------------------------------------------------------------===// 2355 // LowerOperation implementation 2356 //===----------------------------------------------------------------------===// 2357 2358 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2359 /// and LoOpFlags to the target MO flags. 2360 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2361 unsigned &HiOpFlags, unsigned &LoOpFlags, 2362 const GlobalValue *GV = nullptr) { 2363 HiOpFlags = PPCII::MO_HA; 2364 LoOpFlags = PPCII::MO_LO; 2365 2366 // Don't use the pic base if not in PIC relocation model. 2367 if (IsPIC) { 2368 HiOpFlags |= PPCII::MO_PIC_FLAG; 2369 LoOpFlags |= PPCII::MO_PIC_FLAG; 2370 } 2371 2372 // If this is a reference to a global value that requires a non-lazy-ptr, make 2373 // sure that instruction lowering adds it. 2374 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2375 HiOpFlags |= PPCII::MO_NLP_FLAG; 2376 LoOpFlags |= PPCII::MO_NLP_FLAG; 2377 2378 if (GV->hasHiddenVisibility()) { 2379 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2380 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2381 } 2382 } 2383 } 2384 2385 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2386 SelectionDAG &DAG) { 2387 SDLoc DL(HiPart); 2388 EVT PtrVT = HiPart.getValueType(); 2389 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2390 2391 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2392 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2393 2394 // With PIC, the first instruction is actually "GR+hi(&G)". 2395 if (isPIC) 2396 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2397 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2398 2399 // Generate non-pic code that has direct accesses to the constant pool. 2400 // The address of the global is just (hi(&g)+lo(&g)). 2401 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2402 } 2403 2404 static void setUsesTOCBasePtr(MachineFunction &MF) { 2405 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2406 FuncInfo->setUsesTOCBasePtr(); 2407 } 2408 2409 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2410 setUsesTOCBasePtr(DAG.getMachineFunction()); 2411 } 2412 2413 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2414 SDValue GA) { 2415 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2416 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2417 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2418 2419 SDValue Ops[] = { GA, Reg }; 2420 return DAG.getMemIntrinsicNode( 2421 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2422 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true, 2423 false, 0); 2424 } 2425 2426 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2427 SelectionDAG &DAG) const { 2428 EVT PtrVT = Op.getValueType(); 2429 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2430 const Constant *C = CP->getConstVal(); 2431 2432 // 64-bit SVR4 ABI code is always position-independent. 2433 // The actual address of the GlobalValue is stored in the TOC. 2434 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2435 setUsesTOCBasePtr(DAG); 2436 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2437 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2438 } 2439 2440 unsigned MOHiFlag, MOLoFlag; 2441 bool IsPIC = isPositionIndependent(); 2442 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2443 2444 if (IsPIC && Subtarget.isSVR4ABI()) { 2445 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2446 PPCII::MO_PIC_FLAG); 2447 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2448 } 2449 2450 SDValue CPIHi = 2451 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2452 SDValue CPILo = 2453 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2454 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2455 } 2456 2457 // For 64-bit PowerPC, prefer the more compact relative encodings. 2458 // This trades 32 bits per jump table entry for one or two instructions 2459 // on the jump site. 2460 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2461 if (isJumpTableRelative()) 2462 return MachineJumpTableInfo::EK_LabelDifference32; 2463 2464 return TargetLowering::getJumpTableEncoding(); 2465 } 2466 2467 bool PPCTargetLowering::isJumpTableRelative() const { 2468 if (Subtarget.isPPC64()) 2469 return true; 2470 return TargetLowering::isJumpTableRelative(); 2471 } 2472 2473 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2474 SelectionDAG &DAG) const { 2475 if (!Subtarget.isPPC64()) 2476 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2477 2478 switch (getTargetMachine().getCodeModel()) { 2479 case CodeModel::Small: 2480 case CodeModel::Medium: 2481 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2482 default: 2483 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2484 getPointerTy(DAG.getDataLayout())); 2485 } 2486 } 2487 2488 const MCExpr * 2489 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2490 unsigned JTI, 2491 MCContext &Ctx) const { 2492 if (!Subtarget.isPPC64()) 2493 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2494 2495 switch (getTargetMachine().getCodeModel()) { 2496 case CodeModel::Small: 2497 case CodeModel::Medium: 2498 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2499 default: 2500 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2501 } 2502 } 2503 2504 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2505 EVT PtrVT = Op.getValueType(); 2506 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2507 2508 // 64-bit SVR4 ABI code is always position-independent. 2509 // The actual address of the GlobalValue is stored in the TOC. 2510 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2511 setUsesTOCBasePtr(DAG); 2512 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2513 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2514 } 2515 2516 unsigned MOHiFlag, MOLoFlag; 2517 bool IsPIC = isPositionIndependent(); 2518 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2519 2520 if (IsPIC && Subtarget.isSVR4ABI()) { 2521 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2522 PPCII::MO_PIC_FLAG); 2523 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2524 } 2525 2526 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2527 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2528 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2529 } 2530 2531 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2532 SelectionDAG &DAG) const { 2533 EVT PtrVT = Op.getValueType(); 2534 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2535 const BlockAddress *BA = BASDN->getBlockAddress(); 2536 2537 // 64-bit SVR4 ABI code is always position-independent. 2538 // The actual BlockAddress is stored in the TOC. 2539 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2540 setUsesTOCBasePtr(DAG); 2541 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2542 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2543 } 2544 2545 unsigned MOHiFlag, MOLoFlag; 2546 bool IsPIC = isPositionIndependent(); 2547 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2548 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2549 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2550 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2551 } 2552 2553 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2554 SelectionDAG &DAG) const { 2555 // FIXME: TLS addresses currently use medium model code sequences, 2556 // which is the most useful form. Eventually support for small and 2557 // large models could be added if users need it, at the cost of 2558 // additional complexity. 2559 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2560 if (DAG.getTarget().Options.EmulatedTLS) 2561 return LowerToTLSEmulatedModel(GA, DAG); 2562 2563 SDLoc dl(GA); 2564 const GlobalValue *GV = GA->getGlobal(); 2565 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2566 bool is64bit = Subtarget.isPPC64(); 2567 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 2568 PICLevel::Level picLevel = M->getPICLevel(); 2569 2570 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2571 2572 if (Model == TLSModel::LocalExec) { 2573 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2574 PPCII::MO_TPREL_HA); 2575 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2576 PPCII::MO_TPREL_LO); 2577 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2578 : DAG.getRegister(PPC::R2, MVT::i32); 2579 2580 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2581 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2582 } 2583 2584 if (Model == TLSModel::InitialExec) { 2585 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2586 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2587 PPCII::MO_TLS); 2588 SDValue GOTPtr; 2589 if (is64bit) { 2590 setUsesTOCBasePtr(DAG); 2591 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2592 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2593 PtrVT, GOTReg, TGA); 2594 } else 2595 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2596 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2597 PtrVT, TGA, GOTPtr); 2598 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2599 } 2600 2601 if (Model == TLSModel::GeneralDynamic) { 2602 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2603 SDValue GOTPtr; 2604 if (is64bit) { 2605 setUsesTOCBasePtr(DAG); 2606 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2607 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2608 GOTReg, TGA); 2609 } else { 2610 if (picLevel == PICLevel::SmallPIC) 2611 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2612 else 2613 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2614 } 2615 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2616 GOTPtr, TGA, TGA); 2617 } 2618 2619 if (Model == TLSModel::LocalDynamic) { 2620 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2621 SDValue GOTPtr; 2622 if (is64bit) { 2623 setUsesTOCBasePtr(DAG); 2624 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2625 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2626 GOTReg, TGA); 2627 } else { 2628 if (picLevel == PICLevel::SmallPIC) 2629 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2630 else 2631 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2632 } 2633 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2634 PtrVT, GOTPtr, TGA, TGA); 2635 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2636 PtrVT, TLSAddr, TGA); 2637 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2638 } 2639 2640 llvm_unreachable("Unknown TLS model!"); 2641 } 2642 2643 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2644 SelectionDAG &DAG) const { 2645 EVT PtrVT = Op.getValueType(); 2646 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2647 SDLoc DL(GSDN); 2648 const GlobalValue *GV = GSDN->getGlobal(); 2649 2650 // 64-bit SVR4 ABI code is always position-independent. 2651 // The actual address of the GlobalValue is stored in the TOC. 2652 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2653 setUsesTOCBasePtr(DAG); 2654 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2655 return getTOCEntry(DAG, DL, true, GA); 2656 } 2657 2658 unsigned MOHiFlag, MOLoFlag; 2659 bool IsPIC = isPositionIndependent(); 2660 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2661 2662 if (IsPIC && Subtarget.isSVR4ABI()) { 2663 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2664 GSDN->getOffset(), 2665 PPCII::MO_PIC_FLAG); 2666 return getTOCEntry(DAG, DL, false, GA); 2667 } 2668 2669 SDValue GAHi = 2670 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2671 SDValue GALo = 2672 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2673 2674 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2675 2676 // If the global reference is actually to a non-lazy-pointer, we have to do an 2677 // extra load to get the address of the global. 2678 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2679 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2680 return Ptr; 2681 } 2682 2683 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2684 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2685 SDLoc dl(Op); 2686 2687 if (Op.getValueType() == MVT::v2i64) { 2688 // When the operands themselves are v2i64 values, we need to do something 2689 // special because VSX has no underlying comparison operations for these. 2690 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2691 // Equality can be handled by casting to the legal type for Altivec 2692 // comparisons, everything else needs to be expanded. 2693 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2694 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2695 DAG.getSetCC(dl, MVT::v4i32, 2696 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2697 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2698 CC)); 2699 } 2700 2701 return SDValue(); 2702 } 2703 2704 // We handle most of these in the usual way. 2705 return Op; 2706 } 2707 2708 // If we're comparing for equality to zero, expose the fact that this is 2709 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2710 // fold the new nodes. 2711 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2712 return V; 2713 2714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2715 // Leave comparisons against 0 and -1 alone for now, since they're usually 2716 // optimized. FIXME: revisit this when we can custom lower all setcc 2717 // optimizations. 2718 if (C->isAllOnesValue() || C->isNullValue()) 2719 return SDValue(); 2720 } 2721 2722 // If we have an integer seteq/setne, turn it into a compare against zero 2723 // by xor'ing the rhs with the lhs, which is faster than setting a 2724 // condition register, reading it back out, and masking the correct bit. The 2725 // normal approach here uses sub to do this instead of xor. Using xor exposes 2726 // the result to other bit-twiddling opportunities. 2727 EVT LHSVT = Op.getOperand(0).getValueType(); 2728 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2729 EVT VT = Op.getValueType(); 2730 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2731 Op.getOperand(1)); 2732 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2733 } 2734 return SDValue(); 2735 } 2736 2737 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2738 SDNode *Node = Op.getNode(); 2739 EVT VT = Node->getValueType(0); 2740 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2741 SDValue InChain = Node->getOperand(0); 2742 SDValue VAListPtr = Node->getOperand(1); 2743 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2744 SDLoc dl(Node); 2745 2746 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2747 2748 // gpr_index 2749 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2750 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2751 InChain = GprIndex.getValue(1); 2752 2753 if (VT == MVT::i64) { 2754 // Check if GprIndex is even 2755 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2756 DAG.getConstant(1, dl, MVT::i32)); 2757 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2758 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2759 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2760 DAG.getConstant(1, dl, MVT::i32)); 2761 // Align GprIndex to be even if it isn't 2762 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2763 GprIndex); 2764 } 2765 2766 // fpr index is 1 byte after gpr 2767 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2768 DAG.getConstant(1, dl, MVT::i32)); 2769 2770 // fpr 2771 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2772 FprPtr, MachinePointerInfo(SV), MVT::i8); 2773 InChain = FprIndex.getValue(1); 2774 2775 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2776 DAG.getConstant(8, dl, MVT::i32)); 2777 2778 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2779 DAG.getConstant(4, dl, MVT::i32)); 2780 2781 // areas 2782 SDValue OverflowArea = 2783 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2784 InChain = OverflowArea.getValue(1); 2785 2786 SDValue RegSaveArea = 2787 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2788 InChain = RegSaveArea.getValue(1); 2789 2790 // select overflow_area if index > 8 2791 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2792 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2793 2794 // adjustment constant gpr_index * 4/8 2795 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2796 VT.isInteger() ? GprIndex : FprIndex, 2797 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2798 MVT::i32)); 2799 2800 // OurReg = RegSaveArea + RegConstant 2801 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2802 RegConstant); 2803 2804 // Floating types are 32 bytes into RegSaveArea 2805 if (VT.isFloatingPoint()) 2806 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2807 DAG.getConstant(32, dl, MVT::i32)); 2808 2809 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2810 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2811 VT.isInteger() ? GprIndex : FprIndex, 2812 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2813 MVT::i32)); 2814 2815 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2816 VT.isInteger() ? VAListPtr : FprPtr, 2817 MachinePointerInfo(SV), MVT::i8); 2818 2819 // determine if we should load from reg_save_area or overflow_area 2820 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2821 2822 // increase overflow_area by 4/8 if gpr/fpr > 8 2823 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2824 DAG.getConstant(VT.isInteger() ? 4 : 8, 2825 dl, MVT::i32)); 2826 2827 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2828 OverflowAreaPlusN); 2829 2830 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2831 MachinePointerInfo(), MVT::i32); 2832 2833 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2834 } 2835 2836 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2837 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2838 2839 // We have to copy the entire va_list struct: 2840 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2841 return DAG.getMemcpy(Op.getOperand(0), Op, 2842 Op.getOperand(1), Op.getOperand(2), 2843 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2844 false, MachinePointerInfo(), MachinePointerInfo()); 2845 } 2846 2847 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2848 SelectionDAG &DAG) const { 2849 return Op.getOperand(0); 2850 } 2851 2852 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2853 SelectionDAG &DAG) const { 2854 SDValue Chain = Op.getOperand(0); 2855 SDValue Trmp = Op.getOperand(1); // trampoline 2856 SDValue FPtr = Op.getOperand(2); // nested function 2857 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2858 SDLoc dl(Op); 2859 2860 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2861 bool isPPC64 = (PtrVT == MVT::i64); 2862 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2863 2864 TargetLowering::ArgListTy Args; 2865 TargetLowering::ArgListEntry Entry; 2866 2867 Entry.Ty = IntPtrTy; 2868 Entry.Node = Trmp; Args.push_back(Entry); 2869 2870 // TrampSize == (isPPC64 ? 48 : 40); 2871 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2872 isPPC64 ? MVT::i64 : MVT::i32); 2873 Args.push_back(Entry); 2874 2875 Entry.Node = FPtr; Args.push_back(Entry); 2876 Entry.Node = Nest; Args.push_back(Entry); 2877 2878 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2879 TargetLowering::CallLoweringInfo CLI(DAG); 2880 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2881 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2882 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2883 2884 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2885 return CallResult.second; 2886 } 2887 2888 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2889 MachineFunction &MF = DAG.getMachineFunction(); 2890 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2891 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2892 2893 SDLoc dl(Op); 2894 2895 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2896 // vastart just stores the address of the VarArgsFrameIndex slot into the 2897 // memory location argument. 2898 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2899 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2900 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2901 MachinePointerInfo(SV)); 2902 } 2903 2904 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2905 // We suppose the given va_list is already allocated. 2906 // 2907 // typedef struct { 2908 // char gpr; /* index into the array of 8 GPRs 2909 // * stored in the register save area 2910 // * gpr=0 corresponds to r3, 2911 // * gpr=1 to r4, etc. 2912 // */ 2913 // char fpr; /* index into the array of 8 FPRs 2914 // * stored in the register save area 2915 // * fpr=0 corresponds to f1, 2916 // * fpr=1 to f2, etc. 2917 // */ 2918 // char *overflow_arg_area; 2919 // /* location on stack that holds 2920 // * the next overflow argument 2921 // */ 2922 // char *reg_save_area; 2923 // /* where r3:r10 and f1:f8 (if saved) 2924 // * are stored 2925 // */ 2926 // } va_list[1]; 2927 2928 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2929 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2930 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2931 PtrVT); 2932 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2933 PtrVT); 2934 2935 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2936 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2937 2938 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2939 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2940 2941 uint64_t FPROffset = 1; 2942 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2943 2944 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2945 2946 // Store first byte : number of int regs 2947 SDValue firstStore = 2948 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2949 MachinePointerInfo(SV), MVT::i8); 2950 uint64_t nextOffset = FPROffset; 2951 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2952 ConstFPROffset); 2953 2954 // Store second byte : number of float regs 2955 SDValue secondStore = 2956 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2957 MachinePointerInfo(SV, nextOffset), MVT::i8); 2958 nextOffset += StackOffset; 2959 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2960 2961 // Store second word : arguments given on stack 2962 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2963 MachinePointerInfo(SV, nextOffset)); 2964 nextOffset += FrameOffset; 2965 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2966 2967 // Store third word : arguments given in registers 2968 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2969 MachinePointerInfo(SV, nextOffset)); 2970 } 2971 2972 #include "PPCGenCallingConv.inc" 2973 2974 // Function whose sole purpose is to kill compiler warnings 2975 // stemming from unused functions included from PPCGenCallingConv.inc. 2976 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2977 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2978 } 2979 2980 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2981 CCValAssign::LocInfo &LocInfo, 2982 ISD::ArgFlagsTy &ArgFlags, 2983 CCState &State) { 2984 return true; 2985 } 2986 2987 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2988 MVT &LocVT, 2989 CCValAssign::LocInfo &LocInfo, 2990 ISD::ArgFlagsTy &ArgFlags, 2991 CCState &State) { 2992 static const MCPhysReg ArgRegs[] = { 2993 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 2994 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 2995 }; 2996 const unsigned NumArgRegs = array_lengthof(ArgRegs); 2997 2998 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 2999 3000 // Skip one register if the first unallocated register has an even register 3001 // number and there are still argument registers available which have not been 3002 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3003 // need to skip a register if RegNum is odd. 3004 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3005 State.AllocateReg(ArgRegs[RegNum]); 3006 } 3007 3008 // Always return false here, as this function only makes sure that the first 3009 // unallocated register has an odd register number and does not actually 3010 // allocate a register for the current argument. 3011 return false; 3012 } 3013 3014 bool 3015 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3016 MVT &LocVT, 3017 CCValAssign::LocInfo &LocInfo, 3018 ISD::ArgFlagsTy &ArgFlags, 3019 CCState &State) { 3020 static const MCPhysReg ArgRegs[] = { 3021 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3022 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3023 }; 3024 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3025 3026 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3027 int RegsLeft = NumArgRegs - RegNum; 3028 3029 // Skip if there is not enough registers left for long double type (4 gpr regs 3030 // in soft float mode) and put long double argument on the stack. 3031 if (RegNum != NumArgRegs && RegsLeft < 4) { 3032 for (int i = 0; i < RegsLeft; i++) { 3033 State.AllocateReg(ArgRegs[RegNum + i]); 3034 } 3035 } 3036 3037 return false; 3038 } 3039 3040 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3041 MVT &LocVT, 3042 CCValAssign::LocInfo &LocInfo, 3043 ISD::ArgFlagsTy &ArgFlags, 3044 CCState &State) { 3045 static const MCPhysReg ArgRegs[] = { 3046 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3047 PPC::F8 3048 }; 3049 3050 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3051 3052 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3053 3054 // If there is only one Floating-point register left we need to put both f64 3055 // values of a split ppc_fp128 value on the stack. 3056 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3057 State.AllocateReg(ArgRegs[RegNum]); 3058 } 3059 3060 // Always return false here, as this function only makes sure that the two f64 3061 // values a ppc_fp128 value is split into are both passed in registers or both 3062 // passed on the stack and does not actually allocate a register for the 3063 // current argument. 3064 return false; 3065 } 3066 3067 /// FPR - The set of FP registers that should be allocated for arguments, 3068 /// on Darwin. 3069 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3070 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3071 PPC::F11, PPC::F12, PPC::F13}; 3072 3073 /// QFPR - The set of QPX registers that should be allocated for arguments. 3074 static const MCPhysReg QFPR[] = { 3075 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3076 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3077 3078 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3079 /// the stack. 3080 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3081 unsigned PtrByteSize) { 3082 unsigned ArgSize = ArgVT.getStoreSize(); 3083 if (Flags.isByVal()) 3084 ArgSize = Flags.getByValSize(); 3085 3086 // Round up to multiples of the pointer size, except for array members, 3087 // which are always packed. 3088 if (!Flags.isInConsecutiveRegs()) 3089 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3090 3091 return ArgSize; 3092 } 3093 3094 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3095 /// on the stack. 3096 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3097 ISD::ArgFlagsTy Flags, 3098 unsigned PtrByteSize) { 3099 unsigned Align = PtrByteSize; 3100 3101 // Altivec parameters are padded to a 16 byte boundary. 3102 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3103 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3104 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3105 ArgVT == MVT::v1i128) 3106 Align = 16; 3107 // QPX vector types stored in double-precision are padded to a 32 byte 3108 // boundary. 3109 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3110 Align = 32; 3111 3112 // ByVal parameters are aligned as requested. 3113 if (Flags.isByVal()) { 3114 unsigned BVAlign = Flags.getByValAlign(); 3115 if (BVAlign > PtrByteSize) { 3116 if (BVAlign % PtrByteSize != 0) 3117 llvm_unreachable( 3118 "ByVal alignment is not a multiple of the pointer size"); 3119 3120 Align = BVAlign; 3121 } 3122 } 3123 3124 // Array members are always packed to their original alignment. 3125 if (Flags.isInConsecutiveRegs()) { 3126 // If the array member was split into multiple registers, the first 3127 // needs to be aligned to the size of the full type. (Except for 3128 // ppcf128, which is only aligned as its f64 components.) 3129 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3130 Align = OrigVT.getStoreSize(); 3131 else 3132 Align = ArgVT.getStoreSize(); 3133 } 3134 3135 return Align; 3136 } 3137 3138 /// CalculateStackSlotUsed - Return whether this argument will use its 3139 /// stack slot (instead of being passed in registers). ArgOffset, 3140 /// AvailableFPRs, and AvailableVRs must hold the current argument 3141 /// position, and will be updated to account for this argument. 3142 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3143 ISD::ArgFlagsTy Flags, 3144 unsigned PtrByteSize, 3145 unsigned LinkageSize, 3146 unsigned ParamAreaSize, 3147 unsigned &ArgOffset, 3148 unsigned &AvailableFPRs, 3149 unsigned &AvailableVRs, bool HasQPX) { 3150 bool UseMemory = false; 3151 3152 // Respect alignment of argument on the stack. 3153 unsigned Align = 3154 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3155 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3156 // If there's no space left in the argument save area, we must 3157 // use memory (this check also catches zero-sized arguments). 3158 if (ArgOffset >= LinkageSize + ParamAreaSize) 3159 UseMemory = true; 3160 3161 // Allocate argument on the stack. 3162 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3163 if (Flags.isInConsecutiveRegsLast()) 3164 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3165 // If we overran the argument save area, we must use memory 3166 // (this check catches arguments passed partially in memory) 3167 if (ArgOffset > LinkageSize + ParamAreaSize) 3168 UseMemory = true; 3169 3170 // However, if the argument is actually passed in an FPR or a VR, 3171 // we don't use memory after all. 3172 if (!Flags.isByVal()) { 3173 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3174 // QPX registers overlap with the scalar FP registers. 3175 (HasQPX && (ArgVT == MVT::v4f32 || 3176 ArgVT == MVT::v4f64 || 3177 ArgVT == MVT::v4i1))) 3178 if (AvailableFPRs > 0) { 3179 --AvailableFPRs; 3180 return false; 3181 } 3182 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3183 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3184 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3185 ArgVT == MVT::v1i128) 3186 if (AvailableVRs > 0) { 3187 --AvailableVRs; 3188 return false; 3189 } 3190 } 3191 3192 return UseMemory; 3193 } 3194 3195 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3196 /// ensure minimum alignment required for target. 3197 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3198 unsigned NumBytes) { 3199 unsigned TargetAlign = Lowering->getStackAlignment(); 3200 unsigned AlignMask = TargetAlign - 1; 3201 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3202 return NumBytes; 3203 } 3204 3205 SDValue PPCTargetLowering::LowerFormalArguments( 3206 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3207 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3208 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3209 if (Subtarget.isSVR4ABI()) { 3210 if (Subtarget.isPPC64()) 3211 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3212 dl, DAG, InVals); 3213 else 3214 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3215 dl, DAG, InVals); 3216 } else { 3217 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3218 dl, DAG, InVals); 3219 } 3220 } 3221 3222 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3223 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3224 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3225 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3226 3227 // 32-bit SVR4 ABI Stack Frame Layout: 3228 // +-----------------------------------+ 3229 // +--> | Back chain | 3230 // | +-----------------------------------+ 3231 // | | Floating-point register save area | 3232 // | +-----------------------------------+ 3233 // | | General register save area | 3234 // | +-----------------------------------+ 3235 // | | CR save word | 3236 // | +-----------------------------------+ 3237 // | | VRSAVE save word | 3238 // | +-----------------------------------+ 3239 // | | Alignment padding | 3240 // | +-----------------------------------+ 3241 // | | Vector register save area | 3242 // | +-----------------------------------+ 3243 // | | Local variable space | 3244 // | +-----------------------------------+ 3245 // | | Parameter list area | 3246 // | +-----------------------------------+ 3247 // | | LR save word | 3248 // | +-----------------------------------+ 3249 // SP--> +--- | Back chain | 3250 // +-----------------------------------+ 3251 // 3252 // Specifications: 3253 // System V Application Binary Interface PowerPC Processor Supplement 3254 // AltiVec Technology Programming Interface Manual 3255 3256 MachineFunction &MF = DAG.getMachineFunction(); 3257 MachineFrameInfo &MFI = MF.getFrameInfo(); 3258 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3259 3260 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3261 // Potential tail calls could cause overwriting of argument stack slots. 3262 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3263 (CallConv == CallingConv::Fast)); 3264 unsigned PtrByteSize = 4; 3265 3266 // Assign locations to all of the incoming arguments. 3267 SmallVector<CCValAssign, 16> ArgLocs; 3268 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3269 *DAG.getContext()); 3270 3271 // Reserve space for the linkage area on the stack. 3272 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3273 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3274 if (useSoftFloat()) 3275 CCInfo.PreAnalyzeFormalArguments(Ins); 3276 3277 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3278 CCInfo.clearWasPPCF128(); 3279 3280 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3281 CCValAssign &VA = ArgLocs[i]; 3282 3283 // Arguments stored in registers. 3284 if (VA.isRegLoc()) { 3285 const TargetRegisterClass *RC; 3286 EVT ValVT = VA.getValVT(); 3287 3288 switch (ValVT.getSimpleVT().SimpleTy) { 3289 default: 3290 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3291 case MVT::i1: 3292 case MVT::i32: 3293 RC = &PPC::GPRCRegClass; 3294 break; 3295 case MVT::f32: 3296 if (Subtarget.hasP8Vector()) 3297 RC = &PPC::VSSRCRegClass; 3298 else 3299 RC = &PPC::F4RCRegClass; 3300 break; 3301 case MVT::f64: 3302 if (Subtarget.hasVSX()) 3303 RC = &PPC::VSFRCRegClass; 3304 else 3305 RC = &PPC::F8RCRegClass; 3306 break; 3307 case MVT::v16i8: 3308 case MVT::v8i16: 3309 case MVT::v4i32: 3310 RC = &PPC::VRRCRegClass; 3311 break; 3312 case MVT::v4f32: 3313 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3314 break; 3315 case MVT::v2f64: 3316 case MVT::v2i64: 3317 RC = &PPC::VRRCRegClass; 3318 break; 3319 case MVT::v4f64: 3320 RC = &PPC::QFRCRegClass; 3321 break; 3322 case MVT::v4i1: 3323 RC = &PPC::QBRCRegClass; 3324 break; 3325 } 3326 3327 // Transform the arguments stored in physical registers into virtual ones. 3328 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3329 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3330 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3331 3332 if (ValVT == MVT::i1) 3333 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3334 3335 InVals.push_back(ArgValue); 3336 } else { 3337 // Argument stored in memory. 3338 assert(VA.isMemLoc()); 3339 3340 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3341 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3342 isImmutable); 3343 3344 // Create load nodes to retrieve arguments from the stack. 3345 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3346 InVals.push_back( 3347 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3348 } 3349 } 3350 3351 // Assign locations to all of the incoming aggregate by value arguments. 3352 // Aggregates passed by value are stored in the local variable space of the 3353 // caller's stack frame, right above the parameter list area. 3354 SmallVector<CCValAssign, 16> ByValArgLocs; 3355 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3356 ByValArgLocs, *DAG.getContext()); 3357 3358 // Reserve stack space for the allocations in CCInfo. 3359 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3360 3361 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3362 3363 // Area that is at least reserved in the caller of this function. 3364 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3365 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3366 3367 // Set the size that is at least reserved in caller of this function. Tail 3368 // call optimized function's reserved stack space needs to be aligned so that 3369 // taking the difference between two stack areas will result in an aligned 3370 // stack. 3371 MinReservedArea = 3372 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3373 FuncInfo->setMinReservedArea(MinReservedArea); 3374 3375 SmallVector<SDValue, 8> MemOps; 3376 3377 // If the function takes variable number of arguments, make a frame index for 3378 // the start of the first vararg value... for expansion of llvm.va_start. 3379 if (isVarArg) { 3380 static const MCPhysReg GPArgRegs[] = { 3381 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3382 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3383 }; 3384 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3385 3386 static const MCPhysReg FPArgRegs[] = { 3387 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3388 PPC::F8 3389 }; 3390 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3391 3392 if (useSoftFloat()) 3393 NumFPArgRegs = 0; 3394 3395 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3396 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3397 3398 // Make room for NumGPArgRegs and NumFPArgRegs. 3399 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3400 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3401 3402 FuncInfo->setVarArgsStackOffset( 3403 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3404 CCInfo.getNextStackOffset(), true)); 3405 3406 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3407 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3408 3409 // The fixed integer arguments of a variadic function are stored to the 3410 // VarArgsFrameIndex on the stack so that they may be loaded by 3411 // dereferencing the result of va_next. 3412 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3413 // Get an existing live-in vreg, or add a new one. 3414 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3415 if (!VReg) 3416 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3417 3418 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3419 SDValue Store = 3420 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3421 MemOps.push_back(Store); 3422 // Increment the address by four for the next argument to store 3423 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3424 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3425 } 3426 3427 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3428 // is set. 3429 // The double arguments are stored to the VarArgsFrameIndex 3430 // on the stack. 3431 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3432 // Get an existing live-in vreg, or add a new one. 3433 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3434 if (!VReg) 3435 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3436 3437 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3438 SDValue Store = 3439 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3440 MemOps.push_back(Store); 3441 // Increment the address by eight for the next argument to store 3442 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3443 PtrVT); 3444 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3445 } 3446 } 3447 3448 if (!MemOps.empty()) 3449 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3450 3451 return Chain; 3452 } 3453 3454 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3455 // value to MVT::i64 and then truncate to the correct register size. 3456 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3457 EVT ObjectVT, SelectionDAG &DAG, 3458 SDValue ArgVal, 3459 const SDLoc &dl) const { 3460 if (Flags.isSExt()) 3461 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3462 DAG.getValueType(ObjectVT)); 3463 else if (Flags.isZExt()) 3464 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3465 DAG.getValueType(ObjectVT)); 3466 3467 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3468 } 3469 3470 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3471 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3472 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3473 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3474 // TODO: add description of PPC stack frame format, or at least some docs. 3475 // 3476 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3477 bool isLittleEndian = Subtarget.isLittleEndian(); 3478 MachineFunction &MF = DAG.getMachineFunction(); 3479 MachineFrameInfo &MFI = MF.getFrameInfo(); 3480 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3481 3482 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3483 "fastcc not supported on varargs functions"); 3484 3485 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3486 // Potential tail calls could cause overwriting of argument stack slots. 3487 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3488 (CallConv == CallingConv::Fast)); 3489 unsigned PtrByteSize = 8; 3490 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3491 3492 static const MCPhysReg GPR[] = { 3493 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3494 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3495 }; 3496 static const MCPhysReg VR[] = { 3497 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3498 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3499 }; 3500 3501 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3502 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3503 const unsigned Num_VR_Regs = array_lengthof(VR); 3504 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3505 3506 // Do a first pass over the arguments to determine whether the ABI 3507 // guarantees that our caller has allocated the parameter save area 3508 // on its stack frame. In the ELFv1 ABI, this is always the case; 3509 // in the ELFv2 ABI, it is true if this is a vararg function or if 3510 // any parameter is located in a stack slot. 3511 3512 bool HasParameterArea = !isELFv2ABI || isVarArg; 3513 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3514 unsigned NumBytes = LinkageSize; 3515 unsigned AvailableFPRs = Num_FPR_Regs; 3516 unsigned AvailableVRs = Num_VR_Regs; 3517 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3518 if (Ins[i].Flags.isNest()) 3519 continue; 3520 3521 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3522 PtrByteSize, LinkageSize, ParamAreaSize, 3523 NumBytes, AvailableFPRs, AvailableVRs, 3524 Subtarget.hasQPX())) 3525 HasParameterArea = true; 3526 } 3527 3528 // Add DAG nodes to load the arguments or copy them out of registers. On 3529 // entry to a function on PPC, the arguments start after the linkage area, 3530 // although the first ones are often in registers. 3531 3532 unsigned ArgOffset = LinkageSize; 3533 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3534 unsigned &QFPR_idx = FPR_idx; 3535 SmallVector<SDValue, 8> MemOps; 3536 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3537 unsigned CurArgIdx = 0; 3538 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3539 SDValue ArgVal; 3540 bool needsLoad = false; 3541 EVT ObjectVT = Ins[ArgNo].VT; 3542 EVT OrigVT = Ins[ArgNo].ArgVT; 3543 unsigned ObjSize = ObjectVT.getStoreSize(); 3544 unsigned ArgSize = ObjSize; 3545 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3546 if (Ins[ArgNo].isOrigArg()) { 3547 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3548 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3549 } 3550 // We re-align the argument offset for each argument, except when using the 3551 // fast calling convention, when we need to make sure we do that only when 3552 // we'll actually use a stack slot. 3553 unsigned CurArgOffset, Align; 3554 auto ComputeArgOffset = [&]() { 3555 /* Respect alignment of argument on the stack. */ 3556 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3557 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3558 CurArgOffset = ArgOffset; 3559 }; 3560 3561 if (CallConv != CallingConv::Fast) { 3562 ComputeArgOffset(); 3563 3564 /* Compute GPR index associated with argument offset. */ 3565 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3566 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3567 } 3568 3569 // FIXME the codegen can be much improved in some cases. 3570 // We do not have to keep everything in memory. 3571 if (Flags.isByVal()) { 3572 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3573 3574 if (CallConv == CallingConv::Fast) 3575 ComputeArgOffset(); 3576 3577 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3578 ObjSize = Flags.getByValSize(); 3579 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3580 // Empty aggregate parameters do not take up registers. Examples: 3581 // struct { } a; 3582 // union { } b; 3583 // int c[0]; 3584 // etc. However, we have to provide a place-holder in InVals, so 3585 // pretend we have an 8-byte item at the current address for that 3586 // purpose. 3587 if (!ObjSize) { 3588 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3589 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3590 InVals.push_back(FIN); 3591 continue; 3592 } 3593 3594 // Create a stack object covering all stack doublewords occupied 3595 // by the argument. If the argument is (fully or partially) on 3596 // the stack, or if the argument is fully in registers but the 3597 // caller has allocated the parameter save anyway, we can refer 3598 // directly to the caller's stack frame. Otherwise, create a 3599 // local copy in our own frame. 3600 int FI; 3601 if (HasParameterArea || 3602 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3603 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3604 else 3605 FI = MFI.CreateStackObject(ArgSize, Align, false); 3606 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3607 3608 // Handle aggregates smaller than 8 bytes. 3609 if (ObjSize < PtrByteSize) { 3610 // The value of the object is its address, which differs from the 3611 // address of the enclosing doubleword on big-endian systems. 3612 SDValue Arg = FIN; 3613 if (!isLittleEndian) { 3614 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3615 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3616 } 3617 InVals.push_back(Arg); 3618 3619 if (GPR_idx != Num_GPR_Regs) { 3620 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3621 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3622 SDValue Store; 3623 3624 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3625 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3626 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3627 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3628 MachinePointerInfo(&*FuncArg), ObjType); 3629 } else { 3630 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3631 // store the whole register as-is to the parameter save area 3632 // slot. 3633 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3634 MachinePointerInfo(&*FuncArg)); 3635 } 3636 3637 MemOps.push_back(Store); 3638 } 3639 // Whether we copied from a register or not, advance the offset 3640 // into the parameter save area by a full doubleword. 3641 ArgOffset += PtrByteSize; 3642 continue; 3643 } 3644 3645 // The value of the object is its address, which is the address of 3646 // its first stack doubleword. 3647 InVals.push_back(FIN); 3648 3649 // Store whatever pieces of the object are in registers to memory. 3650 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3651 if (GPR_idx == Num_GPR_Regs) 3652 break; 3653 3654 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3655 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3656 SDValue Addr = FIN; 3657 if (j) { 3658 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3659 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3660 } 3661 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3662 MachinePointerInfo(&*FuncArg, j)); 3663 MemOps.push_back(Store); 3664 ++GPR_idx; 3665 } 3666 ArgOffset += ArgSize; 3667 continue; 3668 } 3669 3670 switch (ObjectVT.getSimpleVT().SimpleTy) { 3671 default: llvm_unreachable("Unhandled argument type!"); 3672 case MVT::i1: 3673 case MVT::i32: 3674 case MVT::i64: 3675 if (Flags.isNest()) { 3676 // The 'nest' parameter, if any, is passed in R11. 3677 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3678 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3679 3680 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3681 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3682 3683 break; 3684 } 3685 3686 // These can be scalar arguments or elements of an integer array type 3687 // passed directly. Clang may use those instead of "byval" aggregate 3688 // types to avoid forcing arguments to memory unnecessarily. 3689 if (GPR_idx != Num_GPR_Regs) { 3690 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3691 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3692 3693 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3694 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3695 // value to MVT::i64 and then truncate to the correct register size. 3696 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3697 } else { 3698 if (CallConv == CallingConv::Fast) 3699 ComputeArgOffset(); 3700 3701 needsLoad = true; 3702 ArgSize = PtrByteSize; 3703 } 3704 if (CallConv != CallingConv::Fast || needsLoad) 3705 ArgOffset += 8; 3706 break; 3707 3708 case MVT::f32: 3709 case MVT::f64: 3710 // These can be scalar arguments or elements of a float array type 3711 // passed directly. The latter are used to implement ELFv2 homogenous 3712 // float aggregates. 3713 if (FPR_idx != Num_FPR_Regs) { 3714 unsigned VReg; 3715 3716 if (ObjectVT == MVT::f32) 3717 VReg = MF.addLiveIn(FPR[FPR_idx], 3718 Subtarget.hasP8Vector() 3719 ? &PPC::VSSRCRegClass 3720 : &PPC::F4RCRegClass); 3721 else 3722 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3723 ? &PPC::VSFRCRegClass 3724 : &PPC::F8RCRegClass); 3725 3726 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3727 ++FPR_idx; 3728 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3729 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3730 // once we support fp <-> gpr moves. 3731 3732 // This can only ever happen in the presence of f32 array types, 3733 // since otherwise we never run out of FPRs before running out 3734 // of GPRs. 3735 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3736 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3737 3738 if (ObjectVT == MVT::f32) { 3739 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3740 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3741 DAG.getConstant(32, dl, MVT::i32)); 3742 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3743 } 3744 3745 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3746 } else { 3747 if (CallConv == CallingConv::Fast) 3748 ComputeArgOffset(); 3749 3750 needsLoad = true; 3751 } 3752 3753 // When passing an array of floats, the array occupies consecutive 3754 // space in the argument area; only round up to the next doubleword 3755 // at the end of the array. Otherwise, each float takes 8 bytes. 3756 if (CallConv != CallingConv::Fast || needsLoad) { 3757 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3758 ArgOffset += ArgSize; 3759 if (Flags.isInConsecutiveRegsLast()) 3760 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3761 } 3762 break; 3763 case MVT::v4f32: 3764 case MVT::v4i32: 3765 case MVT::v8i16: 3766 case MVT::v16i8: 3767 case MVT::v2f64: 3768 case MVT::v2i64: 3769 case MVT::v1i128: 3770 if (!Subtarget.hasQPX()) { 3771 // These can be scalar arguments or elements of a vector array type 3772 // passed directly. The latter are used to implement ELFv2 homogenous 3773 // vector aggregates. 3774 if (VR_idx != Num_VR_Regs) { 3775 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3776 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3777 ++VR_idx; 3778 } else { 3779 if (CallConv == CallingConv::Fast) 3780 ComputeArgOffset(); 3781 3782 needsLoad = true; 3783 } 3784 if (CallConv != CallingConv::Fast || needsLoad) 3785 ArgOffset += 16; 3786 break; 3787 } // not QPX 3788 3789 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3790 "Invalid QPX parameter type"); 3791 /* fall through */ 3792 3793 case MVT::v4f64: 3794 case MVT::v4i1: 3795 // QPX vectors are treated like their scalar floating-point subregisters 3796 // (except that they're larger). 3797 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3798 if (QFPR_idx != Num_QFPR_Regs) { 3799 const TargetRegisterClass *RC; 3800 switch (ObjectVT.getSimpleVT().SimpleTy) { 3801 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3802 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3803 default: RC = &PPC::QBRCRegClass; break; 3804 } 3805 3806 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3807 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3808 ++QFPR_idx; 3809 } else { 3810 if (CallConv == CallingConv::Fast) 3811 ComputeArgOffset(); 3812 needsLoad = true; 3813 } 3814 if (CallConv != CallingConv::Fast || needsLoad) 3815 ArgOffset += Sz; 3816 break; 3817 } 3818 3819 // We need to load the argument to a virtual register if we determined 3820 // above that we ran out of physical registers of the appropriate type. 3821 if (needsLoad) { 3822 if (ObjSize < ArgSize && !isLittleEndian) 3823 CurArgOffset += ArgSize - ObjSize; 3824 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3825 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3826 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3827 } 3828 3829 InVals.push_back(ArgVal); 3830 } 3831 3832 // Area that is at least reserved in the caller of this function. 3833 unsigned MinReservedArea; 3834 if (HasParameterArea) 3835 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3836 else 3837 MinReservedArea = LinkageSize; 3838 3839 // Set the size that is at least reserved in caller of this function. Tail 3840 // call optimized functions' reserved stack space needs to be aligned so that 3841 // taking the difference between two stack areas will result in an aligned 3842 // stack. 3843 MinReservedArea = 3844 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3845 FuncInfo->setMinReservedArea(MinReservedArea); 3846 3847 // If the function takes variable number of arguments, make a frame index for 3848 // the start of the first vararg value... for expansion of llvm.va_start. 3849 if (isVarArg) { 3850 int Depth = ArgOffset; 3851 3852 FuncInfo->setVarArgsFrameIndex( 3853 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3854 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3855 3856 // If this function is vararg, store any remaining integer argument regs 3857 // to their spots on the stack so that they may be loaded by dereferencing 3858 // the result of va_next. 3859 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3860 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3861 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3862 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3863 SDValue Store = 3864 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3865 MemOps.push_back(Store); 3866 // Increment the address by four for the next argument to store 3867 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3868 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3869 } 3870 } 3871 3872 if (!MemOps.empty()) 3873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3874 3875 return Chain; 3876 } 3877 3878 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3879 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3880 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3881 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3882 // TODO: add description of PPC stack frame format, or at least some docs. 3883 // 3884 MachineFunction &MF = DAG.getMachineFunction(); 3885 MachineFrameInfo &MFI = MF.getFrameInfo(); 3886 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3887 3888 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3889 bool isPPC64 = PtrVT == MVT::i64; 3890 // Potential tail calls could cause overwriting of argument stack slots. 3891 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3892 (CallConv == CallingConv::Fast)); 3893 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3894 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3895 unsigned ArgOffset = LinkageSize; 3896 // Area that is at least reserved in caller of this function. 3897 unsigned MinReservedArea = ArgOffset; 3898 3899 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3900 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3901 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3902 }; 3903 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3904 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3905 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3906 }; 3907 static const MCPhysReg VR[] = { 3908 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3909 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3910 }; 3911 3912 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3913 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3914 const unsigned Num_VR_Regs = array_lengthof( VR); 3915 3916 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3917 3918 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3919 3920 // In 32-bit non-varargs functions, the stack space for vectors is after the 3921 // stack space for non-vectors. We do not use this space unless we have 3922 // too many vectors to fit in registers, something that only occurs in 3923 // constructed examples:), but we have to walk the arglist to figure 3924 // that out...for the pathological case, compute VecArgOffset as the 3925 // start of the vector parameter area. Computing VecArgOffset is the 3926 // entire point of the following loop. 3927 unsigned VecArgOffset = ArgOffset; 3928 if (!isVarArg && !isPPC64) { 3929 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3930 ++ArgNo) { 3931 EVT ObjectVT = Ins[ArgNo].VT; 3932 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3933 3934 if (Flags.isByVal()) { 3935 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3936 unsigned ObjSize = Flags.getByValSize(); 3937 unsigned ArgSize = 3938 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3939 VecArgOffset += ArgSize; 3940 continue; 3941 } 3942 3943 switch(ObjectVT.getSimpleVT().SimpleTy) { 3944 default: llvm_unreachable("Unhandled argument type!"); 3945 case MVT::i1: 3946 case MVT::i32: 3947 case MVT::f32: 3948 VecArgOffset += 4; 3949 break; 3950 case MVT::i64: // PPC64 3951 case MVT::f64: 3952 // FIXME: We are guaranteed to be !isPPC64 at this point. 3953 // Does MVT::i64 apply? 3954 VecArgOffset += 8; 3955 break; 3956 case MVT::v4f32: 3957 case MVT::v4i32: 3958 case MVT::v8i16: 3959 case MVT::v16i8: 3960 // Nothing to do, we're only looking at Nonvector args here. 3961 break; 3962 } 3963 } 3964 } 3965 // We've found where the vector parameter area in memory is. Skip the 3966 // first 12 parameters; these don't use that memory. 3967 VecArgOffset = ((VecArgOffset+15)/16)*16; 3968 VecArgOffset += 12*16; 3969 3970 // Add DAG nodes to load the arguments or copy them out of registers. On 3971 // entry to a function on PPC, the arguments start after the linkage area, 3972 // although the first ones are often in registers. 3973 3974 SmallVector<SDValue, 8> MemOps; 3975 unsigned nAltivecParamsAtEnd = 0; 3976 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3977 unsigned CurArgIdx = 0; 3978 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3979 SDValue ArgVal; 3980 bool needsLoad = false; 3981 EVT ObjectVT = Ins[ArgNo].VT; 3982 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3983 unsigned ArgSize = ObjSize; 3984 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3985 if (Ins[ArgNo].isOrigArg()) { 3986 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3987 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3988 } 3989 unsigned CurArgOffset = ArgOffset; 3990 3991 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 3992 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 3993 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 3994 if (isVarArg || isPPC64) { 3995 MinReservedArea = ((MinReservedArea+15)/16)*16; 3996 MinReservedArea += CalculateStackSlotSize(ObjectVT, 3997 Flags, 3998 PtrByteSize); 3999 } else nAltivecParamsAtEnd++; 4000 } else 4001 // Calculate min reserved area. 4002 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4003 Flags, 4004 PtrByteSize); 4005 4006 // FIXME the codegen can be much improved in some cases. 4007 // We do not have to keep everything in memory. 4008 if (Flags.isByVal()) { 4009 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4010 4011 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4012 ObjSize = Flags.getByValSize(); 4013 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4014 // Objects of size 1 and 2 are right justified, everything else is 4015 // left justified. This means the memory address is adjusted forwards. 4016 if (ObjSize==1 || ObjSize==2) { 4017 CurArgOffset = CurArgOffset + (4 - ObjSize); 4018 } 4019 // The value of the object is its address. 4020 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4021 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4022 InVals.push_back(FIN); 4023 if (ObjSize==1 || ObjSize==2) { 4024 if (GPR_idx != Num_GPR_Regs) { 4025 unsigned VReg; 4026 if (isPPC64) 4027 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4028 else 4029 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4030 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4031 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4032 SDValue Store = 4033 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4034 MachinePointerInfo(&*FuncArg), ObjType); 4035 MemOps.push_back(Store); 4036 ++GPR_idx; 4037 } 4038 4039 ArgOffset += PtrByteSize; 4040 4041 continue; 4042 } 4043 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4044 // Store whatever pieces of the object are in registers 4045 // to memory. ArgOffset will be the address of the beginning 4046 // of the object. 4047 if (GPR_idx != Num_GPR_Regs) { 4048 unsigned VReg; 4049 if (isPPC64) 4050 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4051 else 4052 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4053 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4054 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4055 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4056 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4057 MachinePointerInfo(&*FuncArg, j)); 4058 MemOps.push_back(Store); 4059 ++GPR_idx; 4060 ArgOffset += PtrByteSize; 4061 } else { 4062 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4063 break; 4064 } 4065 } 4066 continue; 4067 } 4068 4069 switch (ObjectVT.getSimpleVT().SimpleTy) { 4070 default: llvm_unreachable("Unhandled argument type!"); 4071 case MVT::i1: 4072 case MVT::i32: 4073 if (!isPPC64) { 4074 if (GPR_idx != Num_GPR_Regs) { 4075 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4076 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4077 4078 if (ObjectVT == MVT::i1) 4079 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4080 4081 ++GPR_idx; 4082 } else { 4083 needsLoad = true; 4084 ArgSize = PtrByteSize; 4085 } 4086 // All int arguments reserve stack space in the Darwin ABI. 4087 ArgOffset += PtrByteSize; 4088 break; 4089 } 4090 LLVM_FALLTHROUGH; 4091 case MVT::i64: // PPC64 4092 if (GPR_idx != Num_GPR_Regs) { 4093 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4094 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4095 4096 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4097 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4098 // value to MVT::i64 and then truncate to the correct register size. 4099 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4100 4101 ++GPR_idx; 4102 } else { 4103 needsLoad = true; 4104 ArgSize = PtrByteSize; 4105 } 4106 // All int arguments reserve stack space in the Darwin ABI. 4107 ArgOffset += 8; 4108 break; 4109 4110 case MVT::f32: 4111 case MVT::f64: 4112 // Every 4 bytes of argument space consumes one of the GPRs available for 4113 // argument passing. 4114 if (GPR_idx != Num_GPR_Regs) { 4115 ++GPR_idx; 4116 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4117 ++GPR_idx; 4118 } 4119 if (FPR_idx != Num_FPR_Regs) { 4120 unsigned VReg; 4121 4122 if (ObjectVT == MVT::f32) 4123 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4124 else 4125 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4126 4127 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4128 ++FPR_idx; 4129 } else { 4130 needsLoad = true; 4131 } 4132 4133 // All FP arguments reserve stack space in the Darwin ABI. 4134 ArgOffset += isPPC64 ? 8 : ObjSize; 4135 break; 4136 case MVT::v4f32: 4137 case MVT::v4i32: 4138 case MVT::v8i16: 4139 case MVT::v16i8: 4140 // Note that vector arguments in registers don't reserve stack space, 4141 // except in varargs functions. 4142 if (VR_idx != Num_VR_Regs) { 4143 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4144 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4145 if (isVarArg) { 4146 while ((ArgOffset % 16) != 0) { 4147 ArgOffset += PtrByteSize; 4148 if (GPR_idx != Num_GPR_Regs) 4149 GPR_idx++; 4150 } 4151 ArgOffset += 16; 4152 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4153 } 4154 ++VR_idx; 4155 } else { 4156 if (!isVarArg && !isPPC64) { 4157 // Vectors go after all the nonvectors. 4158 CurArgOffset = VecArgOffset; 4159 VecArgOffset += 16; 4160 } else { 4161 // Vectors are aligned. 4162 ArgOffset = ((ArgOffset+15)/16)*16; 4163 CurArgOffset = ArgOffset; 4164 ArgOffset += 16; 4165 } 4166 needsLoad = true; 4167 } 4168 break; 4169 } 4170 4171 // We need to load the argument to a virtual register if we determined above 4172 // that we ran out of physical registers of the appropriate type. 4173 if (needsLoad) { 4174 int FI = MFI.CreateFixedObject(ObjSize, 4175 CurArgOffset + (ArgSize - ObjSize), 4176 isImmutable); 4177 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4178 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4179 } 4180 4181 InVals.push_back(ArgVal); 4182 } 4183 4184 // Allow for Altivec parameters at the end, if needed. 4185 if (nAltivecParamsAtEnd) { 4186 MinReservedArea = ((MinReservedArea+15)/16)*16; 4187 MinReservedArea += 16*nAltivecParamsAtEnd; 4188 } 4189 4190 // Area that is at least reserved in the caller of this function. 4191 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4192 4193 // Set the size that is at least reserved in caller of this function. Tail 4194 // call optimized functions' reserved stack space needs to be aligned so that 4195 // taking the difference between two stack areas will result in an aligned 4196 // stack. 4197 MinReservedArea = 4198 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4199 FuncInfo->setMinReservedArea(MinReservedArea); 4200 4201 // If the function takes variable number of arguments, make a frame index for 4202 // the start of the first vararg value... for expansion of llvm.va_start. 4203 if (isVarArg) { 4204 int Depth = ArgOffset; 4205 4206 FuncInfo->setVarArgsFrameIndex( 4207 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4208 Depth, true)); 4209 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4210 4211 // If this function is vararg, store any remaining integer argument regs 4212 // to their spots on the stack so that they may be loaded by dereferencing 4213 // the result of va_next. 4214 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4215 unsigned VReg; 4216 4217 if (isPPC64) 4218 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4219 else 4220 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4221 4222 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4223 SDValue Store = 4224 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4225 MemOps.push_back(Store); 4226 // Increment the address by four for the next argument to store 4227 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4228 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4229 } 4230 } 4231 4232 if (!MemOps.empty()) 4233 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4234 4235 return Chain; 4236 } 4237 4238 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4239 /// adjusted to accommodate the arguments for the tailcall. 4240 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4241 unsigned ParamSize) { 4242 4243 if (!isTailCall) return 0; 4244 4245 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4246 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4247 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4248 // Remember only if the new adjustement is bigger. 4249 if (SPDiff < FI->getTailCallSPDelta()) 4250 FI->setTailCallSPDelta(SPDiff); 4251 4252 return SPDiff; 4253 } 4254 4255 static bool isFunctionGlobalAddress(SDValue Callee); 4256 4257 static bool 4258 callsShareTOCBase(const Function *Caller, SDValue Callee, 4259 const TargetMachine &TM) { 4260 // If !G, Callee can be an external symbol. 4261 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4262 if (!G) 4263 return false; 4264 4265 // The medium and large code models are expected to provide a sufficiently 4266 // large TOC to provide all data addressing needs of a module with a 4267 // single TOC. Since each module will be addressed with a single TOC then we 4268 // only need to check that caller and callee don't cross dso boundaries. 4269 if (CodeModel::Medium == TM.getCodeModel() || 4270 CodeModel::Large == TM.getCodeModel()) 4271 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4272 4273 // Otherwise we need to ensure callee and caller are in the same section, 4274 // since the linker may allocate multiple TOCs, and we don't know which 4275 // sections will belong to the same TOC base. 4276 4277 const GlobalValue *GV = G->getGlobal(); 4278 if (!GV->isStrongDefinitionForLinker()) 4279 return false; 4280 4281 // Any explicitly-specified sections and section prefixes must also match. 4282 // Also, if we're using -ffunction-sections, then each function is always in 4283 // a different section (the same is true for COMDAT functions). 4284 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4285 GV->getSection() != Caller->getSection()) 4286 return false; 4287 if (const auto *F = dyn_cast<Function>(GV)) { 4288 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4289 return false; 4290 } 4291 4292 // If the callee might be interposed, then we can't assume the ultimate call 4293 // target will be in the same section. Even in cases where we can assume that 4294 // interposition won't happen, in any case where the linker might insert a 4295 // stub to allow for interposition, we must generate code as though 4296 // interposition might occur. To understand why this matters, consider a 4297 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4298 // in the same section, but a is in a different module (i.e. has a different 4299 // TOC base pointer). If the linker allows for interposition between b and c, 4300 // then it will generate a stub for the call edge between b and c which will 4301 // save the TOC pointer into the designated stack slot allocated by b. If we 4302 // return true here, and therefore allow a tail call between b and c, that 4303 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4304 // pointer into the stack slot allocated by a (where the a -> b stub saved 4305 // a's TOC base pointer). If we're not considering a tail call, but rather, 4306 // whether a nop is needed after the call instruction in b, because the linker 4307 // will insert a stub, it might complain about a missing nop if we omit it 4308 // (although many don't complain in this case). 4309 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4310 return false; 4311 4312 return true; 4313 } 4314 4315 static bool 4316 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4317 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4318 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4319 4320 const unsigned PtrByteSize = 8; 4321 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4322 4323 static const MCPhysReg GPR[] = { 4324 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4325 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4326 }; 4327 static const MCPhysReg VR[] = { 4328 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4329 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4330 }; 4331 4332 const unsigned NumGPRs = array_lengthof(GPR); 4333 const unsigned NumFPRs = 13; 4334 const unsigned NumVRs = array_lengthof(VR); 4335 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4336 4337 unsigned NumBytes = LinkageSize; 4338 unsigned AvailableFPRs = NumFPRs; 4339 unsigned AvailableVRs = NumVRs; 4340 4341 for (const ISD::OutputArg& Param : Outs) { 4342 if (Param.Flags.isNest()) continue; 4343 4344 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4345 PtrByteSize, LinkageSize, ParamAreaSize, 4346 NumBytes, AvailableFPRs, AvailableVRs, 4347 Subtarget.hasQPX())) 4348 return true; 4349 } 4350 return false; 4351 } 4352 4353 static bool 4354 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4355 if (CS.arg_size() != CallerFn->arg_size()) 4356 return false; 4357 4358 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4359 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4360 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4361 4362 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4363 const Value* CalleeArg = *CalleeArgIter; 4364 const Value* CallerArg = &(*CallerArgIter); 4365 if (CalleeArg == CallerArg) 4366 continue; 4367 4368 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4369 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4370 // } 4371 // 1st argument of callee is undef and has the same type as caller. 4372 if (CalleeArg->getType() == CallerArg->getType() && 4373 isa<UndefValue>(CalleeArg)) 4374 continue; 4375 4376 return false; 4377 } 4378 4379 return true; 4380 } 4381 4382 bool 4383 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4384 SDValue Callee, 4385 CallingConv::ID CalleeCC, 4386 ImmutableCallSite CS, 4387 bool isVarArg, 4388 const SmallVectorImpl<ISD::OutputArg> &Outs, 4389 const SmallVectorImpl<ISD::InputArg> &Ins, 4390 SelectionDAG& DAG) const { 4391 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4392 4393 if (DisableSCO && !TailCallOpt) return false; 4394 4395 // Variadic argument functions are not supported. 4396 if (isVarArg) return false; 4397 4398 MachineFunction &MF = DAG.getMachineFunction(); 4399 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4400 4401 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has 4402 // the same calling convention 4403 if (CallerCC != CalleeCC) return false; 4404 4405 // SCO support C calling convention 4406 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C) 4407 return false; 4408 4409 // Caller contains any byval parameter is not supported. 4410 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4411 return false; 4412 4413 // Callee contains any byval parameter is not supported, too. 4414 // Note: This is a quick work around, because in some cases, e.g. 4415 // caller's stack size > callee's stack size, we are still able to apply 4416 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574 4417 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4418 return false; 4419 4420 // No TCO/SCO on indirect call because Caller have to restore its TOC 4421 if (!isFunctionGlobalAddress(Callee) && 4422 !isa<ExternalSymbolSDNode>(Callee)) 4423 return false; 4424 4425 // If the caller and callee potentially have different TOC bases then we 4426 // cannot tail call since we need to restore the TOC pointer after the call. 4427 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4428 if (!callsShareTOCBase(MF.getFunction(), Callee, getTargetMachine())) 4429 return false; 4430 4431 // TCO allows altering callee ABI, so we don't have to check further. 4432 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4433 return true; 4434 4435 if (DisableSCO) return false; 4436 4437 // If callee use the same argument list that caller is using, then we can 4438 // apply SCO on this case. If it is not, then we need to check if callee needs 4439 // stack for passing arguments. 4440 if (!hasSameArgumentList(MF.getFunction(), CS) && 4441 needStackSlotPassParameters(Subtarget, Outs)) { 4442 return false; 4443 } 4444 4445 return true; 4446 } 4447 4448 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4449 /// for tail call optimization. Targets which want to do tail call 4450 /// optimization should implement this function. 4451 bool 4452 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4453 CallingConv::ID CalleeCC, 4454 bool isVarArg, 4455 const SmallVectorImpl<ISD::InputArg> &Ins, 4456 SelectionDAG& DAG) const { 4457 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4458 return false; 4459 4460 // Variable argument functions are not supported. 4461 if (isVarArg) 4462 return false; 4463 4464 MachineFunction &MF = DAG.getMachineFunction(); 4465 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4466 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4467 // Functions containing by val parameters are not supported. 4468 for (unsigned i = 0; i != Ins.size(); i++) { 4469 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4470 if (Flags.isByVal()) return false; 4471 } 4472 4473 // Non-PIC/GOT tail calls are supported. 4474 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4475 return true; 4476 4477 // At the moment we can only do local tail calls (in same module, hidden 4478 // or protected) if we are generating PIC. 4479 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4480 return G->getGlobal()->hasHiddenVisibility() 4481 || G->getGlobal()->hasProtectedVisibility(); 4482 } 4483 4484 return false; 4485 } 4486 4487 /// isCallCompatibleAddress - Return the immediate to use if the specified 4488 /// 32-bit value is representable in the immediate field of a BxA instruction. 4489 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4490 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4491 if (!C) return nullptr; 4492 4493 int Addr = C->getZExtValue(); 4494 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4495 SignExtend32<26>(Addr) != Addr) 4496 return nullptr; // Top 6 bits have to be sext of immediate. 4497 4498 return DAG 4499 .getConstant( 4500 (int)C->getZExtValue() >> 2, SDLoc(Op), 4501 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4502 .getNode(); 4503 } 4504 4505 namespace { 4506 4507 struct TailCallArgumentInfo { 4508 SDValue Arg; 4509 SDValue FrameIdxOp; 4510 int FrameIdx = 0; 4511 4512 TailCallArgumentInfo() = default; 4513 }; 4514 4515 } // end anonymous namespace 4516 4517 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4518 static void StoreTailCallArgumentsToStackSlot( 4519 SelectionDAG &DAG, SDValue Chain, 4520 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4521 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4522 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4523 SDValue Arg = TailCallArgs[i].Arg; 4524 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4525 int FI = TailCallArgs[i].FrameIdx; 4526 // Store relative to framepointer. 4527 MemOpChains.push_back(DAG.getStore( 4528 Chain, dl, Arg, FIN, 4529 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4530 } 4531 } 4532 4533 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4534 /// the appropriate stack slot for the tail call optimized function call. 4535 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4536 SDValue OldRetAddr, SDValue OldFP, 4537 int SPDiff, const SDLoc &dl) { 4538 if (SPDiff) { 4539 // Calculate the new stack slot for the return address. 4540 MachineFunction &MF = DAG.getMachineFunction(); 4541 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4542 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4543 bool isPPC64 = Subtarget.isPPC64(); 4544 int SlotSize = isPPC64 ? 8 : 4; 4545 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4546 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4547 NewRetAddrLoc, true); 4548 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4549 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4550 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4551 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4552 4553 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4554 // slot as the FP is never overwritten. 4555 if (Subtarget.isDarwinABI()) { 4556 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4557 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4558 true); 4559 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4560 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4561 MachinePointerInfo::getFixedStack( 4562 DAG.getMachineFunction(), NewFPIdx)); 4563 } 4564 } 4565 return Chain; 4566 } 4567 4568 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4569 /// the position of the argument. 4570 static void 4571 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4572 SDValue Arg, int SPDiff, unsigned ArgOffset, 4573 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4574 int Offset = ArgOffset + SPDiff; 4575 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4576 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4577 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4578 SDValue FIN = DAG.getFrameIndex(FI, VT); 4579 TailCallArgumentInfo Info; 4580 Info.Arg = Arg; 4581 Info.FrameIdxOp = FIN; 4582 Info.FrameIdx = FI; 4583 TailCallArguments.push_back(Info); 4584 } 4585 4586 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4587 /// stack slot. Returns the chain as result and the loaded frame pointers in 4588 /// LROpOut/FPOpout. Used when tail calling. 4589 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4590 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4591 SDValue &FPOpOut, const SDLoc &dl) const { 4592 if (SPDiff) { 4593 // Load the LR and FP stack slot for later adjusting. 4594 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4595 LROpOut = getReturnAddrFrameIndex(DAG); 4596 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4597 Chain = SDValue(LROpOut.getNode(), 1); 4598 4599 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4600 // slot as the FP is never overwritten. 4601 if (Subtarget.isDarwinABI()) { 4602 FPOpOut = getFramePointerFrameIndex(DAG); 4603 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4604 Chain = SDValue(FPOpOut.getNode(), 1); 4605 } 4606 } 4607 return Chain; 4608 } 4609 4610 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4611 /// by "Src" to address "Dst" of size "Size". Alignment information is 4612 /// specified by the specific parameter attribute. The copy will be passed as 4613 /// a byval function parameter. 4614 /// Sometimes what we are copying is the end of a larger object, the part that 4615 /// does not fit in registers. 4616 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4617 SDValue Chain, ISD::ArgFlagsTy Flags, 4618 SelectionDAG &DAG, const SDLoc &dl) { 4619 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4620 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4621 false, false, false, MachinePointerInfo(), 4622 MachinePointerInfo()); 4623 } 4624 4625 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4626 /// tail calls. 4627 static void LowerMemOpCallTo( 4628 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4629 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4630 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4631 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4632 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4633 if (!isTailCall) { 4634 if (isVector) { 4635 SDValue StackPtr; 4636 if (isPPC64) 4637 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4638 else 4639 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4640 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4641 DAG.getConstant(ArgOffset, dl, PtrVT)); 4642 } 4643 MemOpChains.push_back( 4644 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4645 // Calculate and remember argument location. 4646 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4647 TailCallArguments); 4648 } 4649 4650 static void 4651 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4652 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4653 SDValue FPOp, 4654 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4655 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4656 // might overwrite each other in case of tail call optimization. 4657 SmallVector<SDValue, 8> MemOpChains2; 4658 // Do not flag preceding copytoreg stuff together with the following stuff. 4659 InFlag = SDValue(); 4660 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4661 MemOpChains2, dl); 4662 if (!MemOpChains2.empty()) 4663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4664 4665 // Store the return address to the appropriate stack slot. 4666 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4667 4668 // Emit callseq_end just before tailcall node. 4669 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4670 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4671 InFlag = Chain.getValue(1); 4672 } 4673 4674 // Is this global address that of a function that can be called by name? (as 4675 // opposed to something that must hold a descriptor for an indirect call). 4676 static bool isFunctionGlobalAddress(SDValue Callee) { 4677 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4678 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4679 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4680 return false; 4681 4682 return G->getGlobal()->getValueType()->isFunctionTy(); 4683 } 4684 4685 return false; 4686 } 4687 4688 static unsigned 4689 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4690 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4691 bool isPatchPoint, bool hasNest, 4692 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4693 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4694 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4695 bool isPPC64 = Subtarget.isPPC64(); 4696 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4697 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4698 4699 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4700 NodeTys.push_back(MVT::Other); // Returns a chain 4701 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4702 4703 unsigned CallOpc = PPCISD::CALL; 4704 4705 bool needIndirectCall = true; 4706 if (!isSVR4ABI || !isPPC64) 4707 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4708 // If this is an absolute destination address, use the munged value. 4709 Callee = SDValue(Dest, 0); 4710 needIndirectCall = false; 4711 } 4712 4713 // PC-relative references to external symbols should go through $stub, unless 4714 // we're building with the leopard linker or later, which automatically 4715 // synthesizes these stubs. 4716 const TargetMachine &TM = DAG.getTarget(); 4717 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent(); 4718 const GlobalValue *GV = nullptr; 4719 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4720 GV = G->getGlobal(); 4721 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4722 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4723 4724 if (isFunctionGlobalAddress(Callee)) { 4725 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4726 // A call to a TLS address is actually an indirect call to a 4727 // thread-specific pointer. 4728 unsigned OpFlags = 0; 4729 if (UsePlt) 4730 OpFlags = PPCII::MO_PLT; 4731 4732 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4733 // every direct call is) turn it into a TargetGlobalAddress / 4734 // TargetExternalSymbol node so that legalize doesn't hack it. 4735 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4736 Callee.getValueType(), 0, OpFlags); 4737 needIndirectCall = false; 4738 } 4739 4740 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4741 unsigned char OpFlags = 0; 4742 4743 if (UsePlt) 4744 OpFlags = PPCII::MO_PLT; 4745 4746 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4747 OpFlags); 4748 needIndirectCall = false; 4749 } 4750 4751 if (isPatchPoint) { 4752 // We'll form an invalid direct call when lowering a patchpoint; the full 4753 // sequence for an indirect call is complicated, and many of the 4754 // instructions introduced might have side effects (and, thus, can't be 4755 // removed later). The call itself will be removed as soon as the 4756 // argument/return lowering is complete, so the fact that it has the wrong 4757 // kind of operands should not really matter. 4758 needIndirectCall = false; 4759 } 4760 4761 if (needIndirectCall) { 4762 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4763 // to do the call, we can't use PPCISD::CALL. 4764 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4765 4766 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4767 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4768 // entry point, but to the function descriptor (the function entry point 4769 // address is part of the function descriptor though). 4770 // The function descriptor is a three doubleword structure with the 4771 // following fields: function entry point, TOC base address and 4772 // environment pointer. 4773 // Thus for a call through a function pointer, the following actions need 4774 // to be performed: 4775 // 1. Save the TOC of the caller in the TOC save area of its stack 4776 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4777 // 2. Load the address of the function entry point from the function 4778 // descriptor. 4779 // 3. Load the TOC of the callee from the function descriptor into r2. 4780 // 4. Load the environment pointer from the function descriptor into 4781 // r11. 4782 // 5. Branch to the function entry point address. 4783 // 6. On return of the callee, the TOC of the caller needs to be 4784 // restored (this is done in FinishCall()). 4785 // 4786 // The loads are scheduled at the beginning of the call sequence, and the 4787 // register copies are flagged together to ensure that no other 4788 // operations can be scheduled in between. E.g. without flagging the 4789 // copies together, a TOC access in the caller could be scheduled between 4790 // the assignment of the callee TOC and the branch to the callee, which 4791 // results in the TOC access going through the TOC of the callee instead 4792 // of going through the TOC of the caller, which leads to incorrect code. 4793 4794 // Load the address of the function entry point from the function 4795 // descriptor. 4796 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4797 if (LDChain.getValueType() == MVT::Glue) 4798 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4799 4800 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4801 ? (MachineMemOperand::MODereferenceable | 4802 MachineMemOperand::MOInvariant) 4803 : MachineMemOperand::MONone; 4804 4805 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4806 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4807 /* Alignment = */ 8, MMOFlags); 4808 4809 // Load environment pointer into r11. 4810 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4811 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4812 SDValue LoadEnvPtr = 4813 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4814 /* Alignment = */ 8, MMOFlags); 4815 4816 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4817 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4818 SDValue TOCPtr = 4819 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4820 /* Alignment = */ 8, MMOFlags); 4821 4822 setUsesTOCBasePtr(DAG); 4823 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4824 InFlag); 4825 Chain = TOCVal.getValue(0); 4826 InFlag = TOCVal.getValue(1); 4827 4828 // If the function call has an explicit 'nest' parameter, it takes the 4829 // place of the environment pointer. 4830 if (!hasNest) { 4831 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4832 InFlag); 4833 4834 Chain = EnvVal.getValue(0); 4835 InFlag = EnvVal.getValue(1); 4836 } 4837 4838 MTCTROps[0] = Chain; 4839 MTCTROps[1] = LoadFuncPtr; 4840 MTCTROps[2] = InFlag; 4841 } 4842 4843 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4844 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4845 InFlag = Chain.getValue(1); 4846 4847 NodeTys.clear(); 4848 NodeTys.push_back(MVT::Other); 4849 NodeTys.push_back(MVT::Glue); 4850 Ops.push_back(Chain); 4851 CallOpc = PPCISD::BCTRL; 4852 Callee.setNode(nullptr); 4853 // Add use of X11 (holding environment pointer) 4854 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4855 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4856 // Add CTR register as callee so a bctr can be emitted later. 4857 if (isTailCall) 4858 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4859 } 4860 4861 // If this is a direct call, pass the chain and the callee. 4862 if (Callee.getNode()) { 4863 Ops.push_back(Chain); 4864 Ops.push_back(Callee); 4865 } 4866 // If this is a tail call add stack pointer delta. 4867 if (isTailCall) 4868 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4869 4870 // Add argument registers to the end of the list so that they are known live 4871 // into the call. 4872 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4873 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4874 RegsToPass[i].second.getValueType())); 4875 4876 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4877 // into the call. 4878 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4879 setUsesTOCBasePtr(DAG); 4880 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4881 } 4882 4883 return CallOpc; 4884 } 4885 4886 SDValue PPCTargetLowering::LowerCallResult( 4887 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4888 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4889 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4890 SmallVector<CCValAssign, 16> RVLocs; 4891 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4892 *DAG.getContext()); 4893 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4894 4895 // Copy all of the result registers out of their specified physreg. 4896 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4897 CCValAssign &VA = RVLocs[i]; 4898 assert(VA.isRegLoc() && "Can only return in registers!"); 4899 4900 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4901 VA.getLocReg(), VA.getLocVT(), InFlag); 4902 Chain = Val.getValue(1); 4903 InFlag = Val.getValue(2); 4904 4905 switch (VA.getLocInfo()) { 4906 default: llvm_unreachable("Unknown loc info!"); 4907 case CCValAssign::Full: break; 4908 case CCValAssign::AExt: 4909 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4910 break; 4911 case CCValAssign::ZExt: 4912 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4913 DAG.getValueType(VA.getValVT())); 4914 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4915 break; 4916 case CCValAssign::SExt: 4917 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4918 DAG.getValueType(VA.getValVT())); 4919 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4920 break; 4921 } 4922 4923 InVals.push_back(Val); 4924 } 4925 4926 return Chain; 4927 } 4928 4929 SDValue PPCTargetLowering::FinishCall( 4930 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4931 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4932 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4933 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4934 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4935 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 4936 std::vector<EVT> NodeTys; 4937 SmallVector<SDValue, 8> Ops; 4938 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4939 SPDiff, isTailCall, isPatchPoint, hasNest, 4940 RegsToPass, Ops, NodeTys, CS, Subtarget); 4941 4942 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4943 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4944 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4945 4946 // When performing tail call optimization the callee pops its arguments off 4947 // the stack. Account for this here so these bytes can be pushed back on in 4948 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4949 int BytesCalleePops = 4950 (CallConv == CallingConv::Fast && 4951 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 4952 4953 // Add a register mask operand representing the call-preserved registers. 4954 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4955 const uint32_t *Mask = 4956 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 4957 assert(Mask && "Missing call preserved mask for calling convention"); 4958 Ops.push_back(DAG.getRegisterMask(Mask)); 4959 4960 if (InFlag.getNode()) 4961 Ops.push_back(InFlag); 4962 4963 // Emit tail call. 4964 if (isTailCall) { 4965 assert(((Callee.getOpcode() == ISD::Register && 4966 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 4967 Callee.getOpcode() == ISD::TargetExternalSymbol || 4968 Callee.getOpcode() == ISD::TargetGlobalAddress || 4969 isa<ConstantSDNode>(Callee)) && 4970 "Expecting an global address, external symbol, absolute value or register"); 4971 4972 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 4973 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 4974 } 4975 4976 // Add a NOP immediately after the branch instruction when using the 64-bit 4977 // SVR4 ABI. At link time, if caller and callee are in a different module and 4978 // thus have a different TOC, the call will be replaced with a call to a stub 4979 // function which saves the current TOC, loads the TOC of the callee and 4980 // branches to the callee. The NOP will be replaced with a load instruction 4981 // which restores the TOC of the caller from the TOC save slot of the current 4982 // stack frame. If caller and callee belong to the same module (and have the 4983 // same TOC), the NOP will remain unchanged. 4984 4985 MachineFunction &MF = DAG.getMachineFunction(); 4986 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 4987 !isPatchPoint) { 4988 if (CallOpc == PPCISD::BCTRL) { 4989 // This is a call through a function pointer. 4990 // Restore the caller TOC from the save area into R2. 4991 // See PrepareCall() for more information about calls through function 4992 // pointers in the 64-bit SVR4 ABI. 4993 // We are using a target-specific load with r2 hard coded, because the 4994 // result of a target-independent load would never go directly into r2, 4995 // since r2 is a reserved register (which prevents the register allocator 4996 // from allocating it), resulting in an additional register being 4997 // allocated and an unnecessary move instruction being generated. 4998 CallOpc = PPCISD::BCTRL_LOAD_TOC; 4999 5000 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5001 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5002 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5003 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5004 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5005 5006 // The address needs to go after the chain input but before the flag (or 5007 // any other variadic arguments). 5008 Ops.insert(std::next(Ops.begin()), AddTOC); 5009 } else if (CallOpc == PPCISD::CALL && 5010 !callsShareTOCBase(MF.getFunction(), Callee, DAG.getTarget())) { 5011 // Otherwise insert NOP for non-local calls. 5012 CallOpc = PPCISD::CALL_NOP; 5013 } 5014 } 5015 5016 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5017 InFlag = Chain.getValue(1); 5018 5019 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5020 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5021 InFlag, dl); 5022 if (!Ins.empty()) 5023 InFlag = Chain.getValue(1); 5024 5025 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5026 Ins, dl, DAG, InVals); 5027 } 5028 5029 SDValue 5030 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5031 SmallVectorImpl<SDValue> &InVals) const { 5032 SelectionDAG &DAG = CLI.DAG; 5033 SDLoc &dl = CLI.DL; 5034 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5035 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5036 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5037 SDValue Chain = CLI.Chain; 5038 SDValue Callee = CLI.Callee; 5039 bool &isTailCall = CLI.IsTailCall; 5040 CallingConv::ID CallConv = CLI.CallConv; 5041 bool isVarArg = CLI.IsVarArg; 5042 bool isPatchPoint = CLI.IsPatchPoint; 5043 ImmutableCallSite CS = CLI.CS; 5044 5045 if (isTailCall) { 5046 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5047 isTailCall = false; 5048 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5049 isTailCall = 5050 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5051 isVarArg, Outs, Ins, DAG); 5052 else 5053 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5054 Ins, DAG); 5055 if (isTailCall) { 5056 ++NumTailCalls; 5057 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5058 ++NumSiblingCalls; 5059 5060 assert(isa<GlobalAddressSDNode>(Callee) && 5061 "Callee should be an llvm::Function object."); 5062 DEBUG( 5063 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5064 const unsigned Width = 80 - strlen("TCO caller: ") 5065 - strlen(", callee linkage: 0, 0"); 5066 dbgs() << "TCO caller: " 5067 << left_justify(DAG.getMachineFunction().getName(), Width) 5068 << ", callee linkage: " 5069 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 5070 ); 5071 } 5072 } 5073 5074 if (!isTailCall && CS && CS.isMustTailCall()) 5075 report_fatal_error("failed to perform tail call elimination on a call " 5076 "site marked musttail"); 5077 5078 // When long calls (i.e. indirect calls) are always used, calls are always 5079 // made via function pointer. If we have a function name, first translate it 5080 // into a pointer. 5081 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5082 !isTailCall) 5083 Callee = LowerGlobalAddress(Callee, DAG); 5084 5085 if (Subtarget.isSVR4ABI()) { 5086 if (Subtarget.isPPC64()) 5087 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5088 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5089 dl, DAG, InVals, CS); 5090 else 5091 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5092 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5093 dl, DAG, InVals, CS); 5094 } 5095 5096 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5097 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5098 dl, DAG, InVals, CS); 5099 } 5100 5101 SDValue PPCTargetLowering::LowerCall_32SVR4( 5102 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5103 bool isTailCall, bool isPatchPoint, 5104 const SmallVectorImpl<ISD::OutputArg> &Outs, 5105 const SmallVectorImpl<SDValue> &OutVals, 5106 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5107 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5108 ImmutableCallSite CS) const { 5109 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5110 // of the 32-bit SVR4 ABI stack frame layout. 5111 5112 assert((CallConv == CallingConv::C || 5113 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5114 5115 unsigned PtrByteSize = 4; 5116 5117 MachineFunction &MF = DAG.getMachineFunction(); 5118 5119 // Mark this function as potentially containing a function that contains a 5120 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5121 // and restoring the callers stack pointer in this functions epilog. This is 5122 // done because by tail calling the called function might overwrite the value 5123 // in this function's (MF) stack pointer stack slot 0(SP). 5124 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5125 CallConv == CallingConv::Fast) 5126 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5127 5128 // Count how many bytes are to be pushed on the stack, including the linkage 5129 // area, parameter list area and the part of the local variable space which 5130 // contains copies of aggregates which are passed by value. 5131 5132 // Assign locations to all of the outgoing arguments. 5133 SmallVector<CCValAssign, 16> ArgLocs; 5134 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5135 5136 // Reserve space for the linkage area on the stack. 5137 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5138 PtrByteSize); 5139 if (useSoftFloat()) 5140 CCInfo.PreAnalyzeCallOperands(Outs); 5141 5142 if (isVarArg) { 5143 // Handle fixed and variable vector arguments differently. 5144 // Fixed vector arguments go into registers as long as registers are 5145 // available. Variable vector arguments always go into memory. 5146 unsigned NumArgs = Outs.size(); 5147 5148 for (unsigned i = 0; i != NumArgs; ++i) { 5149 MVT ArgVT = Outs[i].VT; 5150 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5151 bool Result; 5152 5153 if (Outs[i].IsFixed) { 5154 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5155 CCInfo); 5156 } else { 5157 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5158 ArgFlags, CCInfo); 5159 } 5160 5161 if (Result) { 5162 #ifndef NDEBUG 5163 errs() << "Call operand #" << i << " has unhandled type " 5164 << EVT(ArgVT).getEVTString() << "\n"; 5165 #endif 5166 llvm_unreachable(nullptr); 5167 } 5168 } 5169 } else { 5170 // All arguments are treated the same. 5171 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5172 } 5173 CCInfo.clearWasPPCF128(); 5174 5175 // Assign locations to all of the outgoing aggregate by value arguments. 5176 SmallVector<CCValAssign, 16> ByValArgLocs; 5177 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5178 5179 // Reserve stack space for the allocations in CCInfo. 5180 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5181 5182 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5183 5184 // Size of the linkage area, parameter list area and the part of the local 5185 // space variable where copies of aggregates which are passed by value are 5186 // stored. 5187 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5188 5189 // Calculate by how many bytes the stack has to be adjusted in case of tail 5190 // call optimization. 5191 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5192 5193 // Adjust the stack pointer for the new arguments... 5194 // These operations are automatically eliminated by the prolog/epilog pass 5195 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5196 SDValue CallSeqStart = Chain; 5197 5198 // Load the return address and frame pointer so it can be moved somewhere else 5199 // later. 5200 SDValue LROp, FPOp; 5201 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5202 5203 // Set up a copy of the stack pointer for use loading and storing any 5204 // arguments that may not fit in the registers available for argument 5205 // passing. 5206 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5207 5208 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5209 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5210 SmallVector<SDValue, 8> MemOpChains; 5211 5212 bool seenFloatArg = false; 5213 // Walk the register/memloc assignments, inserting copies/loads. 5214 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5215 i != e; 5216 ++i) { 5217 CCValAssign &VA = ArgLocs[i]; 5218 SDValue Arg = OutVals[i]; 5219 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5220 5221 if (Flags.isByVal()) { 5222 // Argument is an aggregate which is passed by value, thus we need to 5223 // create a copy of it in the local variable space of the current stack 5224 // frame (which is the stack frame of the caller) and pass the address of 5225 // this copy to the callee. 5226 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5227 CCValAssign &ByValVA = ByValArgLocs[j++]; 5228 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5229 5230 // Memory reserved in the local variable space of the callers stack frame. 5231 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5232 5233 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5234 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5235 StackPtr, PtrOff); 5236 5237 // Create a copy of the argument in the local area of the current 5238 // stack frame. 5239 SDValue MemcpyCall = 5240 CreateCopyOfByValArgument(Arg, PtrOff, 5241 CallSeqStart.getNode()->getOperand(0), 5242 Flags, DAG, dl); 5243 5244 // This must go outside the CALLSEQ_START..END. 5245 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5246 SDLoc(MemcpyCall)); 5247 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5248 NewCallSeqStart.getNode()); 5249 Chain = CallSeqStart = NewCallSeqStart; 5250 5251 // Pass the address of the aggregate copy on the stack either in a 5252 // physical register or in the parameter list area of the current stack 5253 // frame to the callee. 5254 Arg = PtrOff; 5255 } 5256 5257 if (VA.isRegLoc()) { 5258 if (Arg.getValueType() == MVT::i1) 5259 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5260 5261 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5262 // Put argument in a physical register. 5263 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5264 } else { 5265 // Put argument in the parameter list area of the current stack frame. 5266 assert(VA.isMemLoc()); 5267 unsigned LocMemOffset = VA.getLocMemOffset(); 5268 5269 if (!isTailCall) { 5270 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5271 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5272 StackPtr, PtrOff); 5273 5274 MemOpChains.push_back( 5275 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5276 } else { 5277 // Calculate and remember argument location. 5278 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5279 TailCallArguments); 5280 } 5281 } 5282 } 5283 5284 if (!MemOpChains.empty()) 5285 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5286 5287 // Build a sequence of copy-to-reg nodes chained together with token chain 5288 // and flag operands which copy the outgoing args into the appropriate regs. 5289 SDValue InFlag; 5290 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5291 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5292 RegsToPass[i].second, InFlag); 5293 InFlag = Chain.getValue(1); 5294 } 5295 5296 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5297 // registers. 5298 if (isVarArg) { 5299 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5300 SDValue Ops[] = { Chain, InFlag }; 5301 5302 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5303 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5304 5305 InFlag = Chain.getValue(1); 5306 } 5307 5308 if (isTailCall) 5309 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5310 TailCallArguments); 5311 5312 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5313 /* unused except on PPC64 ELFv1 */ false, DAG, 5314 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5315 NumBytes, Ins, InVals, CS); 5316 } 5317 5318 // Copy an argument into memory, being careful to do this outside the 5319 // call sequence for the call to which the argument belongs. 5320 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5321 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5322 SelectionDAG &DAG, const SDLoc &dl) const { 5323 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5324 CallSeqStart.getNode()->getOperand(0), 5325 Flags, DAG, dl); 5326 // The MEMCPY must go outside the CALLSEQ_START..END. 5327 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5328 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5329 SDLoc(MemcpyCall)); 5330 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5331 NewCallSeqStart.getNode()); 5332 return NewCallSeqStart; 5333 } 5334 5335 SDValue PPCTargetLowering::LowerCall_64SVR4( 5336 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5337 bool isTailCall, bool isPatchPoint, 5338 const SmallVectorImpl<ISD::OutputArg> &Outs, 5339 const SmallVectorImpl<SDValue> &OutVals, 5340 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5341 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5342 ImmutableCallSite CS) const { 5343 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5344 bool isLittleEndian = Subtarget.isLittleEndian(); 5345 unsigned NumOps = Outs.size(); 5346 bool hasNest = false; 5347 bool IsSibCall = false; 5348 5349 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5350 unsigned PtrByteSize = 8; 5351 5352 MachineFunction &MF = DAG.getMachineFunction(); 5353 5354 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5355 IsSibCall = true; 5356 5357 // Mark this function as potentially containing a function that contains a 5358 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5359 // and restoring the callers stack pointer in this functions epilog. This is 5360 // done because by tail calling the called function might overwrite the value 5361 // in this function's (MF) stack pointer stack slot 0(SP). 5362 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5363 CallConv == CallingConv::Fast) 5364 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5365 5366 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5367 "fastcc not supported on varargs functions"); 5368 5369 // Count how many bytes are to be pushed on the stack, including the linkage 5370 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5371 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5372 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5373 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5374 unsigned NumBytes = LinkageSize; 5375 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5376 unsigned &QFPR_idx = FPR_idx; 5377 5378 static const MCPhysReg GPR[] = { 5379 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5380 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5381 }; 5382 static const MCPhysReg VR[] = { 5383 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5384 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5385 }; 5386 5387 const unsigned NumGPRs = array_lengthof(GPR); 5388 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5389 const unsigned NumVRs = array_lengthof(VR); 5390 const unsigned NumQFPRs = NumFPRs; 5391 5392 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5393 // can be passed to the callee in registers. 5394 // For the fast calling convention, there is another check below. 5395 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5396 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5397 if (!HasParameterArea) { 5398 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5399 unsigned AvailableFPRs = NumFPRs; 5400 unsigned AvailableVRs = NumVRs; 5401 unsigned NumBytesTmp = NumBytes; 5402 for (unsigned i = 0; i != NumOps; ++i) { 5403 if (Outs[i].Flags.isNest()) continue; 5404 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5405 PtrByteSize, LinkageSize, ParamAreaSize, 5406 NumBytesTmp, AvailableFPRs, AvailableVRs, 5407 Subtarget.hasQPX())) 5408 HasParameterArea = true; 5409 } 5410 } 5411 5412 // When using the fast calling convention, we don't provide backing for 5413 // arguments that will be in registers. 5414 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5415 5416 // Add up all the space actually used. 5417 for (unsigned i = 0; i != NumOps; ++i) { 5418 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5419 EVT ArgVT = Outs[i].VT; 5420 EVT OrigVT = Outs[i].ArgVT; 5421 5422 if (Flags.isNest()) 5423 continue; 5424 5425 if (CallConv == CallingConv::Fast) { 5426 if (Flags.isByVal()) 5427 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5428 else 5429 switch (ArgVT.getSimpleVT().SimpleTy) { 5430 default: llvm_unreachable("Unexpected ValueType for argument!"); 5431 case MVT::i1: 5432 case MVT::i32: 5433 case MVT::i64: 5434 if (++NumGPRsUsed <= NumGPRs) 5435 continue; 5436 break; 5437 case MVT::v4i32: 5438 case MVT::v8i16: 5439 case MVT::v16i8: 5440 case MVT::v2f64: 5441 case MVT::v2i64: 5442 case MVT::v1i128: 5443 if (++NumVRsUsed <= NumVRs) 5444 continue; 5445 break; 5446 case MVT::v4f32: 5447 // When using QPX, this is handled like a FP register, otherwise, it 5448 // is an Altivec register. 5449 if (Subtarget.hasQPX()) { 5450 if (++NumFPRsUsed <= NumFPRs) 5451 continue; 5452 } else { 5453 if (++NumVRsUsed <= NumVRs) 5454 continue; 5455 } 5456 break; 5457 case MVT::f32: 5458 case MVT::f64: 5459 case MVT::v4f64: // QPX 5460 case MVT::v4i1: // QPX 5461 if (++NumFPRsUsed <= NumFPRs) 5462 continue; 5463 break; 5464 } 5465 } 5466 5467 /* Respect alignment of argument on the stack. */ 5468 unsigned Align = 5469 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5470 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5471 5472 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5473 if (Flags.isInConsecutiveRegsLast()) 5474 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5475 } 5476 5477 unsigned NumBytesActuallyUsed = NumBytes; 5478 5479 // In the old ELFv1 ABI, 5480 // the prolog code of the callee may store up to 8 GPR argument registers to 5481 // the stack, allowing va_start to index over them in memory if its varargs. 5482 // Because we cannot tell if this is needed on the caller side, we have to 5483 // conservatively assume that it is needed. As such, make sure we have at 5484 // least enough stack space for the caller to store the 8 GPRs. 5485 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5486 // really requires memory operands, e.g. a vararg function. 5487 if (HasParameterArea) 5488 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5489 else 5490 NumBytes = LinkageSize; 5491 5492 // Tail call needs the stack to be aligned. 5493 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5494 CallConv == CallingConv::Fast) 5495 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5496 5497 int SPDiff = 0; 5498 5499 // Calculate by how many bytes the stack has to be adjusted in case of tail 5500 // call optimization. 5501 if (!IsSibCall) 5502 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5503 5504 // To protect arguments on the stack from being clobbered in a tail call, 5505 // force all the loads to happen before doing any other lowering. 5506 if (isTailCall) 5507 Chain = DAG.getStackArgumentTokenFactor(Chain); 5508 5509 // Adjust the stack pointer for the new arguments... 5510 // These operations are automatically eliminated by the prolog/epilog pass 5511 if (!IsSibCall) 5512 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5513 SDValue CallSeqStart = Chain; 5514 5515 // Load the return address and frame pointer so it can be move somewhere else 5516 // later. 5517 SDValue LROp, FPOp; 5518 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5519 5520 // Set up a copy of the stack pointer for use loading and storing any 5521 // arguments that may not fit in the registers available for argument 5522 // passing. 5523 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5524 5525 // Figure out which arguments are going to go in registers, and which in 5526 // memory. Also, if this is a vararg function, floating point operations 5527 // must be stored to our stack, and loaded into integer regs as well, if 5528 // any integer regs are available for argument passing. 5529 unsigned ArgOffset = LinkageSize; 5530 5531 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5532 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5533 5534 SmallVector<SDValue, 8> MemOpChains; 5535 for (unsigned i = 0; i != NumOps; ++i) { 5536 SDValue Arg = OutVals[i]; 5537 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5538 EVT ArgVT = Outs[i].VT; 5539 EVT OrigVT = Outs[i].ArgVT; 5540 5541 // PtrOff will be used to store the current argument to the stack if a 5542 // register cannot be found for it. 5543 SDValue PtrOff; 5544 5545 // We re-align the argument offset for each argument, except when using the 5546 // fast calling convention, when we need to make sure we do that only when 5547 // we'll actually use a stack slot. 5548 auto ComputePtrOff = [&]() { 5549 /* Respect alignment of argument on the stack. */ 5550 unsigned Align = 5551 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5552 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5553 5554 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5555 5556 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5557 }; 5558 5559 if (CallConv != CallingConv::Fast) { 5560 ComputePtrOff(); 5561 5562 /* Compute GPR index associated with argument offset. */ 5563 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5564 GPR_idx = std::min(GPR_idx, NumGPRs); 5565 } 5566 5567 // Promote integers to 64-bit values. 5568 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5569 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5570 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5571 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5572 } 5573 5574 // FIXME memcpy is used way more than necessary. Correctness first. 5575 // Note: "by value" is code for passing a structure by value, not 5576 // basic types. 5577 if (Flags.isByVal()) { 5578 // Note: Size includes alignment padding, so 5579 // struct x { short a; char b; } 5580 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5581 // These are the proper values we need for right-justifying the 5582 // aggregate in a parameter register. 5583 unsigned Size = Flags.getByValSize(); 5584 5585 // An empty aggregate parameter takes up no storage and no 5586 // registers. 5587 if (Size == 0) 5588 continue; 5589 5590 if (CallConv == CallingConv::Fast) 5591 ComputePtrOff(); 5592 5593 // All aggregates smaller than 8 bytes must be passed right-justified. 5594 if (Size==1 || Size==2 || Size==4) { 5595 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5596 if (GPR_idx != NumGPRs) { 5597 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5598 MachinePointerInfo(), VT); 5599 MemOpChains.push_back(Load.getValue(1)); 5600 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5601 5602 ArgOffset += PtrByteSize; 5603 continue; 5604 } 5605 } 5606 5607 if (GPR_idx == NumGPRs && Size < 8) { 5608 SDValue AddPtr = PtrOff; 5609 if (!isLittleEndian) { 5610 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5611 PtrOff.getValueType()); 5612 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5613 } 5614 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5615 CallSeqStart, 5616 Flags, DAG, dl); 5617 ArgOffset += PtrByteSize; 5618 continue; 5619 } 5620 // Copy entire object into memory. There are cases where gcc-generated 5621 // code assumes it is there, even if it could be put entirely into 5622 // registers. (This is not what the doc says.) 5623 5624 // FIXME: The above statement is likely due to a misunderstanding of the 5625 // documents. All arguments must be copied into the parameter area BY 5626 // THE CALLEE in the event that the callee takes the address of any 5627 // formal argument. That has not yet been implemented. However, it is 5628 // reasonable to use the stack area as a staging area for the register 5629 // load. 5630 5631 // Skip this for small aggregates, as we will use the same slot for a 5632 // right-justified copy, below. 5633 if (Size >= 8) 5634 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5635 CallSeqStart, 5636 Flags, DAG, dl); 5637 5638 // When a register is available, pass a small aggregate right-justified. 5639 if (Size < 8 && GPR_idx != NumGPRs) { 5640 // The easiest way to get this right-justified in a register 5641 // is to copy the structure into the rightmost portion of a 5642 // local variable slot, then load the whole slot into the 5643 // register. 5644 // FIXME: The memcpy seems to produce pretty awful code for 5645 // small aggregates, particularly for packed ones. 5646 // FIXME: It would be preferable to use the slot in the 5647 // parameter save area instead of a new local variable. 5648 SDValue AddPtr = PtrOff; 5649 if (!isLittleEndian) { 5650 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5651 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5652 } 5653 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5654 CallSeqStart, 5655 Flags, DAG, dl); 5656 5657 // Load the slot into the register. 5658 SDValue Load = 5659 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5660 MemOpChains.push_back(Load.getValue(1)); 5661 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5662 5663 // Done with this argument. 5664 ArgOffset += PtrByteSize; 5665 continue; 5666 } 5667 5668 // For aggregates larger than PtrByteSize, copy the pieces of the 5669 // object that fit into registers from the parameter save area. 5670 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5671 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5672 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5673 if (GPR_idx != NumGPRs) { 5674 SDValue Load = 5675 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5676 MemOpChains.push_back(Load.getValue(1)); 5677 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5678 ArgOffset += PtrByteSize; 5679 } else { 5680 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5681 break; 5682 } 5683 } 5684 continue; 5685 } 5686 5687 switch (Arg.getSimpleValueType().SimpleTy) { 5688 default: llvm_unreachable("Unexpected ValueType for argument!"); 5689 case MVT::i1: 5690 case MVT::i32: 5691 case MVT::i64: 5692 if (Flags.isNest()) { 5693 // The 'nest' parameter, if any, is passed in R11. 5694 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5695 hasNest = true; 5696 break; 5697 } 5698 5699 // These can be scalar arguments or elements of an integer array type 5700 // passed directly. Clang may use those instead of "byval" aggregate 5701 // types to avoid forcing arguments to memory unnecessarily. 5702 if (GPR_idx != NumGPRs) { 5703 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5704 } else { 5705 if (CallConv == CallingConv::Fast) 5706 ComputePtrOff(); 5707 5708 assert(HasParameterArea && 5709 "Parameter area must exist to pass an argument in memory."); 5710 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5711 true, isTailCall, false, MemOpChains, 5712 TailCallArguments, dl); 5713 if (CallConv == CallingConv::Fast) 5714 ArgOffset += PtrByteSize; 5715 } 5716 if (CallConv != CallingConv::Fast) 5717 ArgOffset += PtrByteSize; 5718 break; 5719 case MVT::f32: 5720 case MVT::f64: { 5721 // These can be scalar arguments or elements of a float array type 5722 // passed directly. The latter are used to implement ELFv2 homogenous 5723 // float aggregates. 5724 5725 // Named arguments go into FPRs first, and once they overflow, the 5726 // remaining arguments go into GPRs and then the parameter save area. 5727 // Unnamed arguments for vararg functions always go to GPRs and 5728 // then the parameter save area. For now, put all arguments to vararg 5729 // routines always in both locations (FPR *and* GPR or stack slot). 5730 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5731 bool NeededLoad = false; 5732 5733 // First load the argument into the next available FPR. 5734 if (FPR_idx != NumFPRs) 5735 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5736 5737 // Next, load the argument into GPR or stack slot if needed. 5738 if (!NeedGPROrStack) 5739 ; 5740 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5741 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5742 // once we support fp <-> gpr moves. 5743 5744 // In the non-vararg case, this can only ever happen in the 5745 // presence of f32 array types, since otherwise we never run 5746 // out of FPRs before running out of GPRs. 5747 SDValue ArgVal; 5748 5749 // Double values are always passed in a single GPR. 5750 if (Arg.getValueType() != MVT::f32) { 5751 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5752 5753 // Non-array float values are extended and passed in a GPR. 5754 } else if (!Flags.isInConsecutiveRegs()) { 5755 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5756 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5757 5758 // If we have an array of floats, we collect every odd element 5759 // together with its predecessor into one GPR. 5760 } else if (ArgOffset % PtrByteSize != 0) { 5761 SDValue Lo, Hi; 5762 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5763 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5764 if (!isLittleEndian) 5765 std::swap(Lo, Hi); 5766 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5767 5768 // The final element, if even, goes into the first half of a GPR. 5769 } else if (Flags.isInConsecutiveRegsLast()) { 5770 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5771 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5772 if (!isLittleEndian) 5773 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5774 DAG.getConstant(32, dl, MVT::i32)); 5775 5776 // Non-final even elements are skipped; they will be handled 5777 // together the with subsequent argument on the next go-around. 5778 } else 5779 ArgVal = SDValue(); 5780 5781 if (ArgVal.getNode()) 5782 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5783 } else { 5784 if (CallConv == CallingConv::Fast) 5785 ComputePtrOff(); 5786 5787 // Single-precision floating-point values are mapped to the 5788 // second (rightmost) word of the stack doubleword. 5789 if (Arg.getValueType() == MVT::f32 && 5790 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5791 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5792 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5793 } 5794 5795 assert(HasParameterArea && 5796 "Parameter area must exist to pass an argument in memory."); 5797 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5798 true, isTailCall, false, MemOpChains, 5799 TailCallArguments, dl); 5800 5801 NeededLoad = true; 5802 } 5803 // When passing an array of floats, the array occupies consecutive 5804 // space in the argument area; only round up to the next doubleword 5805 // at the end of the array. Otherwise, each float takes 8 bytes. 5806 if (CallConv != CallingConv::Fast || NeededLoad) { 5807 ArgOffset += (Arg.getValueType() == MVT::f32 && 5808 Flags.isInConsecutiveRegs()) ? 4 : 8; 5809 if (Flags.isInConsecutiveRegsLast()) 5810 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5811 } 5812 break; 5813 } 5814 case MVT::v4f32: 5815 case MVT::v4i32: 5816 case MVT::v8i16: 5817 case MVT::v16i8: 5818 case MVT::v2f64: 5819 case MVT::v2i64: 5820 case MVT::v1i128: 5821 if (!Subtarget.hasQPX()) { 5822 // These can be scalar arguments or elements of a vector array type 5823 // passed directly. The latter are used to implement ELFv2 homogenous 5824 // vector aggregates. 5825 5826 // For a varargs call, named arguments go into VRs or on the stack as 5827 // usual; unnamed arguments always go to the stack or the corresponding 5828 // GPRs when within range. For now, we always put the value in both 5829 // locations (or even all three). 5830 if (isVarArg) { 5831 assert(HasParameterArea && 5832 "Parameter area must exist if we have a varargs call."); 5833 // We could elide this store in the case where the object fits 5834 // entirely in R registers. Maybe later. 5835 SDValue Store = 5836 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5837 MemOpChains.push_back(Store); 5838 if (VR_idx != NumVRs) { 5839 SDValue Load = 5840 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5841 MemOpChains.push_back(Load.getValue(1)); 5842 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5843 } 5844 ArgOffset += 16; 5845 for (unsigned i=0; i<16; i+=PtrByteSize) { 5846 if (GPR_idx == NumGPRs) 5847 break; 5848 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5849 DAG.getConstant(i, dl, PtrVT)); 5850 SDValue Load = 5851 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5852 MemOpChains.push_back(Load.getValue(1)); 5853 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5854 } 5855 break; 5856 } 5857 5858 // Non-varargs Altivec params go into VRs or on the stack. 5859 if (VR_idx != NumVRs) { 5860 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5861 } else { 5862 if (CallConv == CallingConv::Fast) 5863 ComputePtrOff(); 5864 5865 assert(HasParameterArea && 5866 "Parameter area must exist to pass an argument in memory."); 5867 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5868 true, isTailCall, true, MemOpChains, 5869 TailCallArguments, dl); 5870 if (CallConv == CallingConv::Fast) 5871 ArgOffset += 16; 5872 } 5873 5874 if (CallConv != CallingConv::Fast) 5875 ArgOffset += 16; 5876 break; 5877 } // not QPX 5878 5879 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5880 "Invalid QPX parameter type"); 5881 5882 /* fall through */ 5883 case MVT::v4f64: 5884 case MVT::v4i1: { 5885 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5886 if (isVarArg) { 5887 assert(HasParameterArea && 5888 "Parameter area must exist if we have a varargs call."); 5889 // We could elide this store in the case where the object fits 5890 // entirely in R registers. Maybe later. 5891 SDValue Store = 5892 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5893 MemOpChains.push_back(Store); 5894 if (QFPR_idx != NumQFPRs) { 5895 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5896 PtrOff, MachinePointerInfo()); 5897 MemOpChains.push_back(Load.getValue(1)); 5898 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5899 } 5900 ArgOffset += (IsF32 ? 16 : 32); 5901 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5902 if (GPR_idx == NumGPRs) 5903 break; 5904 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5905 DAG.getConstant(i, dl, PtrVT)); 5906 SDValue Load = 5907 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5908 MemOpChains.push_back(Load.getValue(1)); 5909 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5910 } 5911 break; 5912 } 5913 5914 // Non-varargs QPX params go into registers or on the stack. 5915 if (QFPR_idx != NumQFPRs) { 5916 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5917 } else { 5918 if (CallConv == CallingConv::Fast) 5919 ComputePtrOff(); 5920 5921 assert(HasParameterArea && 5922 "Parameter area must exist to pass an argument in memory."); 5923 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5924 true, isTailCall, true, MemOpChains, 5925 TailCallArguments, dl); 5926 if (CallConv == CallingConv::Fast) 5927 ArgOffset += (IsF32 ? 16 : 32); 5928 } 5929 5930 if (CallConv != CallingConv::Fast) 5931 ArgOffset += (IsF32 ? 16 : 32); 5932 break; 5933 } 5934 } 5935 } 5936 5937 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 5938 "mismatch in size of parameter area"); 5939 (void)NumBytesActuallyUsed; 5940 5941 if (!MemOpChains.empty()) 5942 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5943 5944 // Check if this is an indirect call (MTCTR/BCTRL). 5945 // See PrepareCall() for more information about calls through function 5946 // pointers in the 64-bit SVR4 ABI. 5947 if (!isTailCall && !isPatchPoint && 5948 !isFunctionGlobalAddress(Callee) && 5949 !isa<ExternalSymbolSDNode>(Callee)) { 5950 // Load r2 into a virtual register and store it to the TOC save area. 5951 setUsesTOCBasePtr(DAG); 5952 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 5953 // TOC save area offset. 5954 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5955 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5956 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5957 Chain = DAG.getStore( 5958 Val.getValue(1), dl, Val, AddPtr, 5959 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 5960 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 5961 // This does not mean the MTCTR instruction must use R12; it's easier 5962 // to model this as an extra parameter, so do that. 5963 if (isELFv2ABI && !isPatchPoint) 5964 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 5965 } 5966 5967 // Build a sequence of copy-to-reg nodes chained together with token chain 5968 // and flag operands which copy the outgoing args into the appropriate regs. 5969 SDValue InFlag; 5970 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5971 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5972 RegsToPass[i].second, InFlag); 5973 InFlag = Chain.getValue(1); 5974 } 5975 5976 if (isTailCall && !IsSibCall) 5977 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5978 TailCallArguments); 5979 5980 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 5981 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 5982 SPDiff, NumBytes, Ins, InVals, CS); 5983 } 5984 5985 SDValue PPCTargetLowering::LowerCall_Darwin( 5986 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5987 bool isTailCall, bool isPatchPoint, 5988 const SmallVectorImpl<ISD::OutputArg> &Outs, 5989 const SmallVectorImpl<SDValue> &OutVals, 5990 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5991 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5992 ImmutableCallSite CS) const { 5993 unsigned NumOps = Outs.size(); 5994 5995 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5996 bool isPPC64 = PtrVT == MVT::i64; 5997 unsigned PtrByteSize = isPPC64 ? 8 : 4; 5998 5999 MachineFunction &MF = DAG.getMachineFunction(); 6000 6001 // Mark this function as potentially containing a function that contains a 6002 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6003 // and restoring the callers stack pointer in this functions epilog. This is 6004 // done because by tail calling the called function might overwrite the value 6005 // in this function's (MF) stack pointer stack slot 0(SP). 6006 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6007 CallConv == CallingConv::Fast) 6008 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6009 6010 // Count how many bytes are to be pushed on the stack, including the linkage 6011 // area, and parameter passing area. We start with 24/48 bytes, which is 6012 // prereserved space for [SP][CR][LR][3 x unused]. 6013 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6014 unsigned NumBytes = LinkageSize; 6015 6016 // Add up all the space actually used. 6017 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6018 // they all go in registers, but we must reserve stack space for them for 6019 // possible use by the caller. In varargs or 64-bit calls, parameters are 6020 // assigned stack space in order, with padding so Altivec parameters are 6021 // 16-byte aligned. 6022 unsigned nAltivecParamsAtEnd = 0; 6023 for (unsigned i = 0; i != NumOps; ++i) { 6024 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6025 EVT ArgVT = Outs[i].VT; 6026 // Varargs Altivec parameters are padded to a 16 byte boundary. 6027 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6028 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6029 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6030 if (!isVarArg && !isPPC64) { 6031 // Non-varargs Altivec parameters go after all the non-Altivec 6032 // parameters; handle those later so we know how much padding we need. 6033 nAltivecParamsAtEnd++; 6034 continue; 6035 } 6036 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6037 NumBytes = ((NumBytes+15)/16)*16; 6038 } 6039 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6040 } 6041 6042 // Allow for Altivec parameters at the end, if needed. 6043 if (nAltivecParamsAtEnd) { 6044 NumBytes = ((NumBytes+15)/16)*16; 6045 NumBytes += 16*nAltivecParamsAtEnd; 6046 } 6047 6048 // The prolog code of the callee may store up to 8 GPR argument registers to 6049 // the stack, allowing va_start to index over them in memory if its varargs. 6050 // Because we cannot tell if this is needed on the caller side, we have to 6051 // conservatively assume that it is needed. As such, make sure we have at 6052 // least enough stack space for the caller to store the 8 GPRs. 6053 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6054 6055 // Tail call needs the stack to be aligned. 6056 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6057 CallConv == CallingConv::Fast) 6058 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6059 6060 // Calculate by how many bytes the stack has to be adjusted in case of tail 6061 // call optimization. 6062 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6063 6064 // To protect arguments on the stack from being clobbered in a tail call, 6065 // force all the loads to happen before doing any other lowering. 6066 if (isTailCall) 6067 Chain = DAG.getStackArgumentTokenFactor(Chain); 6068 6069 // Adjust the stack pointer for the new arguments... 6070 // These operations are automatically eliminated by the prolog/epilog pass 6071 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6072 SDValue CallSeqStart = Chain; 6073 6074 // Load the return address and frame pointer so it can be move somewhere else 6075 // later. 6076 SDValue LROp, FPOp; 6077 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6078 6079 // Set up a copy of the stack pointer for use loading and storing any 6080 // arguments that may not fit in the registers available for argument 6081 // passing. 6082 SDValue StackPtr; 6083 if (isPPC64) 6084 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6085 else 6086 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6087 6088 // Figure out which arguments are going to go in registers, and which in 6089 // memory. Also, if this is a vararg function, floating point operations 6090 // must be stored to our stack, and loaded into integer regs as well, if 6091 // any integer regs are available for argument passing. 6092 unsigned ArgOffset = LinkageSize; 6093 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6094 6095 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6096 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6097 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6098 }; 6099 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6100 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6101 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6102 }; 6103 static const MCPhysReg VR[] = { 6104 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6105 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6106 }; 6107 const unsigned NumGPRs = array_lengthof(GPR_32); 6108 const unsigned NumFPRs = 13; 6109 const unsigned NumVRs = array_lengthof(VR); 6110 6111 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6112 6113 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6114 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6115 6116 SmallVector<SDValue, 8> MemOpChains; 6117 for (unsigned i = 0; i != NumOps; ++i) { 6118 SDValue Arg = OutVals[i]; 6119 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6120 6121 // PtrOff will be used to store the current argument to the stack if a 6122 // register cannot be found for it. 6123 SDValue PtrOff; 6124 6125 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6126 6127 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6128 6129 // On PPC64, promote integers to 64-bit values. 6130 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6131 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6132 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6133 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6134 } 6135 6136 // FIXME memcpy is used way more than necessary. Correctness first. 6137 // Note: "by value" is code for passing a structure by value, not 6138 // basic types. 6139 if (Flags.isByVal()) { 6140 unsigned Size = Flags.getByValSize(); 6141 // Very small objects are passed right-justified. Everything else is 6142 // passed left-justified. 6143 if (Size==1 || Size==2) { 6144 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6145 if (GPR_idx != NumGPRs) { 6146 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6147 MachinePointerInfo(), VT); 6148 MemOpChains.push_back(Load.getValue(1)); 6149 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6150 6151 ArgOffset += PtrByteSize; 6152 } else { 6153 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6154 PtrOff.getValueType()); 6155 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6156 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6157 CallSeqStart, 6158 Flags, DAG, dl); 6159 ArgOffset += PtrByteSize; 6160 } 6161 continue; 6162 } 6163 // Copy entire object into memory. There are cases where gcc-generated 6164 // code assumes it is there, even if it could be put entirely into 6165 // registers. (This is not what the doc says.) 6166 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6167 CallSeqStart, 6168 Flags, DAG, dl); 6169 6170 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6171 // copy the pieces of the object that fit into registers from the 6172 // parameter save area. 6173 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6174 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6175 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6176 if (GPR_idx != NumGPRs) { 6177 SDValue Load = 6178 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6179 MemOpChains.push_back(Load.getValue(1)); 6180 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6181 ArgOffset += PtrByteSize; 6182 } else { 6183 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6184 break; 6185 } 6186 } 6187 continue; 6188 } 6189 6190 switch (Arg.getSimpleValueType().SimpleTy) { 6191 default: llvm_unreachable("Unexpected ValueType for argument!"); 6192 case MVT::i1: 6193 case MVT::i32: 6194 case MVT::i64: 6195 if (GPR_idx != NumGPRs) { 6196 if (Arg.getValueType() == MVT::i1) 6197 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6198 6199 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6200 } else { 6201 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6202 isPPC64, isTailCall, false, MemOpChains, 6203 TailCallArguments, dl); 6204 } 6205 ArgOffset += PtrByteSize; 6206 break; 6207 case MVT::f32: 6208 case MVT::f64: 6209 if (FPR_idx != NumFPRs) { 6210 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6211 6212 if (isVarArg) { 6213 SDValue Store = 6214 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6215 MemOpChains.push_back(Store); 6216 6217 // Float varargs are always shadowed in available integer registers 6218 if (GPR_idx != NumGPRs) { 6219 SDValue Load = 6220 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6221 MemOpChains.push_back(Load.getValue(1)); 6222 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6223 } 6224 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6225 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6226 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6227 SDValue Load = 6228 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6229 MemOpChains.push_back(Load.getValue(1)); 6230 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6231 } 6232 } else { 6233 // If we have any FPRs remaining, we may also have GPRs remaining. 6234 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6235 // GPRs. 6236 if (GPR_idx != NumGPRs) 6237 ++GPR_idx; 6238 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6239 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6240 ++GPR_idx; 6241 } 6242 } else 6243 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6244 isPPC64, isTailCall, false, MemOpChains, 6245 TailCallArguments, dl); 6246 if (isPPC64) 6247 ArgOffset += 8; 6248 else 6249 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6250 break; 6251 case MVT::v4f32: 6252 case MVT::v4i32: 6253 case MVT::v8i16: 6254 case MVT::v16i8: 6255 if (isVarArg) { 6256 // These go aligned on the stack, or in the corresponding R registers 6257 // when within range. The Darwin PPC ABI doc claims they also go in 6258 // V registers; in fact gcc does this only for arguments that are 6259 // prototyped, not for those that match the ... We do it for all 6260 // arguments, seems to work. 6261 while (ArgOffset % 16 !=0) { 6262 ArgOffset += PtrByteSize; 6263 if (GPR_idx != NumGPRs) 6264 GPR_idx++; 6265 } 6266 // We could elide this store in the case where the object fits 6267 // entirely in R registers. Maybe later. 6268 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6269 DAG.getConstant(ArgOffset, dl, PtrVT)); 6270 SDValue Store = 6271 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6272 MemOpChains.push_back(Store); 6273 if (VR_idx != NumVRs) { 6274 SDValue Load = 6275 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6276 MemOpChains.push_back(Load.getValue(1)); 6277 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6278 } 6279 ArgOffset += 16; 6280 for (unsigned i=0; i<16; i+=PtrByteSize) { 6281 if (GPR_idx == NumGPRs) 6282 break; 6283 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6284 DAG.getConstant(i, dl, PtrVT)); 6285 SDValue Load = 6286 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6287 MemOpChains.push_back(Load.getValue(1)); 6288 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6289 } 6290 break; 6291 } 6292 6293 // Non-varargs Altivec params generally go in registers, but have 6294 // stack space allocated at the end. 6295 if (VR_idx != NumVRs) { 6296 // Doesn't have GPR space allocated. 6297 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6298 } else if (nAltivecParamsAtEnd==0) { 6299 // We are emitting Altivec params in order. 6300 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6301 isPPC64, isTailCall, true, MemOpChains, 6302 TailCallArguments, dl); 6303 ArgOffset += 16; 6304 } 6305 break; 6306 } 6307 } 6308 // If all Altivec parameters fit in registers, as they usually do, 6309 // they get stack space following the non-Altivec parameters. We 6310 // don't track this here because nobody below needs it. 6311 // If there are more Altivec parameters than fit in registers emit 6312 // the stores here. 6313 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6314 unsigned j = 0; 6315 // Offset is aligned; skip 1st 12 params which go in V registers. 6316 ArgOffset = ((ArgOffset+15)/16)*16; 6317 ArgOffset += 12*16; 6318 for (unsigned i = 0; i != NumOps; ++i) { 6319 SDValue Arg = OutVals[i]; 6320 EVT ArgType = Outs[i].VT; 6321 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6322 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6323 if (++j > NumVRs) { 6324 SDValue PtrOff; 6325 // We are emitting Altivec params in order. 6326 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6327 isPPC64, isTailCall, true, MemOpChains, 6328 TailCallArguments, dl); 6329 ArgOffset += 16; 6330 } 6331 } 6332 } 6333 } 6334 6335 if (!MemOpChains.empty()) 6336 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6337 6338 // On Darwin, R12 must contain the address of an indirect callee. This does 6339 // not mean the MTCTR instruction must use R12; it's easier to model this as 6340 // an extra parameter, so do that. 6341 if (!isTailCall && 6342 !isFunctionGlobalAddress(Callee) && 6343 !isa<ExternalSymbolSDNode>(Callee) && 6344 !isBLACompatibleAddress(Callee, DAG)) 6345 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6346 PPC::R12), Callee)); 6347 6348 // Build a sequence of copy-to-reg nodes chained together with token chain 6349 // and flag operands which copy the outgoing args into the appropriate regs. 6350 SDValue InFlag; 6351 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6352 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6353 RegsToPass[i].second, InFlag); 6354 InFlag = Chain.getValue(1); 6355 } 6356 6357 if (isTailCall) 6358 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6359 TailCallArguments); 6360 6361 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6362 /* unused except on PPC64 ELFv1 */ false, DAG, 6363 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6364 NumBytes, Ins, InVals, CS); 6365 } 6366 6367 bool 6368 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6369 MachineFunction &MF, bool isVarArg, 6370 const SmallVectorImpl<ISD::OutputArg> &Outs, 6371 LLVMContext &Context) const { 6372 SmallVector<CCValAssign, 16> RVLocs; 6373 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6374 return CCInfo.CheckReturn(Outs, RetCC_PPC); 6375 } 6376 6377 SDValue 6378 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6379 bool isVarArg, 6380 const SmallVectorImpl<ISD::OutputArg> &Outs, 6381 const SmallVectorImpl<SDValue> &OutVals, 6382 const SDLoc &dl, SelectionDAG &DAG) const { 6383 SmallVector<CCValAssign, 16> RVLocs; 6384 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6385 *DAG.getContext()); 6386 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 6387 6388 SDValue Flag; 6389 SmallVector<SDValue, 4> RetOps(1, Chain); 6390 6391 // Copy the result values into the output registers. 6392 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6393 CCValAssign &VA = RVLocs[i]; 6394 assert(VA.isRegLoc() && "Can only return in registers!"); 6395 6396 SDValue Arg = OutVals[i]; 6397 6398 switch (VA.getLocInfo()) { 6399 default: llvm_unreachable("Unknown loc info!"); 6400 case CCValAssign::Full: break; 6401 case CCValAssign::AExt: 6402 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6403 break; 6404 case CCValAssign::ZExt: 6405 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6406 break; 6407 case CCValAssign::SExt: 6408 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6409 break; 6410 } 6411 6412 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6413 Flag = Chain.getValue(1); 6414 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6415 } 6416 6417 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6418 const MCPhysReg *I = 6419 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6420 if (I) { 6421 for (; *I; ++I) { 6422 6423 if (PPC::G8RCRegClass.contains(*I)) 6424 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6425 else if (PPC::F8RCRegClass.contains(*I)) 6426 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6427 else if (PPC::CRRCRegClass.contains(*I)) 6428 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6429 else if (PPC::VRRCRegClass.contains(*I)) 6430 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6431 else 6432 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6433 } 6434 } 6435 6436 RetOps[0] = Chain; // Update chain. 6437 6438 // Add the flag if we have it. 6439 if (Flag.getNode()) 6440 RetOps.push_back(Flag); 6441 6442 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6443 } 6444 6445 SDValue 6446 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6447 SelectionDAG &DAG) const { 6448 SDLoc dl(Op); 6449 6450 // Get the correct type for integers. 6451 EVT IntVT = Op.getValueType(); 6452 6453 // Get the inputs. 6454 SDValue Chain = Op.getOperand(0); 6455 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6456 // Build a DYNAREAOFFSET node. 6457 SDValue Ops[2] = {Chain, FPSIdx}; 6458 SDVTList VTs = DAG.getVTList(IntVT); 6459 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6460 } 6461 6462 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6463 SelectionDAG &DAG) const { 6464 // When we pop the dynamic allocation we need to restore the SP link. 6465 SDLoc dl(Op); 6466 6467 // Get the correct type for pointers. 6468 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6469 6470 // Construct the stack pointer operand. 6471 bool isPPC64 = Subtarget.isPPC64(); 6472 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6473 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6474 6475 // Get the operands for the STACKRESTORE. 6476 SDValue Chain = Op.getOperand(0); 6477 SDValue SaveSP = Op.getOperand(1); 6478 6479 // Load the old link SP. 6480 SDValue LoadLinkSP = 6481 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6482 6483 // Restore the stack pointer. 6484 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6485 6486 // Store the old link SP. 6487 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6488 } 6489 6490 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6491 MachineFunction &MF = DAG.getMachineFunction(); 6492 bool isPPC64 = Subtarget.isPPC64(); 6493 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6494 6495 // Get current frame pointer save index. The users of this index will be 6496 // primarily DYNALLOC instructions. 6497 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6498 int RASI = FI->getReturnAddrSaveIndex(); 6499 6500 // If the frame pointer save index hasn't been defined yet. 6501 if (!RASI) { 6502 // Find out what the fix offset of the frame pointer save area. 6503 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6504 // Allocate the frame index for frame pointer save area. 6505 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6506 // Save the result. 6507 FI->setReturnAddrSaveIndex(RASI); 6508 } 6509 return DAG.getFrameIndex(RASI, PtrVT); 6510 } 6511 6512 SDValue 6513 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6514 MachineFunction &MF = DAG.getMachineFunction(); 6515 bool isPPC64 = Subtarget.isPPC64(); 6516 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6517 6518 // Get current frame pointer save index. The users of this index will be 6519 // primarily DYNALLOC instructions. 6520 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6521 int FPSI = FI->getFramePointerSaveIndex(); 6522 6523 // If the frame pointer save index hasn't been defined yet. 6524 if (!FPSI) { 6525 // Find out what the fix offset of the frame pointer save area. 6526 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6527 // Allocate the frame index for frame pointer save area. 6528 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6529 // Save the result. 6530 FI->setFramePointerSaveIndex(FPSI); 6531 } 6532 return DAG.getFrameIndex(FPSI, PtrVT); 6533 } 6534 6535 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6536 SelectionDAG &DAG) const { 6537 // Get the inputs. 6538 SDValue Chain = Op.getOperand(0); 6539 SDValue Size = Op.getOperand(1); 6540 SDLoc dl(Op); 6541 6542 // Get the correct type for pointers. 6543 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6544 // Negate the size. 6545 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6546 DAG.getConstant(0, dl, PtrVT), Size); 6547 // Construct a node for the frame pointer save index. 6548 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6549 // Build a DYNALLOC node. 6550 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6551 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6552 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6553 } 6554 6555 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 MachineFunction &MF = DAG.getMachineFunction(); 6558 6559 bool isPPC64 = Subtarget.isPPC64(); 6560 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6561 6562 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6563 return DAG.getFrameIndex(FI, PtrVT); 6564 } 6565 6566 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6567 SelectionDAG &DAG) const { 6568 SDLoc DL(Op); 6569 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6570 DAG.getVTList(MVT::i32, MVT::Other), 6571 Op.getOperand(0), Op.getOperand(1)); 6572 } 6573 6574 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6575 SelectionDAG &DAG) const { 6576 SDLoc DL(Op); 6577 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6578 Op.getOperand(0), Op.getOperand(1)); 6579 } 6580 6581 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6582 if (Op.getValueType().isVector()) 6583 return LowerVectorLoad(Op, DAG); 6584 6585 assert(Op.getValueType() == MVT::i1 && 6586 "Custom lowering only for i1 loads"); 6587 6588 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6589 6590 SDLoc dl(Op); 6591 LoadSDNode *LD = cast<LoadSDNode>(Op); 6592 6593 SDValue Chain = LD->getChain(); 6594 SDValue BasePtr = LD->getBasePtr(); 6595 MachineMemOperand *MMO = LD->getMemOperand(); 6596 6597 SDValue NewLD = 6598 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6599 BasePtr, MVT::i8, MMO); 6600 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6601 6602 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6603 return DAG.getMergeValues(Ops, dl); 6604 } 6605 6606 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6607 if (Op.getOperand(1).getValueType().isVector()) 6608 return LowerVectorStore(Op, DAG); 6609 6610 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6611 "Custom lowering only for i1 stores"); 6612 6613 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6614 6615 SDLoc dl(Op); 6616 StoreSDNode *ST = cast<StoreSDNode>(Op); 6617 6618 SDValue Chain = ST->getChain(); 6619 SDValue BasePtr = ST->getBasePtr(); 6620 SDValue Value = ST->getValue(); 6621 MachineMemOperand *MMO = ST->getMemOperand(); 6622 6623 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6624 Value); 6625 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6626 } 6627 6628 // FIXME: Remove this once the ANDI glue bug is fixed: 6629 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6630 assert(Op.getValueType() == MVT::i1 && 6631 "Custom lowering only for i1 results"); 6632 6633 SDLoc DL(Op); 6634 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6635 Op.getOperand(0)); 6636 } 6637 6638 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6639 /// possible. 6640 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6641 // Not FP? Not a fsel. 6642 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6643 !Op.getOperand(2).getValueType().isFloatingPoint()) 6644 return Op; 6645 6646 // We might be able to do better than this under some circumstances, but in 6647 // general, fsel-based lowering of select is a finite-math-only optimization. 6648 // For more information, see section F.3 of the 2.06 ISA specification. 6649 if (!DAG.getTarget().Options.NoInfsFPMath || 6650 !DAG.getTarget().Options.NoNaNsFPMath) 6651 return Op; 6652 // TODO: Propagate flags from the select rather than global settings. 6653 SDNodeFlags Flags; 6654 Flags.setNoInfs(true); 6655 Flags.setNoNaNs(true); 6656 6657 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6658 6659 EVT ResVT = Op.getValueType(); 6660 EVT CmpVT = Op.getOperand(0).getValueType(); 6661 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6662 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6663 SDLoc dl(Op); 6664 6665 // If the RHS of the comparison is a 0.0, we don't need to do the 6666 // subtraction at all. 6667 SDValue Sel1; 6668 if (isFloatingPointZero(RHS)) 6669 switch (CC) { 6670 default: break; // SETUO etc aren't handled by fsel. 6671 case ISD::SETNE: 6672 std::swap(TV, FV); 6673 LLVM_FALLTHROUGH; 6674 case ISD::SETEQ: 6675 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6676 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6677 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6678 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6679 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6680 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6681 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6682 case ISD::SETULT: 6683 case ISD::SETLT: 6684 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6685 LLVM_FALLTHROUGH; 6686 case ISD::SETOGE: 6687 case ISD::SETGE: 6688 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6689 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6690 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6691 case ISD::SETUGT: 6692 case ISD::SETGT: 6693 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6694 LLVM_FALLTHROUGH; 6695 case ISD::SETOLE: 6696 case ISD::SETLE: 6697 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6698 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6699 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6700 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6701 } 6702 6703 SDValue Cmp; 6704 switch (CC) { 6705 default: break; // SETUO etc aren't handled by fsel. 6706 case ISD::SETNE: 6707 std::swap(TV, FV); 6708 LLVM_FALLTHROUGH; 6709 case ISD::SETEQ: 6710 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6711 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6712 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6713 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6714 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6715 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6716 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6717 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6718 case ISD::SETULT: 6719 case ISD::SETLT: 6720 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6721 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6722 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6723 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6724 case ISD::SETOGE: 6725 case ISD::SETGE: 6726 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6727 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6728 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6729 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6730 case ISD::SETUGT: 6731 case ISD::SETGT: 6732 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6733 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6734 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6735 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6736 case ISD::SETOLE: 6737 case ISD::SETLE: 6738 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6739 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6740 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6741 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6742 } 6743 return Op; 6744 } 6745 6746 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6747 SelectionDAG &DAG, 6748 const SDLoc &dl) const { 6749 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6750 SDValue Src = Op.getOperand(0); 6751 if (Src.getValueType() == MVT::f32) 6752 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6753 6754 SDValue Tmp; 6755 switch (Op.getSimpleValueType().SimpleTy) { 6756 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6757 case MVT::i32: 6758 Tmp = DAG.getNode( 6759 Op.getOpcode() == ISD::FP_TO_SINT 6760 ? PPCISD::FCTIWZ 6761 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6762 dl, MVT::f64, Src); 6763 break; 6764 case MVT::i64: 6765 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6766 "i64 FP_TO_UINT is supported only with FPCVT"); 6767 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6768 PPCISD::FCTIDUZ, 6769 dl, MVT::f64, Src); 6770 break; 6771 } 6772 6773 // Convert the FP value to an int value through memory. 6774 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6775 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6776 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6777 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6778 MachinePointerInfo MPI = 6779 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6780 6781 // Emit a store to the stack slot. 6782 SDValue Chain; 6783 if (i32Stack) { 6784 MachineFunction &MF = DAG.getMachineFunction(); 6785 MachineMemOperand *MMO = 6786 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6787 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6788 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6789 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6790 } else 6791 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6792 6793 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6794 // add in a bias on big endian. 6795 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6796 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6797 DAG.getConstant(4, dl, FIPtr.getValueType())); 6798 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6799 } 6800 6801 RLI.Chain = Chain; 6802 RLI.Ptr = FIPtr; 6803 RLI.MPI = MPI; 6804 } 6805 6806 /// \brief Custom lowers floating point to integer conversions to use 6807 /// the direct move instructions available in ISA 2.07 to avoid the 6808 /// need for load/store combinations. 6809 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6810 SelectionDAG &DAG, 6811 const SDLoc &dl) const { 6812 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6813 SDValue Src = Op.getOperand(0); 6814 6815 if (Src.getValueType() == MVT::f32) 6816 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6817 6818 SDValue Tmp; 6819 switch (Op.getSimpleValueType().SimpleTy) { 6820 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6821 case MVT::i32: 6822 Tmp = DAG.getNode( 6823 Op.getOpcode() == ISD::FP_TO_SINT 6824 ? PPCISD::FCTIWZ 6825 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6826 dl, MVT::f64, Src); 6827 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6828 break; 6829 case MVT::i64: 6830 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6831 "i64 FP_TO_UINT is supported only with FPCVT"); 6832 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6833 PPCISD::FCTIDUZ, 6834 dl, MVT::f64, Src); 6835 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6836 break; 6837 } 6838 return Tmp; 6839 } 6840 6841 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6842 const SDLoc &dl) const { 6843 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6844 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6845 6846 ReuseLoadInfo RLI; 6847 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6848 6849 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6850 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6851 } 6852 6853 // We're trying to insert a regular store, S, and then a load, L. If the 6854 // incoming value, O, is a load, we might just be able to have our load use the 6855 // address used by O. However, we don't know if anything else will store to 6856 // that address before we can load from it. To prevent this situation, we need 6857 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6858 // the same chain operand as O, we create a token factor from the chain results 6859 // of O and L, and we replace all uses of O's chain result with that token 6860 // factor (see spliceIntoChain below for this last part). 6861 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6862 ReuseLoadInfo &RLI, 6863 SelectionDAG &DAG, 6864 ISD::LoadExtType ET) const { 6865 SDLoc dl(Op); 6866 if (ET == ISD::NON_EXTLOAD && 6867 (Op.getOpcode() == ISD::FP_TO_UINT || 6868 Op.getOpcode() == ISD::FP_TO_SINT) && 6869 isOperationLegalOrCustom(Op.getOpcode(), 6870 Op.getOperand(0).getValueType())) { 6871 6872 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6873 return true; 6874 } 6875 6876 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6877 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6878 LD->isNonTemporal()) 6879 return false; 6880 if (LD->getMemoryVT() != MemVT) 6881 return false; 6882 6883 RLI.Ptr = LD->getBasePtr(); 6884 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 6885 assert(LD->getAddressingMode() == ISD::PRE_INC && 6886 "Non-pre-inc AM on PPC?"); 6887 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 6888 LD->getOffset()); 6889 } 6890 6891 RLI.Chain = LD->getChain(); 6892 RLI.MPI = LD->getPointerInfo(); 6893 RLI.IsDereferenceable = LD->isDereferenceable(); 6894 RLI.IsInvariant = LD->isInvariant(); 6895 RLI.Alignment = LD->getAlignment(); 6896 RLI.AAInfo = LD->getAAInfo(); 6897 RLI.Ranges = LD->getRanges(); 6898 6899 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 6900 return true; 6901 } 6902 6903 // Given the head of the old chain, ResChain, insert a token factor containing 6904 // it and NewResChain, and make users of ResChain now be users of that token 6905 // factor. 6906 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 6907 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 6908 SDValue NewResChain, 6909 SelectionDAG &DAG) const { 6910 if (!ResChain) 6911 return; 6912 6913 SDLoc dl(NewResChain); 6914 6915 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6916 NewResChain, DAG.getUNDEF(MVT::Other)); 6917 assert(TF.getNode() != NewResChain.getNode() && 6918 "A new TF really is required here"); 6919 6920 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6921 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6922 } 6923 6924 /// \brief Analyze profitability of direct move 6925 /// prefer float load to int load plus direct move 6926 /// when there is no integer use of int load 6927 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 6928 SDNode *Origin = Op.getOperand(0).getNode(); 6929 if (Origin->getOpcode() != ISD::LOAD) 6930 return true; 6931 6932 // If there is no LXSIBZX/LXSIHZX, like Power8, 6933 // prefer direct move if the memory size is 1 or 2 bytes. 6934 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 6935 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 6936 return true; 6937 6938 for (SDNode::use_iterator UI = Origin->use_begin(), 6939 UE = Origin->use_end(); 6940 UI != UE; ++UI) { 6941 6942 // Only look at the users of the loaded value. 6943 if (UI.getUse().get().getResNo() != 0) 6944 continue; 6945 6946 if (UI->getOpcode() != ISD::SINT_TO_FP && 6947 UI->getOpcode() != ISD::UINT_TO_FP) 6948 return true; 6949 } 6950 6951 return false; 6952 } 6953 6954 /// \brief Custom lowers integer to floating point conversions to use 6955 /// the direct move instructions available in ISA 2.07 to avoid the 6956 /// need for load/store combinations. 6957 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 6958 SelectionDAG &DAG, 6959 const SDLoc &dl) const { 6960 assert((Op.getValueType() == MVT::f32 || 6961 Op.getValueType() == MVT::f64) && 6962 "Invalid floating point type as target of conversion"); 6963 assert(Subtarget.hasFPCVT() && 6964 "Int to FP conversions with direct moves require FPCVT"); 6965 SDValue FP; 6966 SDValue Src = Op.getOperand(0); 6967 bool SinglePrec = Op.getValueType() == MVT::f32; 6968 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 6969 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 6970 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 6971 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 6972 6973 if (WordInt) { 6974 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 6975 dl, MVT::f64, Src); 6976 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6977 } 6978 else { 6979 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 6980 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6981 } 6982 6983 return FP; 6984 } 6985 6986 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 6987 SelectionDAG &DAG) const { 6988 SDLoc dl(Op); 6989 6990 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 6991 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 6992 return SDValue(); 6993 6994 SDValue Value = Op.getOperand(0); 6995 // The values are now known to be -1 (false) or 1 (true). To convert this 6996 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 6997 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 6998 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 6999 7000 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7001 7002 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7003 7004 if (Op.getValueType() != MVT::v4f64) 7005 Value = DAG.getNode(ISD::FP_ROUND, dl, 7006 Op.getValueType(), Value, 7007 DAG.getIntPtrConstant(1, dl)); 7008 return Value; 7009 } 7010 7011 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7012 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7013 return SDValue(); 7014 7015 if (Op.getOperand(0).getValueType() == MVT::i1) 7016 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7017 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7018 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7019 7020 // If we have direct moves, we can do all the conversion, skip the store/load 7021 // however, without FPCVT we can't do most conversions. 7022 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7023 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7024 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7025 7026 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7027 "UINT_TO_FP is supported only with FPCVT"); 7028 7029 // If we have FCFIDS, then use it when converting to single-precision. 7030 // Otherwise, convert to double-precision and then round. 7031 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7032 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7033 : PPCISD::FCFIDS) 7034 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7035 : PPCISD::FCFID); 7036 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7037 ? MVT::f32 7038 : MVT::f64; 7039 7040 if (Op.getOperand(0).getValueType() == MVT::i64) { 7041 SDValue SINT = Op.getOperand(0); 7042 // When converting to single-precision, we actually need to convert 7043 // to double-precision first and then round to single-precision. 7044 // To avoid double-rounding effects during that operation, we have 7045 // to prepare the input operand. Bits that might be truncated when 7046 // converting to double-precision are replaced by a bit that won't 7047 // be lost at this stage, but is below the single-precision rounding 7048 // position. 7049 // 7050 // However, if -enable-unsafe-fp-math is in effect, accept double 7051 // rounding to avoid the extra overhead. 7052 if (Op.getValueType() == MVT::f32 && 7053 !Subtarget.hasFPCVT() && 7054 !DAG.getTarget().Options.UnsafeFPMath) { 7055 7056 // Twiddle input to make sure the low 11 bits are zero. (If this 7057 // is the case, we are guaranteed the value will fit into the 53 bit 7058 // mantissa of an IEEE double-precision value without rounding.) 7059 // If any of those low 11 bits were not zero originally, make sure 7060 // bit 12 (value 2048) is set instead, so that the final rounding 7061 // to single-precision gets the correct result. 7062 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7063 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7064 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7065 Round, DAG.getConstant(2047, dl, MVT::i64)); 7066 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7067 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7068 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7069 7070 // However, we cannot use that value unconditionally: if the magnitude 7071 // of the input value is small, the bit-twiddling we did above might 7072 // end up visibly changing the output. Fortunately, in that case, we 7073 // don't need to twiddle bits since the original input will convert 7074 // exactly to double-precision floating-point already. Therefore, 7075 // construct a conditional to use the original value if the top 11 7076 // bits are all sign-bit copies, and use the rounded value computed 7077 // above otherwise. 7078 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7079 SINT, DAG.getConstant(53, dl, MVT::i32)); 7080 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7081 Cond, DAG.getConstant(1, dl, MVT::i64)); 7082 Cond = DAG.getSetCC(dl, MVT::i32, 7083 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7084 7085 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7086 } 7087 7088 ReuseLoadInfo RLI; 7089 SDValue Bits; 7090 7091 MachineFunction &MF = DAG.getMachineFunction(); 7092 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7093 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7094 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7095 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7096 } else if (Subtarget.hasLFIWAX() && 7097 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7098 MachineMemOperand *MMO = 7099 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7100 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7101 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7102 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7103 DAG.getVTList(MVT::f64, MVT::Other), 7104 Ops, MVT::i32, MMO); 7105 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7106 } else if (Subtarget.hasFPCVT() && 7107 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7108 MachineMemOperand *MMO = 7109 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7110 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7111 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7112 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7113 DAG.getVTList(MVT::f64, MVT::Other), 7114 Ops, MVT::i32, MMO); 7115 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7116 } else if (((Subtarget.hasLFIWAX() && 7117 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7118 (Subtarget.hasFPCVT() && 7119 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7120 SINT.getOperand(0).getValueType() == MVT::i32) { 7121 MachineFrameInfo &MFI = MF.getFrameInfo(); 7122 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7123 7124 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7125 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7126 7127 SDValue Store = 7128 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7129 MachinePointerInfo::getFixedStack( 7130 DAG.getMachineFunction(), FrameIdx)); 7131 7132 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7133 "Expected an i32 store"); 7134 7135 RLI.Ptr = FIdx; 7136 RLI.Chain = Store; 7137 RLI.MPI = 7138 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7139 RLI.Alignment = 4; 7140 7141 MachineMemOperand *MMO = 7142 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7143 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7144 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7145 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7146 PPCISD::LFIWZX : PPCISD::LFIWAX, 7147 dl, DAG.getVTList(MVT::f64, MVT::Other), 7148 Ops, MVT::i32, MMO); 7149 } else 7150 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7151 7152 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7153 7154 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7155 FP = DAG.getNode(ISD::FP_ROUND, dl, 7156 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7157 return FP; 7158 } 7159 7160 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7161 "Unhandled INT_TO_FP type in custom expander!"); 7162 // Since we only generate this in 64-bit mode, we can take advantage of 7163 // 64-bit registers. In particular, sign extend the input value into the 7164 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7165 // then lfd it and fcfid it. 7166 MachineFunction &MF = DAG.getMachineFunction(); 7167 MachineFrameInfo &MFI = MF.getFrameInfo(); 7168 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7169 7170 SDValue Ld; 7171 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7172 ReuseLoadInfo RLI; 7173 bool ReusingLoad; 7174 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7175 DAG))) { 7176 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7177 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7178 7179 SDValue Store = 7180 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7181 MachinePointerInfo::getFixedStack( 7182 DAG.getMachineFunction(), FrameIdx)); 7183 7184 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7185 "Expected an i32 store"); 7186 7187 RLI.Ptr = FIdx; 7188 RLI.Chain = Store; 7189 RLI.MPI = 7190 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7191 RLI.Alignment = 4; 7192 } 7193 7194 MachineMemOperand *MMO = 7195 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7196 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7197 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7198 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7199 PPCISD::LFIWZX : PPCISD::LFIWAX, 7200 dl, DAG.getVTList(MVT::f64, MVT::Other), 7201 Ops, MVT::i32, MMO); 7202 if (ReusingLoad) 7203 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7204 } else { 7205 assert(Subtarget.isPPC64() && 7206 "i32->FP without LFIWAX supported only on PPC64"); 7207 7208 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7209 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7210 7211 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7212 Op.getOperand(0)); 7213 7214 // STD the extended value into the stack slot. 7215 SDValue Store = DAG.getStore( 7216 DAG.getEntryNode(), dl, Ext64, FIdx, 7217 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7218 7219 // Load the value as a double. 7220 Ld = DAG.getLoad( 7221 MVT::f64, dl, Store, FIdx, 7222 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7223 } 7224 7225 // FCFID it and return it. 7226 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7227 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7228 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7229 DAG.getIntPtrConstant(0, dl)); 7230 return FP; 7231 } 7232 7233 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7234 SelectionDAG &DAG) const { 7235 SDLoc dl(Op); 7236 /* 7237 The rounding mode is in bits 30:31 of FPSR, and has the following 7238 settings: 7239 00 Round to nearest 7240 01 Round to 0 7241 10 Round to +inf 7242 11 Round to -inf 7243 7244 FLT_ROUNDS, on the other hand, expects the following: 7245 -1 Undefined 7246 0 Round to 0 7247 1 Round to nearest 7248 2 Round to +inf 7249 3 Round to -inf 7250 7251 To perform the conversion, we do: 7252 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7253 */ 7254 7255 MachineFunction &MF = DAG.getMachineFunction(); 7256 EVT VT = Op.getValueType(); 7257 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7258 7259 // Save FP Control Word to register 7260 EVT NodeTys[] = { 7261 MVT::f64, // return register 7262 MVT::Glue // unused in this context 7263 }; 7264 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7265 7266 // Save FP register to stack slot 7267 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7268 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7269 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7270 MachinePointerInfo()); 7271 7272 // Load FP Control Word from low 32 bits of stack slot. 7273 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7274 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7275 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7276 7277 // Transform as necessary 7278 SDValue CWD1 = 7279 DAG.getNode(ISD::AND, dl, MVT::i32, 7280 CWD, DAG.getConstant(3, dl, MVT::i32)); 7281 SDValue CWD2 = 7282 DAG.getNode(ISD::SRL, dl, MVT::i32, 7283 DAG.getNode(ISD::AND, dl, MVT::i32, 7284 DAG.getNode(ISD::XOR, dl, MVT::i32, 7285 CWD, DAG.getConstant(3, dl, MVT::i32)), 7286 DAG.getConstant(3, dl, MVT::i32)), 7287 DAG.getConstant(1, dl, MVT::i32)); 7288 7289 SDValue RetVal = 7290 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7291 7292 return DAG.getNode((VT.getSizeInBits() < 16 ? 7293 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7294 } 7295 7296 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7297 EVT VT = Op.getValueType(); 7298 unsigned BitWidth = VT.getSizeInBits(); 7299 SDLoc dl(Op); 7300 assert(Op.getNumOperands() == 3 && 7301 VT == Op.getOperand(1).getValueType() && 7302 "Unexpected SHL!"); 7303 7304 // Expand into a bunch of logical ops. Note that these ops 7305 // depend on the PPC behavior for oversized shift amounts. 7306 SDValue Lo = Op.getOperand(0); 7307 SDValue Hi = Op.getOperand(1); 7308 SDValue Amt = Op.getOperand(2); 7309 EVT AmtVT = Amt.getValueType(); 7310 7311 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7312 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7313 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7314 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7315 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7316 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7317 DAG.getConstant(-BitWidth, dl, AmtVT)); 7318 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7319 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7320 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7321 SDValue OutOps[] = { OutLo, OutHi }; 7322 return DAG.getMergeValues(OutOps, dl); 7323 } 7324 7325 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7326 EVT VT = Op.getValueType(); 7327 SDLoc dl(Op); 7328 unsigned BitWidth = VT.getSizeInBits(); 7329 assert(Op.getNumOperands() == 3 && 7330 VT == Op.getOperand(1).getValueType() && 7331 "Unexpected SRL!"); 7332 7333 // Expand into a bunch of logical ops. Note that these ops 7334 // depend on the PPC behavior for oversized shift amounts. 7335 SDValue Lo = Op.getOperand(0); 7336 SDValue Hi = Op.getOperand(1); 7337 SDValue Amt = Op.getOperand(2); 7338 EVT AmtVT = Amt.getValueType(); 7339 7340 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7341 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7342 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7343 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7344 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7345 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7346 DAG.getConstant(-BitWidth, dl, AmtVT)); 7347 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7348 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7349 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7350 SDValue OutOps[] = { OutLo, OutHi }; 7351 return DAG.getMergeValues(OutOps, dl); 7352 } 7353 7354 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7355 SDLoc dl(Op); 7356 EVT VT = Op.getValueType(); 7357 unsigned BitWidth = VT.getSizeInBits(); 7358 assert(Op.getNumOperands() == 3 && 7359 VT == Op.getOperand(1).getValueType() && 7360 "Unexpected SRA!"); 7361 7362 // Expand into a bunch of logical ops, followed by a select_cc. 7363 SDValue Lo = Op.getOperand(0); 7364 SDValue Hi = Op.getOperand(1); 7365 SDValue Amt = Op.getOperand(2); 7366 EVT AmtVT = Amt.getValueType(); 7367 7368 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7369 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7370 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7371 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7372 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7373 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7374 DAG.getConstant(-BitWidth, dl, AmtVT)); 7375 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7376 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7377 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7378 Tmp4, Tmp6, ISD::SETLE); 7379 SDValue OutOps[] = { OutLo, OutHi }; 7380 return DAG.getMergeValues(OutOps, dl); 7381 } 7382 7383 //===----------------------------------------------------------------------===// 7384 // Vector related lowering. 7385 // 7386 7387 /// BuildSplatI - Build a canonical splati of Val with an element size of 7388 /// SplatSize. Cast the result to VT. 7389 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7390 SelectionDAG &DAG, const SDLoc &dl) { 7391 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7392 7393 static const MVT VTys[] = { // canonical VT to use for each size. 7394 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7395 }; 7396 7397 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7398 7399 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7400 if (Val == -1) 7401 SplatSize = 1; 7402 7403 EVT CanonicalVT = VTys[SplatSize-1]; 7404 7405 // Build a canonical splat for this value. 7406 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7407 } 7408 7409 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7410 /// specified intrinsic ID. 7411 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7412 const SDLoc &dl, EVT DestVT = MVT::Other) { 7413 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7414 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7415 DAG.getConstant(IID, dl, MVT::i32), Op); 7416 } 7417 7418 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7419 /// specified intrinsic ID. 7420 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7421 SelectionDAG &DAG, const SDLoc &dl, 7422 EVT DestVT = MVT::Other) { 7423 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7424 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7425 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7426 } 7427 7428 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7429 /// specified intrinsic ID. 7430 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7431 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7432 EVT DestVT = MVT::Other) { 7433 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7434 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7435 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7436 } 7437 7438 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7439 /// amount. The result has the specified value type. 7440 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7441 SelectionDAG &DAG, const SDLoc &dl) { 7442 // Force LHS/RHS to be the right type. 7443 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7444 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7445 7446 int Ops[16]; 7447 for (unsigned i = 0; i != 16; ++i) 7448 Ops[i] = i + Amt; 7449 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7450 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7451 } 7452 7453 /// Do we have an efficient pattern in a .td file for this node? 7454 /// 7455 /// \param V - pointer to the BuildVectorSDNode being matched 7456 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7457 /// 7458 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7459 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7460 /// the opposite is true (expansion is beneficial) are: 7461 /// - The node builds a vector out of integers that are not 32 or 64-bits 7462 /// - The node builds a vector out of constants 7463 /// - The node is a "load-and-splat" 7464 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7465 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7466 bool HasDirectMove) { 7467 EVT VecVT = V->getValueType(0); 7468 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 || 7469 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7470 if (!RightType) 7471 return false; 7472 7473 bool IsSplat = true; 7474 bool IsLoad = false; 7475 SDValue Op0 = V->getOperand(0); 7476 7477 // This function is called in a block that confirms the node is not a constant 7478 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7479 // different constants. 7480 if (V->isConstant()) 7481 return false; 7482 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7483 if (V->getOperand(i).isUndef()) 7484 return false; 7485 // We want to expand nodes that represent load-and-splat even if the 7486 // loaded value is a floating point truncation or conversion to int. 7487 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7488 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7489 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7490 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7491 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7492 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7493 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7494 IsLoad = true; 7495 // If the operands are different or the input is not a load and has more 7496 // uses than just this BV node, then it isn't a splat. 7497 if (V->getOperand(i) != Op0 || 7498 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7499 IsSplat = false; 7500 } 7501 return !(IsSplat && IsLoad); 7502 } 7503 7504 // If this is a case we can't handle, return null and let the default 7505 // expansion code take care of it. If we CAN select this case, and if it 7506 // selects to a single instruction, return Op. Otherwise, if we can codegen 7507 // this case more efficiently than a constant pool load, lower it to the 7508 // sequence of ops that should be used. 7509 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7510 SelectionDAG &DAG) const { 7511 SDLoc dl(Op); 7512 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7513 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7514 7515 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7516 // We first build an i32 vector, load it into a QPX register, 7517 // then convert it to a floating-point vector and compare it 7518 // to a zero vector to get the boolean result. 7519 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7520 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7521 MachinePointerInfo PtrInfo = 7522 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7523 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7524 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7525 7526 assert(BVN->getNumOperands() == 4 && 7527 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7528 7529 bool IsConst = true; 7530 for (unsigned i = 0; i < 4; ++i) { 7531 if (BVN->getOperand(i).isUndef()) continue; 7532 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7533 IsConst = false; 7534 break; 7535 } 7536 } 7537 7538 if (IsConst) { 7539 Constant *One = 7540 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7541 Constant *NegOne = 7542 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7543 7544 Constant *CV[4]; 7545 for (unsigned i = 0; i < 4; ++i) { 7546 if (BVN->getOperand(i).isUndef()) 7547 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7548 else if (isNullConstant(BVN->getOperand(i))) 7549 CV[i] = NegOne; 7550 else 7551 CV[i] = One; 7552 } 7553 7554 Constant *CP = ConstantVector::get(CV); 7555 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7556 16 /* alignment */); 7557 7558 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7559 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7560 return DAG.getMemIntrinsicNode( 7561 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7562 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7563 } 7564 7565 SmallVector<SDValue, 4> Stores; 7566 for (unsigned i = 0; i < 4; ++i) { 7567 if (BVN->getOperand(i).isUndef()) continue; 7568 7569 unsigned Offset = 4*i; 7570 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7571 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7572 7573 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7574 if (StoreSize > 4) { 7575 Stores.push_back( 7576 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7577 PtrInfo.getWithOffset(Offset), MVT::i32)); 7578 } else { 7579 SDValue StoreValue = BVN->getOperand(i); 7580 if (StoreSize < 4) 7581 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7582 7583 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7584 PtrInfo.getWithOffset(Offset))); 7585 } 7586 } 7587 7588 SDValue StoreChain; 7589 if (!Stores.empty()) 7590 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7591 else 7592 StoreChain = DAG.getEntryNode(); 7593 7594 // Now load from v4i32 into the QPX register; this will extend it to 7595 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7596 // is typed as v4f64 because the QPX register integer states are not 7597 // explicitly represented. 7598 7599 SDValue Ops[] = {StoreChain, 7600 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7601 FIdx}; 7602 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7603 7604 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7605 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7606 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7607 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7608 LoadedVect); 7609 7610 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7611 7612 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7613 } 7614 7615 // All other QPX vectors are handled by generic code. 7616 if (Subtarget.hasQPX()) 7617 return SDValue(); 7618 7619 // Check if this is a splat of a constant value. 7620 APInt APSplatBits, APSplatUndef; 7621 unsigned SplatBitSize; 7622 bool HasAnyUndefs; 7623 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7624 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7625 SplatBitSize > 32) { 7626 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7627 // lowered to VSX instructions under certain conditions. 7628 // Without VSX, there is no pattern more efficient than expanding the node. 7629 if (Subtarget.hasVSX() && 7630 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove())) 7631 return Op; 7632 return SDValue(); 7633 } 7634 7635 unsigned SplatBits = APSplatBits.getZExtValue(); 7636 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7637 unsigned SplatSize = SplatBitSize / 8; 7638 7639 // First, handle single instruction cases. 7640 7641 // All zeros? 7642 if (SplatBits == 0) { 7643 // Canonicalize all zero vectors to be v4i32. 7644 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7645 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7646 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7647 } 7648 return Op; 7649 } 7650 7651 // We have XXSPLTIB for constant splats one byte wide 7652 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7653 // This is a splat of 1-byte elements with some elements potentially undef. 7654 // Rather than trying to match undef in the SDAG patterns, ensure that all 7655 // elements are the same constant. 7656 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7657 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7658 dl, MVT::i32)); 7659 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7660 if (Op.getValueType() != MVT::v16i8) 7661 return DAG.getBitcast(Op.getValueType(), NewBV); 7662 return NewBV; 7663 } 7664 7665 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 7666 // detect that constant splats like v8i16: 0xABAB are really just splats 7667 // of a 1-byte constant. In this case, we need to convert the node to a 7668 // splat of v16i8 and a bitcast. 7669 if (Op.getValueType() != MVT::v16i8) 7670 return DAG.getBitcast(Op.getValueType(), 7671 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 7672 7673 return Op; 7674 } 7675 7676 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7677 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7678 (32-SplatBitSize)); 7679 if (SextVal >= -16 && SextVal <= 15) 7680 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7681 7682 // Two instruction sequences. 7683 7684 // If this value is in the range [-32,30] and is even, use: 7685 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7686 // If this value is in the range [17,31] and is odd, use: 7687 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7688 // If this value is in the range [-31,-17] and is odd, use: 7689 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7690 // Note the last two are three-instruction sequences. 7691 if (SextVal >= -32 && SextVal <= 31) { 7692 // To avoid having these optimizations undone by constant folding, 7693 // we convert to a pseudo that will be expanded later into one of 7694 // the above forms. 7695 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7696 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7697 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7698 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7699 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7700 if (VT == Op.getValueType()) 7701 return RetVal; 7702 else 7703 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7704 } 7705 7706 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7707 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7708 // for fneg/fabs. 7709 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7710 // Make -1 and vspltisw -1: 7711 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7712 7713 // Make the VSLW intrinsic, computing 0x8000_0000. 7714 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7715 OnesV, DAG, dl); 7716 7717 // xor by OnesV to invert it. 7718 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7719 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7720 } 7721 7722 // Check to see if this is a wide variety of vsplti*, binop self cases. 7723 static const signed char SplatCsts[] = { 7724 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7725 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7726 }; 7727 7728 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7729 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7730 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7731 int i = SplatCsts[idx]; 7732 7733 // Figure out what shift amount will be used by altivec if shifted by i in 7734 // this splat size. 7735 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7736 7737 // vsplti + shl self. 7738 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7739 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7740 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7741 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7742 Intrinsic::ppc_altivec_vslw 7743 }; 7744 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7745 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7746 } 7747 7748 // vsplti + srl self. 7749 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7750 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7751 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7752 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7753 Intrinsic::ppc_altivec_vsrw 7754 }; 7755 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7756 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7757 } 7758 7759 // vsplti + sra self. 7760 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7761 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7762 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7763 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7764 Intrinsic::ppc_altivec_vsraw 7765 }; 7766 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7767 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7768 } 7769 7770 // vsplti + rol self. 7771 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7772 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7773 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7774 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7775 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7776 Intrinsic::ppc_altivec_vrlw 7777 }; 7778 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7779 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7780 } 7781 7782 // t = vsplti c, result = vsldoi t, t, 1 7783 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7784 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7785 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7786 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7787 } 7788 // t = vsplti c, result = vsldoi t, t, 2 7789 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7790 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7791 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7792 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7793 } 7794 // t = vsplti c, result = vsldoi t, t, 3 7795 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7796 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7797 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7798 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7799 } 7800 } 7801 7802 return SDValue(); 7803 } 7804 7805 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7806 /// the specified operations to build the shuffle. 7807 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7808 SDValue RHS, SelectionDAG &DAG, 7809 const SDLoc &dl) { 7810 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7811 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7812 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7813 7814 enum { 7815 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7816 OP_VMRGHW, 7817 OP_VMRGLW, 7818 OP_VSPLTISW0, 7819 OP_VSPLTISW1, 7820 OP_VSPLTISW2, 7821 OP_VSPLTISW3, 7822 OP_VSLDOI4, 7823 OP_VSLDOI8, 7824 OP_VSLDOI12 7825 }; 7826 7827 if (OpNum == OP_COPY) { 7828 if (LHSID == (1*9+2)*9+3) return LHS; 7829 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7830 return RHS; 7831 } 7832 7833 SDValue OpLHS, OpRHS; 7834 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7835 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7836 7837 int ShufIdxs[16]; 7838 switch (OpNum) { 7839 default: llvm_unreachable("Unknown i32 permute!"); 7840 case OP_VMRGHW: 7841 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7842 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7843 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7844 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7845 break; 7846 case OP_VMRGLW: 7847 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7848 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7849 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7850 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7851 break; 7852 case OP_VSPLTISW0: 7853 for (unsigned i = 0; i != 16; ++i) 7854 ShufIdxs[i] = (i&3)+0; 7855 break; 7856 case OP_VSPLTISW1: 7857 for (unsigned i = 0; i != 16; ++i) 7858 ShufIdxs[i] = (i&3)+4; 7859 break; 7860 case OP_VSPLTISW2: 7861 for (unsigned i = 0; i != 16; ++i) 7862 ShufIdxs[i] = (i&3)+8; 7863 break; 7864 case OP_VSPLTISW3: 7865 for (unsigned i = 0; i != 16; ++i) 7866 ShufIdxs[i] = (i&3)+12; 7867 break; 7868 case OP_VSLDOI4: 7869 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7870 case OP_VSLDOI8: 7871 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7872 case OP_VSLDOI12: 7873 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7874 } 7875 EVT VT = OpLHS.getValueType(); 7876 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7877 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7878 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7879 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7880 } 7881 7882 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 7883 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 7884 /// return the code it can be lowered into. Worst case, it can always be 7885 /// lowered into a vperm. 7886 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7887 SelectionDAG &DAG) const { 7888 SDLoc dl(Op); 7889 SDValue V1 = Op.getOperand(0); 7890 SDValue V2 = Op.getOperand(1); 7891 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7892 EVT VT = Op.getValueType(); 7893 bool isLittleEndian = Subtarget.isLittleEndian(); 7894 7895 unsigned ShiftElts, InsertAtByte; 7896 bool Swap; 7897 if (Subtarget.hasP9Vector() && 7898 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 7899 isLittleEndian)) { 7900 if (Swap) 7901 std::swap(V1, V2); 7902 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7903 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 7904 if (ShiftElts) { 7905 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 7906 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7907 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl, 7908 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7909 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7910 } 7911 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2, 7912 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7913 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 7914 } 7915 7916 7917 if (Subtarget.hasVSX() && 7918 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 7919 if (Swap) 7920 std::swap(V1, V2); 7921 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7922 SDValue Conv2 = 7923 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 7924 7925 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 7926 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7927 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 7928 } 7929 7930 if (Subtarget.hasVSX() && 7931 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 7932 if (Swap) 7933 std::swap(V1, V2); 7934 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 7935 SDValue Conv2 = 7936 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 7937 7938 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 7939 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7940 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 7941 } 7942 7943 if (Subtarget.hasP9Vector()) { 7944 if (PPC::isXXBRHShuffleMask(SVOp)) { 7945 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 7946 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 7947 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 7948 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 7949 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7950 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 7951 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 7952 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 7953 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 7954 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 7955 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 7956 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 7957 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 7958 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 7959 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 7960 } 7961 } 7962 7963 if (Subtarget.hasVSX()) { 7964 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 7965 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 7966 7967 // If the source for the shuffle is a scalar_to_vector that came from a 7968 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 7969 if (Subtarget.hasP9Vector() && 7970 ((isLittleEndian && SplatIdx == 3) || 7971 (!isLittleEndian && SplatIdx == 0))) { 7972 SDValue Src = V1.getOperand(0); 7973 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 7974 Src.getOperand(0).getOpcode() == ISD::LOAD && 7975 Src.getOperand(0).hasOneUse()) 7976 return V1; 7977 } 7978 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 7979 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 7980 DAG.getConstant(SplatIdx, dl, MVT::i32)); 7981 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 7982 } 7983 7984 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 7985 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 7986 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 7987 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 7988 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 7989 } 7990 } 7991 7992 if (Subtarget.hasQPX()) { 7993 if (VT.getVectorNumElements() != 4) 7994 return SDValue(); 7995 7996 if (V2.isUndef()) V2 = V1; 7997 7998 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 7999 if (AlignIdx != -1) { 8000 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8001 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8002 } else if (SVOp->isSplat()) { 8003 int SplatIdx = SVOp->getSplatIndex(); 8004 if (SplatIdx >= 4) { 8005 std::swap(V1, V2); 8006 SplatIdx -= 4; 8007 } 8008 8009 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8010 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8011 } 8012 8013 // Lower this into a qvgpci/qvfperm pair. 8014 8015 // Compute the qvgpci literal 8016 unsigned idx = 0; 8017 for (unsigned i = 0; i < 4; ++i) { 8018 int m = SVOp->getMaskElt(i); 8019 unsigned mm = m >= 0 ? (unsigned) m : i; 8020 idx |= mm << (3-i)*3; 8021 } 8022 8023 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8024 DAG.getConstant(idx, dl, MVT::i32)); 8025 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8026 } 8027 8028 // Cases that are handled by instructions that take permute immediates 8029 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8030 // selected by the instruction selector. 8031 if (V2.isUndef()) { 8032 if (PPC::isSplatShuffleMask(SVOp, 1) || 8033 PPC::isSplatShuffleMask(SVOp, 2) || 8034 PPC::isSplatShuffleMask(SVOp, 4) || 8035 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8036 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8037 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8038 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8039 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8040 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8041 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8042 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8043 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8044 (Subtarget.hasP8Altivec() && ( 8045 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8046 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8047 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8048 return Op; 8049 } 8050 } 8051 8052 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8053 // and produce a fixed permutation. If any of these match, do not lower to 8054 // VPERM. 8055 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8056 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8057 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8058 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8059 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8060 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8061 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8062 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8063 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8064 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8065 (Subtarget.hasP8Altivec() && ( 8066 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8067 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8068 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8069 return Op; 8070 8071 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8072 // perfect shuffle table to emit an optimal matching sequence. 8073 ArrayRef<int> PermMask = SVOp->getMask(); 8074 8075 unsigned PFIndexes[4]; 8076 bool isFourElementShuffle = true; 8077 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8078 unsigned EltNo = 8; // Start out undef. 8079 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8080 if (PermMask[i*4+j] < 0) 8081 continue; // Undef, ignore it. 8082 8083 unsigned ByteSource = PermMask[i*4+j]; 8084 if ((ByteSource & 3) != j) { 8085 isFourElementShuffle = false; 8086 break; 8087 } 8088 8089 if (EltNo == 8) { 8090 EltNo = ByteSource/4; 8091 } else if (EltNo != ByteSource/4) { 8092 isFourElementShuffle = false; 8093 break; 8094 } 8095 } 8096 PFIndexes[i] = EltNo; 8097 } 8098 8099 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8100 // perfect shuffle vector to determine if it is cost effective to do this as 8101 // discrete instructions, or whether we should use a vperm. 8102 // For now, we skip this for little endian until such time as we have a 8103 // little-endian perfect shuffle table. 8104 if (isFourElementShuffle && !isLittleEndian) { 8105 // Compute the index in the perfect shuffle table. 8106 unsigned PFTableIndex = 8107 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8108 8109 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8110 unsigned Cost = (PFEntry >> 30); 8111 8112 // Determining when to avoid vperm is tricky. Many things affect the cost 8113 // of vperm, particularly how many times the perm mask needs to be computed. 8114 // For example, if the perm mask can be hoisted out of a loop or is already 8115 // used (perhaps because there are multiple permutes with the same shuffle 8116 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8117 // the loop requires an extra register. 8118 // 8119 // As a compromise, we only emit discrete instructions if the shuffle can be 8120 // generated in 3 or fewer operations. When we have loop information 8121 // available, if this block is within a loop, we should avoid using vperm 8122 // for 3-operation perms and use a constant pool load instead. 8123 if (Cost < 3) 8124 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8125 } 8126 8127 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8128 // vector that will get spilled to the constant pool. 8129 if (V2.isUndef()) V2 = V1; 8130 8131 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8132 // that it is in input element units, not in bytes. Convert now. 8133 8134 // For little endian, the order of the input vectors is reversed, and 8135 // the permutation mask is complemented with respect to 31. This is 8136 // necessary to produce proper semantics with the big-endian-biased vperm 8137 // instruction. 8138 EVT EltVT = V1.getValueType().getVectorElementType(); 8139 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8140 8141 SmallVector<SDValue, 16> ResultMask; 8142 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8143 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8144 8145 for (unsigned j = 0; j != BytesPerElement; ++j) 8146 if (isLittleEndian) 8147 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8148 dl, MVT::i32)); 8149 else 8150 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8151 MVT::i32)); 8152 } 8153 8154 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8155 if (isLittleEndian) 8156 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8157 V2, V1, VPermMask); 8158 else 8159 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8160 V1, V2, VPermMask); 8161 } 8162 8163 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8164 /// vector comparison. If it is, return true and fill in Opc/isDot with 8165 /// information about the intrinsic. 8166 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8167 bool &isDot, const PPCSubtarget &Subtarget) { 8168 unsigned IntrinsicID = 8169 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8170 CompareOpc = -1; 8171 isDot = false; 8172 switch (IntrinsicID) { 8173 default: 8174 return false; 8175 // Comparison predicates. 8176 case Intrinsic::ppc_altivec_vcmpbfp_p: 8177 CompareOpc = 966; 8178 isDot = true; 8179 break; 8180 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8181 CompareOpc = 198; 8182 isDot = true; 8183 break; 8184 case Intrinsic::ppc_altivec_vcmpequb_p: 8185 CompareOpc = 6; 8186 isDot = true; 8187 break; 8188 case Intrinsic::ppc_altivec_vcmpequh_p: 8189 CompareOpc = 70; 8190 isDot = true; 8191 break; 8192 case Intrinsic::ppc_altivec_vcmpequw_p: 8193 CompareOpc = 134; 8194 isDot = true; 8195 break; 8196 case Intrinsic::ppc_altivec_vcmpequd_p: 8197 if (Subtarget.hasP8Altivec()) { 8198 CompareOpc = 199; 8199 isDot = true; 8200 } else 8201 return false; 8202 break; 8203 case Intrinsic::ppc_altivec_vcmpneb_p: 8204 case Intrinsic::ppc_altivec_vcmpneh_p: 8205 case Intrinsic::ppc_altivec_vcmpnew_p: 8206 case Intrinsic::ppc_altivec_vcmpnezb_p: 8207 case Intrinsic::ppc_altivec_vcmpnezh_p: 8208 case Intrinsic::ppc_altivec_vcmpnezw_p: 8209 if (Subtarget.hasP9Altivec()) { 8210 switch (IntrinsicID) { 8211 default: 8212 llvm_unreachable("Unknown comparison intrinsic."); 8213 case Intrinsic::ppc_altivec_vcmpneb_p: 8214 CompareOpc = 7; 8215 break; 8216 case Intrinsic::ppc_altivec_vcmpneh_p: 8217 CompareOpc = 71; 8218 break; 8219 case Intrinsic::ppc_altivec_vcmpnew_p: 8220 CompareOpc = 135; 8221 break; 8222 case Intrinsic::ppc_altivec_vcmpnezb_p: 8223 CompareOpc = 263; 8224 break; 8225 case Intrinsic::ppc_altivec_vcmpnezh_p: 8226 CompareOpc = 327; 8227 break; 8228 case Intrinsic::ppc_altivec_vcmpnezw_p: 8229 CompareOpc = 391; 8230 break; 8231 } 8232 isDot = true; 8233 } else 8234 return false; 8235 break; 8236 case Intrinsic::ppc_altivec_vcmpgefp_p: 8237 CompareOpc = 454; 8238 isDot = true; 8239 break; 8240 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8241 CompareOpc = 710; 8242 isDot = true; 8243 break; 8244 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8245 CompareOpc = 774; 8246 isDot = true; 8247 break; 8248 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8249 CompareOpc = 838; 8250 isDot = true; 8251 break; 8252 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8253 CompareOpc = 902; 8254 isDot = true; 8255 break; 8256 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8257 if (Subtarget.hasP8Altivec()) { 8258 CompareOpc = 967; 8259 isDot = true; 8260 } else 8261 return false; 8262 break; 8263 case Intrinsic::ppc_altivec_vcmpgtub_p: 8264 CompareOpc = 518; 8265 isDot = true; 8266 break; 8267 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8268 CompareOpc = 582; 8269 isDot = true; 8270 break; 8271 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8272 CompareOpc = 646; 8273 isDot = true; 8274 break; 8275 case Intrinsic::ppc_altivec_vcmpgtud_p: 8276 if (Subtarget.hasP8Altivec()) { 8277 CompareOpc = 711; 8278 isDot = true; 8279 } else 8280 return false; 8281 break; 8282 8283 // VSX predicate comparisons use the same infrastructure 8284 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8285 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8286 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8287 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8288 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8289 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8290 if (Subtarget.hasVSX()) { 8291 switch (IntrinsicID) { 8292 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8293 CompareOpc = 99; 8294 break; 8295 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8296 CompareOpc = 115; 8297 break; 8298 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8299 CompareOpc = 107; 8300 break; 8301 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8302 CompareOpc = 67; 8303 break; 8304 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8305 CompareOpc = 83; 8306 break; 8307 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8308 CompareOpc = 75; 8309 break; 8310 } 8311 isDot = true; 8312 } else 8313 return false; 8314 break; 8315 8316 // Normal Comparisons. 8317 case Intrinsic::ppc_altivec_vcmpbfp: 8318 CompareOpc = 966; 8319 break; 8320 case Intrinsic::ppc_altivec_vcmpeqfp: 8321 CompareOpc = 198; 8322 break; 8323 case Intrinsic::ppc_altivec_vcmpequb: 8324 CompareOpc = 6; 8325 break; 8326 case Intrinsic::ppc_altivec_vcmpequh: 8327 CompareOpc = 70; 8328 break; 8329 case Intrinsic::ppc_altivec_vcmpequw: 8330 CompareOpc = 134; 8331 break; 8332 case Intrinsic::ppc_altivec_vcmpequd: 8333 if (Subtarget.hasP8Altivec()) 8334 CompareOpc = 199; 8335 else 8336 return false; 8337 break; 8338 case Intrinsic::ppc_altivec_vcmpneb: 8339 case Intrinsic::ppc_altivec_vcmpneh: 8340 case Intrinsic::ppc_altivec_vcmpnew: 8341 case Intrinsic::ppc_altivec_vcmpnezb: 8342 case Intrinsic::ppc_altivec_vcmpnezh: 8343 case Intrinsic::ppc_altivec_vcmpnezw: 8344 if (Subtarget.hasP9Altivec()) 8345 switch (IntrinsicID) { 8346 default: 8347 llvm_unreachable("Unknown comparison intrinsic."); 8348 case Intrinsic::ppc_altivec_vcmpneb: 8349 CompareOpc = 7; 8350 break; 8351 case Intrinsic::ppc_altivec_vcmpneh: 8352 CompareOpc = 71; 8353 break; 8354 case Intrinsic::ppc_altivec_vcmpnew: 8355 CompareOpc = 135; 8356 break; 8357 case Intrinsic::ppc_altivec_vcmpnezb: 8358 CompareOpc = 263; 8359 break; 8360 case Intrinsic::ppc_altivec_vcmpnezh: 8361 CompareOpc = 327; 8362 break; 8363 case Intrinsic::ppc_altivec_vcmpnezw: 8364 CompareOpc = 391; 8365 break; 8366 } 8367 else 8368 return false; 8369 break; 8370 case Intrinsic::ppc_altivec_vcmpgefp: 8371 CompareOpc = 454; 8372 break; 8373 case Intrinsic::ppc_altivec_vcmpgtfp: 8374 CompareOpc = 710; 8375 break; 8376 case Intrinsic::ppc_altivec_vcmpgtsb: 8377 CompareOpc = 774; 8378 break; 8379 case Intrinsic::ppc_altivec_vcmpgtsh: 8380 CompareOpc = 838; 8381 break; 8382 case Intrinsic::ppc_altivec_vcmpgtsw: 8383 CompareOpc = 902; 8384 break; 8385 case Intrinsic::ppc_altivec_vcmpgtsd: 8386 if (Subtarget.hasP8Altivec()) 8387 CompareOpc = 967; 8388 else 8389 return false; 8390 break; 8391 case Intrinsic::ppc_altivec_vcmpgtub: 8392 CompareOpc = 518; 8393 break; 8394 case Intrinsic::ppc_altivec_vcmpgtuh: 8395 CompareOpc = 582; 8396 break; 8397 case Intrinsic::ppc_altivec_vcmpgtuw: 8398 CompareOpc = 646; 8399 break; 8400 case Intrinsic::ppc_altivec_vcmpgtud: 8401 if (Subtarget.hasP8Altivec()) 8402 CompareOpc = 711; 8403 else 8404 return false; 8405 break; 8406 } 8407 return true; 8408 } 8409 8410 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8411 /// lower, do it, otherwise return null. 8412 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8413 SelectionDAG &DAG) const { 8414 unsigned IntrinsicID = 8415 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8416 8417 SDLoc dl(Op); 8418 8419 if (IntrinsicID == Intrinsic::thread_pointer) { 8420 // Reads the thread pointer register, used for __builtin_thread_pointer. 8421 if (Subtarget.isPPC64()) 8422 return DAG.getRegister(PPC::X13, MVT::i64); 8423 return DAG.getRegister(PPC::R2, MVT::i32); 8424 } 8425 8426 // We are looking for absolute values here. 8427 // The idea is to try to fit one of two patterns: 8428 // max (a, (0-a)) OR max ((0-a), a) 8429 if (Subtarget.hasP9Vector() && 8430 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 8431 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 8432 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 8433 SDValue V1 = Op.getOperand(1); 8434 SDValue V2 = Op.getOperand(2); 8435 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 8436 (V1.getSimpleValueType() == MVT::v4i32 || 8437 V1.getSimpleValueType() == MVT::v8i16 || 8438 V1.getSimpleValueType() == MVT::v16i8)) { 8439 if ( V1.getOpcode() == ISD::SUB && 8440 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 8441 V1.getOperand(1) == V2 ) { 8442 // Generate the abs instruction with the operands 8443 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 8444 } 8445 8446 if ( V2.getOpcode() == ISD::SUB && 8447 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 8448 V2.getOperand(1) == V1 ) { 8449 // Generate the abs instruction with the operands 8450 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 8451 } 8452 } 8453 } 8454 8455 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8456 // opcode number of the comparison. 8457 int CompareOpc; 8458 bool isDot; 8459 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8460 return SDValue(); // Don't custom lower most intrinsics. 8461 8462 // If this is a non-dot comparison, make the VCMP node and we are done. 8463 if (!isDot) { 8464 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8465 Op.getOperand(1), Op.getOperand(2), 8466 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8467 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8468 } 8469 8470 // Create the PPCISD altivec 'dot' comparison node. 8471 SDValue Ops[] = { 8472 Op.getOperand(2), // LHS 8473 Op.getOperand(3), // RHS 8474 DAG.getConstant(CompareOpc, dl, MVT::i32) 8475 }; 8476 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8477 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8478 8479 // Now that we have the comparison, emit a copy from the CR to a GPR. 8480 // This is flagged to the above dot comparison. 8481 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8482 DAG.getRegister(PPC::CR6, MVT::i32), 8483 CompNode.getValue(1)); 8484 8485 // Unpack the result based on how the target uses it. 8486 unsigned BitNo; // Bit # of CR6. 8487 bool InvertBit; // Invert result? 8488 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8489 default: // Can't happen, don't crash on invalid number though. 8490 case 0: // Return the value of the EQ bit of CR6. 8491 BitNo = 0; InvertBit = false; 8492 break; 8493 case 1: // Return the inverted value of the EQ bit of CR6. 8494 BitNo = 0; InvertBit = true; 8495 break; 8496 case 2: // Return the value of the LT bit of CR6. 8497 BitNo = 2; InvertBit = false; 8498 break; 8499 case 3: // Return the inverted value of the LT bit of CR6. 8500 BitNo = 2; InvertBit = true; 8501 break; 8502 } 8503 8504 // Shift the bit into the low position. 8505 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8506 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8507 // Isolate the bit. 8508 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8509 DAG.getConstant(1, dl, MVT::i32)); 8510 8511 // If we are supposed to, toggle the bit. 8512 if (InvertBit) 8513 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8514 DAG.getConstant(1, dl, MVT::i32)); 8515 return Flags; 8516 } 8517 8518 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8519 SelectionDAG &DAG) const { 8520 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 8521 // the beginning of the argument list. 8522 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 8523 SDLoc DL(Op); 8524 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 8525 case Intrinsic::ppc_cfence: { 8526 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 8527 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 8528 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 8529 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 8530 Op.getOperand(ArgStart + 1)), 8531 Op.getOperand(0)), 8532 0); 8533 } 8534 default: 8535 break; 8536 } 8537 return SDValue(); 8538 } 8539 8540 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 8541 // Check for a DIV with the same operands as this REM. 8542 for (auto UI : Op.getOperand(1)->uses()) { 8543 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 8544 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 8545 if (UI->getOperand(0) == Op.getOperand(0) && 8546 UI->getOperand(1) == Op.getOperand(1)) 8547 return SDValue(); 8548 } 8549 return Op; 8550 } 8551 8552 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8553 SelectionDAG &DAG) const { 8554 SDLoc dl(Op); 8555 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8556 // instructions), but for smaller types, we need to first extend up to v2i32 8557 // before doing going farther. 8558 if (Op.getValueType() == MVT::v2i64) { 8559 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8560 if (ExtVT != MVT::v2i32) { 8561 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8562 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8563 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8564 ExtVT.getVectorElementType(), 4))); 8565 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8566 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8567 DAG.getValueType(MVT::v2i32)); 8568 } 8569 8570 return Op; 8571 } 8572 8573 return SDValue(); 8574 } 8575 8576 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8577 SelectionDAG &DAG) const { 8578 SDLoc dl(Op); 8579 // Create a stack slot that is 16-byte aligned. 8580 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8581 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8582 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8583 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8584 8585 // Store the input value into Value#0 of the stack slot. 8586 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8587 MachinePointerInfo()); 8588 // Load it out. 8589 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8590 } 8591 8592 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8593 SelectionDAG &DAG) const { 8594 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8595 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8596 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8597 // We have legal lowering for constant indices but not for variable ones. 8598 if (C) 8599 return Op; 8600 return SDValue(); 8601 } 8602 8603 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8604 SelectionDAG &DAG) const { 8605 SDLoc dl(Op); 8606 SDNode *N = Op.getNode(); 8607 8608 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 8609 "Unknown extract_vector_elt type"); 8610 8611 SDValue Value = N->getOperand(0); 8612 8613 // The first part of this is like the store lowering except that we don't 8614 // need to track the chain. 8615 8616 // The values are now known to be -1 (false) or 1 (true). To convert this 8617 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8618 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8619 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8620 8621 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8622 // understand how to form the extending load. 8623 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8624 8625 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8626 8627 // Now convert to an integer and store. 8628 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8629 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8630 Value); 8631 8632 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8633 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8634 MachinePointerInfo PtrInfo = 8635 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8636 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8637 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8638 8639 SDValue StoreChain = DAG.getEntryNode(); 8640 SDValue Ops[] = {StoreChain, 8641 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8642 Value, FIdx}; 8643 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8644 8645 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8646 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8647 8648 // Extract the value requested. 8649 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8650 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8651 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8652 8653 SDValue IntVal = 8654 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 8655 8656 if (!Subtarget.useCRBits()) 8657 return IntVal; 8658 8659 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 8660 } 8661 8662 /// Lowering for QPX v4i1 loads 8663 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 8664 SelectionDAG &DAG) const { 8665 SDLoc dl(Op); 8666 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 8667 SDValue LoadChain = LN->getChain(); 8668 SDValue BasePtr = LN->getBasePtr(); 8669 8670 if (Op.getValueType() == MVT::v4f64 || 8671 Op.getValueType() == MVT::v4f32) { 8672 EVT MemVT = LN->getMemoryVT(); 8673 unsigned Alignment = LN->getAlignment(); 8674 8675 // If this load is properly aligned, then it is legal. 8676 if (Alignment >= MemVT.getStoreSize()) 8677 return Op; 8678 8679 EVT ScalarVT = Op.getValueType().getScalarType(), 8680 ScalarMemVT = MemVT.getScalarType(); 8681 unsigned Stride = ScalarMemVT.getStoreSize(); 8682 8683 SDValue Vals[4], LoadChains[4]; 8684 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8685 SDValue Load; 8686 if (ScalarVT != ScalarMemVT) 8687 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 8688 BasePtr, 8689 LN->getPointerInfo().getWithOffset(Idx * Stride), 8690 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8691 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8692 else 8693 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 8694 LN->getPointerInfo().getWithOffset(Idx * Stride), 8695 MinAlign(Alignment, Idx * Stride), 8696 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8697 8698 if (Idx == 0 && LN->isIndexed()) { 8699 assert(LN->getAddressingMode() == ISD::PRE_INC && 8700 "Unknown addressing mode on vector load"); 8701 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 8702 LN->getAddressingMode()); 8703 } 8704 8705 Vals[Idx] = Load; 8706 LoadChains[Idx] = Load.getValue(1); 8707 8708 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8709 DAG.getConstant(Stride, dl, 8710 BasePtr.getValueType())); 8711 } 8712 8713 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8714 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 8715 8716 if (LN->isIndexed()) { 8717 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 8718 return DAG.getMergeValues(RetOps, dl); 8719 } 8720 8721 SDValue RetOps[] = { Value, TF }; 8722 return DAG.getMergeValues(RetOps, dl); 8723 } 8724 8725 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 8726 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 8727 8728 // To lower v4i1 from a byte array, we load the byte elements of the 8729 // vector and then reuse the BUILD_VECTOR logic. 8730 8731 SDValue VectElmts[4], VectElmtChains[4]; 8732 for (unsigned i = 0; i < 4; ++i) { 8733 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8734 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8735 8736 VectElmts[i] = DAG.getExtLoad( 8737 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 8738 LN->getPointerInfo().getWithOffset(i), MVT::i8, 8739 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8740 VectElmtChains[i] = VectElmts[i].getValue(1); 8741 } 8742 8743 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 8744 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 8745 8746 SDValue RVals[] = { Value, LoadChain }; 8747 return DAG.getMergeValues(RVals, dl); 8748 } 8749 8750 /// Lowering for QPX v4i1 stores 8751 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 8752 SelectionDAG &DAG) const { 8753 SDLoc dl(Op); 8754 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 8755 SDValue StoreChain = SN->getChain(); 8756 SDValue BasePtr = SN->getBasePtr(); 8757 SDValue Value = SN->getValue(); 8758 8759 if (Value.getValueType() == MVT::v4f64 || 8760 Value.getValueType() == MVT::v4f32) { 8761 EVT MemVT = SN->getMemoryVT(); 8762 unsigned Alignment = SN->getAlignment(); 8763 8764 // If this store is properly aligned, then it is legal. 8765 if (Alignment >= MemVT.getStoreSize()) 8766 return Op; 8767 8768 EVT ScalarVT = Value.getValueType().getScalarType(), 8769 ScalarMemVT = MemVT.getScalarType(); 8770 unsigned Stride = ScalarMemVT.getStoreSize(); 8771 8772 SDValue Stores[4]; 8773 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8774 SDValue Ex = DAG.getNode( 8775 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 8776 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 8777 SDValue Store; 8778 if (ScalarVT != ScalarMemVT) 8779 Store = 8780 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 8781 SN->getPointerInfo().getWithOffset(Idx * Stride), 8782 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8783 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8784 else 8785 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 8786 SN->getPointerInfo().getWithOffset(Idx * Stride), 8787 MinAlign(Alignment, Idx * Stride), 8788 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 8789 8790 if (Idx == 0 && SN->isIndexed()) { 8791 assert(SN->getAddressingMode() == ISD::PRE_INC && 8792 "Unknown addressing mode on vector store"); 8793 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 8794 SN->getAddressingMode()); 8795 } 8796 8797 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8798 DAG.getConstant(Stride, dl, 8799 BasePtr.getValueType())); 8800 Stores[Idx] = Store; 8801 } 8802 8803 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8804 8805 if (SN->isIndexed()) { 8806 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 8807 return DAG.getMergeValues(RetOps, dl); 8808 } 8809 8810 return TF; 8811 } 8812 8813 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 8814 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 8815 8816 // The values are now known to be -1 (false) or 1 (true). To convert this 8817 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8818 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8819 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8820 8821 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8822 // understand how to form the extending load. 8823 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8824 8825 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8826 8827 // Now convert to an integer and store. 8828 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8829 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8830 Value); 8831 8832 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8833 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8834 MachinePointerInfo PtrInfo = 8835 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8836 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8837 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8838 8839 SDValue Ops[] = {StoreChain, 8840 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8841 Value, FIdx}; 8842 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8843 8844 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8845 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8846 8847 // Move data into the byte array. 8848 SDValue Loads[4], LoadChains[4]; 8849 for (unsigned i = 0; i < 4; ++i) { 8850 unsigned Offset = 4*i; 8851 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8852 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8853 8854 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 8855 PtrInfo.getWithOffset(Offset)); 8856 LoadChains[i] = Loads[i].getValue(1); 8857 } 8858 8859 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8860 8861 SDValue Stores[4]; 8862 for (unsigned i = 0; i < 4; ++i) { 8863 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 8864 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 8865 8866 Stores[i] = DAG.getTruncStore( 8867 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 8868 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 8869 SN->getAAInfo()); 8870 } 8871 8872 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8873 8874 return StoreChain; 8875 } 8876 8877 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 8878 SDLoc dl(Op); 8879 if (Op.getValueType() == MVT::v4i32) { 8880 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8881 8882 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 8883 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 8884 8885 SDValue RHSSwap = // = vrlw RHS, 16 8886 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 8887 8888 // Shrinkify inputs to v8i16. 8889 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 8890 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 8891 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 8892 8893 // Low parts multiplied together, generating 32-bit results (we ignore the 8894 // top parts). 8895 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 8896 LHS, RHS, DAG, dl, MVT::v4i32); 8897 8898 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 8899 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 8900 // Shift the high parts up 16 bits. 8901 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 8902 Neg16, DAG, dl); 8903 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 8904 } else if (Op.getValueType() == MVT::v8i16) { 8905 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8906 8907 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 8908 8909 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 8910 LHS, RHS, Zero, DAG, dl); 8911 } else if (Op.getValueType() == MVT::v16i8) { 8912 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 8913 bool isLittleEndian = Subtarget.isLittleEndian(); 8914 8915 // Multiply the even 8-bit parts, producing 16-bit sums. 8916 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 8917 LHS, RHS, DAG, dl, MVT::v8i16); 8918 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 8919 8920 // Multiply the odd 8-bit parts, producing 16-bit sums. 8921 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 8922 LHS, RHS, DAG, dl, MVT::v8i16); 8923 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 8924 8925 // Merge the results together. Because vmuleub and vmuloub are 8926 // instructions with a big-endian bias, we must reverse the 8927 // element numbering and reverse the meaning of "odd" and "even" 8928 // when generating little endian code. 8929 int Ops[16]; 8930 for (unsigned i = 0; i != 8; ++i) { 8931 if (isLittleEndian) { 8932 Ops[i*2 ] = 2*i; 8933 Ops[i*2+1] = 2*i+16; 8934 } else { 8935 Ops[i*2 ] = 2*i+1; 8936 Ops[i*2+1] = 2*i+1+16; 8937 } 8938 } 8939 if (isLittleEndian) 8940 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 8941 else 8942 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 8943 } else { 8944 llvm_unreachable("Unknown mul to lower!"); 8945 } 8946 } 8947 8948 /// LowerOperation - Provide custom lowering hooks for some operations. 8949 /// 8950 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8951 switch (Op.getOpcode()) { 8952 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 8953 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8954 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8955 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8956 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8957 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 8958 case ISD::SETCC: return LowerSETCC(Op, DAG); 8959 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 8960 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 8961 case ISD::VASTART: 8962 return LowerVASTART(Op, DAG); 8963 8964 case ISD::VAARG: 8965 return LowerVAARG(Op, DAG); 8966 8967 case ISD::VACOPY: 8968 return LowerVACOPY(Op, DAG); 8969 8970 case ISD::STACKRESTORE: 8971 return LowerSTACKRESTORE(Op, DAG); 8972 8973 case ISD::DYNAMIC_STACKALLOC: 8974 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8975 8976 case ISD::GET_DYNAMIC_AREA_OFFSET: 8977 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 8978 8979 case ISD::EH_DWARF_CFA: 8980 return LowerEH_DWARF_CFA(Op, DAG); 8981 8982 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 8983 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 8984 8985 case ISD::LOAD: return LowerLOAD(Op, DAG); 8986 case ISD::STORE: return LowerSTORE(Op, DAG); 8987 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 8988 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8989 case ISD::FP_TO_UINT: 8990 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 8991 SDLoc(Op)); 8992 case ISD::UINT_TO_FP: 8993 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8994 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8995 8996 // Lower 64-bit shifts. 8997 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 8998 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 8999 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9000 9001 // Vector-related lowering. 9002 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9003 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9004 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9005 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9006 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 9007 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9008 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9009 case ISD::MUL: return LowerMUL(Op, DAG); 9010 9011 // For counter-based loop handling. 9012 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9013 9014 // Frame & Return address. 9015 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9016 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9017 9018 case ISD::INTRINSIC_VOID: 9019 return LowerINTRINSIC_VOID(Op, DAG); 9020 case ISD::SREM: 9021 case ISD::UREM: 9022 return LowerREM(Op, DAG); 9023 } 9024 } 9025 9026 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9027 SmallVectorImpl<SDValue>&Results, 9028 SelectionDAG &DAG) const { 9029 SDLoc dl(N); 9030 switch (N->getOpcode()) { 9031 default: 9032 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9033 case ISD::READCYCLECOUNTER: { 9034 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9035 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9036 9037 Results.push_back(RTB); 9038 Results.push_back(RTB.getValue(1)); 9039 Results.push_back(RTB.getValue(2)); 9040 break; 9041 } 9042 case ISD::INTRINSIC_W_CHAIN: { 9043 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9044 Intrinsic::ppc_is_decremented_ctr_nonzero) 9045 break; 9046 9047 assert(N->getValueType(0) == MVT::i1 && 9048 "Unexpected result type for CTR decrement intrinsic"); 9049 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9050 N->getValueType(0)); 9051 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9052 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9053 N->getOperand(1)); 9054 9055 Results.push_back(NewInt); 9056 Results.push_back(NewInt.getValue(1)); 9057 break; 9058 } 9059 case ISD::VAARG: { 9060 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9061 return; 9062 9063 EVT VT = N->getValueType(0); 9064 9065 if (VT == MVT::i64) { 9066 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9067 9068 Results.push_back(NewNode); 9069 Results.push_back(NewNode.getValue(1)); 9070 } 9071 return; 9072 } 9073 case ISD::FP_ROUND_INREG: { 9074 assert(N->getValueType(0) == MVT::ppcf128); 9075 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 9076 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9077 MVT::f64, N->getOperand(0), 9078 DAG.getIntPtrConstant(0, dl)); 9079 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9080 MVT::f64, N->getOperand(0), 9081 DAG.getIntPtrConstant(1, dl)); 9082 9083 // Add the two halves of the long double in round-to-zero mode. 9084 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 9085 9086 // We know the low half is about to be thrown away, so just use something 9087 // convenient. 9088 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 9089 FPreg, FPreg)); 9090 return; 9091 } 9092 case ISD::FP_TO_SINT: 9093 case ISD::FP_TO_UINT: 9094 // LowerFP_TO_INT() can only handle f32 and f64. 9095 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9096 return; 9097 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9098 return; 9099 } 9100 } 9101 9102 //===----------------------------------------------------------------------===// 9103 // Other Lowering Code 9104 //===----------------------------------------------------------------------===// 9105 9106 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9107 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9108 Function *Func = Intrinsic::getDeclaration(M, Id); 9109 return Builder.CreateCall(Func, {}); 9110 } 9111 9112 // The mappings for emitLeading/TrailingFence is taken from 9113 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9114 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9115 Instruction *Inst, 9116 AtomicOrdering Ord) const { 9117 if (Ord == AtomicOrdering::SequentiallyConsistent) 9118 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9119 if (isReleaseOrStronger(Ord)) 9120 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9121 return nullptr; 9122 } 9123 9124 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9125 Instruction *Inst, 9126 AtomicOrdering Ord) const { 9127 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9128 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9129 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9130 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9131 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9132 return Builder.CreateCall( 9133 Intrinsic::getDeclaration( 9134 Builder.GetInsertBlock()->getParent()->getParent(), 9135 Intrinsic::ppc_cfence, {Inst->getType()}), 9136 {Inst}); 9137 // FIXME: Can use isync for rmw operation. 9138 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9139 } 9140 return nullptr; 9141 } 9142 9143 MachineBasicBlock * 9144 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9145 unsigned AtomicSize, 9146 unsigned BinOpcode, 9147 unsigned CmpOpcode, 9148 unsigned CmpPred) const { 9149 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9150 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9151 9152 auto LoadMnemonic = PPC::LDARX; 9153 auto StoreMnemonic = PPC::STDCX; 9154 switch (AtomicSize) { 9155 default: 9156 llvm_unreachable("Unexpected size of atomic entity"); 9157 case 1: 9158 LoadMnemonic = PPC::LBARX; 9159 StoreMnemonic = PPC::STBCX; 9160 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9161 break; 9162 case 2: 9163 LoadMnemonic = PPC::LHARX; 9164 StoreMnemonic = PPC::STHCX; 9165 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9166 break; 9167 case 4: 9168 LoadMnemonic = PPC::LWARX; 9169 StoreMnemonic = PPC::STWCX; 9170 break; 9171 case 8: 9172 LoadMnemonic = PPC::LDARX; 9173 StoreMnemonic = PPC::STDCX; 9174 break; 9175 } 9176 9177 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9178 MachineFunction *F = BB->getParent(); 9179 MachineFunction::iterator It = ++BB->getIterator(); 9180 9181 unsigned dest = MI.getOperand(0).getReg(); 9182 unsigned ptrA = MI.getOperand(1).getReg(); 9183 unsigned ptrB = MI.getOperand(2).getReg(); 9184 unsigned incr = MI.getOperand(3).getReg(); 9185 DebugLoc dl = MI.getDebugLoc(); 9186 9187 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9188 MachineBasicBlock *loop2MBB = 9189 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9190 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9191 F->insert(It, loopMBB); 9192 if (CmpOpcode) 9193 F->insert(It, loop2MBB); 9194 F->insert(It, exitMBB); 9195 exitMBB->splice(exitMBB->begin(), BB, 9196 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9197 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9198 9199 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9200 unsigned TmpReg = (!BinOpcode) ? incr : 9201 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9202 : &PPC::GPRCRegClass); 9203 9204 // thisMBB: 9205 // ... 9206 // fallthrough --> loopMBB 9207 BB->addSuccessor(loopMBB); 9208 9209 // loopMBB: 9210 // l[wd]arx dest, ptr 9211 // add r0, dest, incr 9212 // st[wd]cx. r0, ptr 9213 // bne- loopMBB 9214 // fallthrough --> exitMBB 9215 9216 // For max/min... 9217 // loopMBB: 9218 // l[wd]arx dest, ptr 9219 // cmpl?[wd] incr, dest 9220 // bgt exitMBB 9221 // loop2MBB: 9222 // st[wd]cx. dest, ptr 9223 // bne- loopMBB 9224 // fallthrough --> exitMBB 9225 9226 BB = loopMBB; 9227 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9228 .addReg(ptrA).addReg(ptrB); 9229 if (BinOpcode) 9230 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9231 if (CmpOpcode) { 9232 // Signed comparisons of byte or halfword values must be sign-extended. 9233 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9234 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9235 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9236 ExtReg).addReg(dest); 9237 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9238 .addReg(incr).addReg(ExtReg); 9239 } else 9240 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9241 .addReg(incr).addReg(dest); 9242 9243 BuildMI(BB, dl, TII->get(PPC::BCC)) 9244 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9245 BB->addSuccessor(loop2MBB); 9246 BB->addSuccessor(exitMBB); 9247 BB = loop2MBB; 9248 } 9249 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9250 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9251 BuildMI(BB, dl, TII->get(PPC::BCC)) 9252 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9253 BB->addSuccessor(loopMBB); 9254 BB->addSuccessor(exitMBB); 9255 9256 // exitMBB: 9257 // ... 9258 BB = exitMBB; 9259 return BB; 9260 } 9261 9262 MachineBasicBlock * 9263 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9264 MachineBasicBlock *BB, 9265 bool is8bit, // operation 9266 unsigned BinOpcode, 9267 unsigned CmpOpcode, 9268 unsigned CmpPred) const { 9269 // If we support part-word atomic mnemonics, just use them 9270 if (Subtarget.hasPartwordAtomics()) 9271 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9272 CmpOpcode, CmpPred); 9273 9274 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9275 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9276 // In 64 bit mode we have to use 64 bits for addresses, even though the 9277 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9278 // registers without caring whether they're 32 or 64, but here we're 9279 // doing actual arithmetic on the addresses. 9280 bool is64bit = Subtarget.isPPC64(); 9281 bool isLittleEndian = Subtarget.isLittleEndian(); 9282 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9283 9284 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9285 MachineFunction *F = BB->getParent(); 9286 MachineFunction::iterator It = ++BB->getIterator(); 9287 9288 unsigned dest = MI.getOperand(0).getReg(); 9289 unsigned ptrA = MI.getOperand(1).getReg(); 9290 unsigned ptrB = MI.getOperand(2).getReg(); 9291 unsigned incr = MI.getOperand(3).getReg(); 9292 DebugLoc dl = MI.getDebugLoc(); 9293 9294 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9295 MachineBasicBlock *loop2MBB = 9296 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9297 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9298 F->insert(It, loopMBB); 9299 if (CmpOpcode) 9300 F->insert(It, loop2MBB); 9301 F->insert(It, exitMBB); 9302 exitMBB->splice(exitMBB->begin(), BB, 9303 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9304 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9305 9306 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9307 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9308 : &PPC::GPRCRegClass; 9309 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9310 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9311 unsigned ShiftReg = 9312 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9313 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9314 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9315 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9316 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9317 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9318 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9319 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9320 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9321 unsigned Ptr1Reg; 9322 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9323 9324 // thisMBB: 9325 // ... 9326 // fallthrough --> loopMBB 9327 BB->addSuccessor(loopMBB); 9328 9329 // The 4-byte load must be aligned, while a char or short may be 9330 // anywhere in the word. Hence all this nasty bookkeeping code. 9331 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9332 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9333 // xori shift, shift1, 24 [16] 9334 // rlwinm ptr, ptr1, 0, 0, 29 9335 // slw incr2, incr, shift 9336 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9337 // slw mask, mask2, shift 9338 // loopMBB: 9339 // lwarx tmpDest, ptr 9340 // add tmp, tmpDest, incr2 9341 // andc tmp2, tmpDest, mask 9342 // and tmp3, tmp, mask 9343 // or tmp4, tmp3, tmp2 9344 // stwcx. tmp4, ptr 9345 // bne- loopMBB 9346 // fallthrough --> exitMBB 9347 // srw dest, tmpDest, shift 9348 if (ptrA != ZeroReg) { 9349 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9350 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9351 .addReg(ptrA).addReg(ptrB); 9352 } else { 9353 Ptr1Reg = ptrB; 9354 } 9355 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9356 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9357 if (!isLittleEndian) 9358 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9359 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9360 if (is64bit) 9361 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9362 .addReg(Ptr1Reg).addImm(0).addImm(61); 9363 else 9364 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9365 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9366 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9367 .addReg(incr).addReg(ShiftReg); 9368 if (is8bit) 9369 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9370 else { 9371 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9372 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9373 } 9374 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9375 .addReg(Mask2Reg).addReg(ShiftReg); 9376 9377 BB = loopMBB; 9378 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9379 .addReg(ZeroReg).addReg(PtrReg); 9380 if (BinOpcode) 9381 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9382 .addReg(Incr2Reg).addReg(TmpDestReg); 9383 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9384 .addReg(TmpDestReg).addReg(MaskReg); 9385 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9386 .addReg(TmpReg).addReg(MaskReg); 9387 if (CmpOpcode) { 9388 // For unsigned comparisons, we can directly compare the shifted values. 9389 // For signed comparisons we shift and sign extend. 9390 unsigned SReg = RegInfo.createVirtualRegister(RC); 9391 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9392 .addReg(TmpDestReg).addReg(MaskReg); 9393 unsigned ValueReg = SReg; 9394 unsigned CmpReg = Incr2Reg; 9395 if (CmpOpcode == PPC::CMPW) { 9396 ValueReg = RegInfo.createVirtualRegister(RC); 9397 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9398 .addReg(SReg).addReg(ShiftReg); 9399 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9400 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9401 .addReg(ValueReg); 9402 ValueReg = ValueSReg; 9403 CmpReg = incr; 9404 } 9405 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9406 .addReg(CmpReg).addReg(ValueReg); 9407 BuildMI(BB, dl, TII->get(PPC::BCC)) 9408 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9409 BB->addSuccessor(loop2MBB); 9410 BB->addSuccessor(exitMBB); 9411 BB = loop2MBB; 9412 } 9413 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9414 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9415 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9416 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9417 BuildMI(BB, dl, TII->get(PPC::BCC)) 9418 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9419 BB->addSuccessor(loopMBB); 9420 BB->addSuccessor(exitMBB); 9421 9422 // exitMBB: 9423 // ... 9424 BB = exitMBB; 9425 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9426 .addReg(ShiftReg); 9427 return BB; 9428 } 9429 9430 llvm::MachineBasicBlock * 9431 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9432 MachineBasicBlock *MBB) const { 9433 DebugLoc DL = MI.getDebugLoc(); 9434 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9435 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9436 9437 MachineFunction *MF = MBB->getParent(); 9438 MachineRegisterInfo &MRI = MF->getRegInfo(); 9439 9440 const BasicBlock *BB = MBB->getBasicBlock(); 9441 MachineFunction::iterator I = ++MBB->getIterator(); 9442 9443 // Memory Reference 9444 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9445 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9446 9447 unsigned DstReg = MI.getOperand(0).getReg(); 9448 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9449 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9450 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9451 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9452 9453 MVT PVT = getPointerTy(MF->getDataLayout()); 9454 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9455 "Invalid Pointer Size!"); 9456 // For v = setjmp(buf), we generate 9457 // 9458 // thisMBB: 9459 // SjLjSetup mainMBB 9460 // bl mainMBB 9461 // v_restore = 1 9462 // b sinkMBB 9463 // 9464 // mainMBB: 9465 // buf[LabelOffset] = LR 9466 // v_main = 0 9467 // 9468 // sinkMBB: 9469 // v = phi(main, restore) 9470 // 9471 9472 MachineBasicBlock *thisMBB = MBB; 9473 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9474 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9475 MF->insert(I, mainMBB); 9476 MF->insert(I, sinkMBB); 9477 9478 MachineInstrBuilder MIB; 9479 9480 // Transfer the remainder of BB and its successor edges to sinkMBB. 9481 sinkMBB->splice(sinkMBB->begin(), MBB, 9482 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9483 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9484 9485 // Note that the structure of the jmp_buf used here is not compatible 9486 // with that used by libc, and is not designed to be. Specifically, it 9487 // stores only those 'reserved' registers that LLVM does not otherwise 9488 // understand how to spill. Also, by convention, by the time this 9489 // intrinsic is called, Clang has already stored the frame address in the 9490 // first slot of the buffer and stack address in the third. Following the 9491 // X86 target code, we'll store the jump address in the second slot. We also 9492 // need to save the TOC pointer (R2) to handle jumps between shared 9493 // libraries, and that will be stored in the fourth slot. The thread 9494 // identifier (R13) is not affected. 9495 9496 // thisMBB: 9497 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9498 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9499 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9500 9501 // Prepare IP either in reg. 9502 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9503 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9504 unsigned BufReg = MI.getOperand(1).getReg(); 9505 9506 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9507 setUsesTOCBasePtr(*MBB->getParent()); 9508 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9509 .addReg(PPC::X2) 9510 .addImm(TOCOffset) 9511 .addReg(BufReg); 9512 MIB.setMemRefs(MMOBegin, MMOEnd); 9513 } 9514 9515 // Naked functions never have a base pointer, and so we use r1. For all 9516 // other functions, this decision must be delayed until during PEI. 9517 unsigned BaseReg; 9518 if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) 9519 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9520 else 9521 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9522 9523 MIB = BuildMI(*thisMBB, MI, DL, 9524 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9525 .addReg(BaseReg) 9526 .addImm(BPOffset) 9527 .addReg(BufReg); 9528 MIB.setMemRefs(MMOBegin, MMOEnd); 9529 9530 // Setup 9531 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9532 MIB.addRegMask(TRI->getNoPreservedMask()); 9533 9534 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9535 9536 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9537 .addMBB(mainMBB); 9538 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9539 9540 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9541 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9542 9543 // mainMBB: 9544 // mainDstReg = 0 9545 MIB = 9546 BuildMI(mainMBB, DL, 9547 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9548 9549 // Store IP 9550 if (Subtarget.isPPC64()) { 9551 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9552 .addReg(LabelReg) 9553 .addImm(LabelOffset) 9554 .addReg(BufReg); 9555 } else { 9556 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9557 .addReg(LabelReg) 9558 .addImm(LabelOffset) 9559 .addReg(BufReg); 9560 } 9561 9562 MIB.setMemRefs(MMOBegin, MMOEnd); 9563 9564 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9565 mainMBB->addSuccessor(sinkMBB); 9566 9567 // sinkMBB: 9568 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9569 TII->get(PPC::PHI), DstReg) 9570 .addReg(mainDstReg).addMBB(mainMBB) 9571 .addReg(restoreDstReg).addMBB(thisMBB); 9572 9573 MI.eraseFromParent(); 9574 return sinkMBB; 9575 } 9576 9577 MachineBasicBlock * 9578 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9579 MachineBasicBlock *MBB) const { 9580 DebugLoc DL = MI.getDebugLoc(); 9581 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9582 9583 MachineFunction *MF = MBB->getParent(); 9584 MachineRegisterInfo &MRI = MF->getRegInfo(); 9585 9586 // Memory Reference 9587 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9588 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9589 9590 MVT PVT = getPointerTy(MF->getDataLayout()); 9591 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9592 "Invalid Pointer Size!"); 9593 9594 const TargetRegisterClass *RC = 9595 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9596 unsigned Tmp = MRI.createVirtualRegister(RC); 9597 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9598 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9599 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9600 unsigned BP = 9601 (PVT == MVT::i64) 9602 ? PPC::X30 9603 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 9604 : PPC::R30); 9605 9606 MachineInstrBuilder MIB; 9607 9608 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9609 const int64_t SPOffset = 2 * PVT.getStoreSize(); 9610 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9611 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9612 9613 unsigned BufReg = MI.getOperand(0).getReg(); 9614 9615 // Reload FP (the jumped-to function may not have had a 9616 // frame pointer, and if so, then its r31 will be restored 9617 // as necessary). 9618 if (PVT == MVT::i64) { 9619 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 9620 .addImm(0) 9621 .addReg(BufReg); 9622 } else { 9623 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 9624 .addImm(0) 9625 .addReg(BufReg); 9626 } 9627 MIB.setMemRefs(MMOBegin, MMOEnd); 9628 9629 // Reload IP 9630 if (PVT == MVT::i64) { 9631 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 9632 .addImm(LabelOffset) 9633 .addReg(BufReg); 9634 } else { 9635 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 9636 .addImm(LabelOffset) 9637 .addReg(BufReg); 9638 } 9639 MIB.setMemRefs(MMOBegin, MMOEnd); 9640 9641 // Reload SP 9642 if (PVT == MVT::i64) { 9643 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 9644 .addImm(SPOffset) 9645 .addReg(BufReg); 9646 } else { 9647 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 9648 .addImm(SPOffset) 9649 .addReg(BufReg); 9650 } 9651 MIB.setMemRefs(MMOBegin, MMOEnd); 9652 9653 // Reload BP 9654 if (PVT == MVT::i64) { 9655 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 9656 .addImm(BPOffset) 9657 .addReg(BufReg); 9658 } else { 9659 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 9660 .addImm(BPOffset) 9661 .addReg(BufReg); 9662 } 9663 MIB.setMemRefs(MMOBegin, MMOEnd); 9664 9665 // Reload TOC 9666 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 9667 setUsesTOCBasePtr(*MBB->getParent()); 9668 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 9669 .addImm(TOCOffset) 9670 .addReg(BufReg); 9671 9672 MIB.setMemRefs(MMOBegin, MMOEnd); 9673 } 9674 9675 // Jump 9676 BuildMI(*MBB, MI, DL, 9677 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 9678 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 9679 9680 MI.eraseFromParent(); 9681 return MBB; 9682 } 9683 9684 MachineBasicBlock * 9685 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9686 MachineBasicBlock *BB) const { 9687 if (MI.getOpcode() == TargetOpcode::STACKMAP || 9688 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9689 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 9690 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9691 // Call lowering should have added an r2 operand to indicate a dependence 9692 // on the TOC base pointer value. It can't however, because there is no 9693 // way to mark the dependence as implicit there, and so the stackmap code 9694 // will confuse it with a regular operand. Instead, add the dependence 9695 // here. 9696 setUsesTOCBasePtr(*BB->getParent()); 9697 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 9698 } 9699 9700 return emitPatchPoint(MI, BB); 9701 } 9702 9703 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 9704 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 9705 return emitEHSjLjSetJmp(MI, BB); 9706 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 9707 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 9708 return emitEHSjLjLongJmp(MI, BB); 9709 } 9710 9711 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9712 9713 // To "insert" these instructions we actually have to insert their 9714 // control-flow patterns. 9715 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9716 MachineFunction::iterator It = ++BB->getIterator(); 9717 9718 MachineFunction *F = BB->getParent(); 9719 9720 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9721 MI.getOpcode() == PPC::SELECT_CC_I8 || 9722 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 9723 SmallVector<MachineOperand, 2> Cond; 9724 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9725 MI.getOpcode() == PPC::SELECT_CC_I8) 9726 Cond.push_back(MI.getOperand(4)); 9727 else 9728 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 9729 Cond.push_back(MI.getOperand(1)); 9730 9731 DebugLoc dl = MI.getDebugLoc(); 9732 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 9733 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 9734 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9735 MI.getOpcode() == PPC::SELECT_CC_I8 || 9736 MI.getOpcode() == PPC::SELECT_CC_F4 || 9737 MI.getOpcode() == PPC::SELECT_CC_F8 || 9738 MI.getOpcode() == PPC::SELECT_CC_QFRC || 9739 MI.getOpcode() == PPC::SELECT_CC_QSRC || 9740 MI.getOpcode() == PPC::SELECT_CC_QBRC || 9741 MI.getOpcode() == PPC::SELECT_CC_VRRC || 9742 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 9743 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 9744 MI.getOpcode() == PPC::SELECT_CC_VSRC || 9745 MI.getOpcode() == PPC::SELECT_I4 || 9746 MI.getOpcode() == PPC::SELECT_I8 || 9747 MI.getOpcode() == PPC::SELECT_F4 || 9748 MI.getOpcode() == PPC::SELECT_F8 || 9749 MI.getOpcode() == PPC::SELECT_QFRC || 9750 MI.getOpcode() == PPC::SELECT_QSRC || 9751 MI.getOpcode() == PPC::SELECT_QBRC || 9752 MI.getOpcode() == PPC::SELECT_VRRC || 9753 MI.getOpcode() == PPC::SELECT_VSFRC || 9754 MI.getOpcode() == PPC::SELECT_VSSRC || 9755 MI.getOpcode() == PPC::SELECT_VSRC) { 9756 // The incoming instruction knows the destination vreg to set, the 9757 // condition code register to branch on, the true/false values to 9758 // select between, and a branch opcode to use. 9759 9760 // thisMBB: 9761 // ... 9762 // TrueVal = ... 9763 // cmpTY ccX, r1, r2 9764 // bCC copy1MBB 9765 // fallthrough --> copy0MBB 9766 MachineBasicBlock *thisMBB = BB; 9767 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9768 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9769 DebugLoc dl = MI.getDebugLoc(); 9770 F->insert(It, copy0MBB); 9771 F->insert(It, sinkMBB); 9772 9773 // Transfer the remainder of BB and its successor edges to sinkMBB. 9774 sinkMBB->splice(sinkMBB->begin(), BB, 9775 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9776 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9777 9778 // Next, add the true and fallthrough blocks as its successors. 9779 BB->addSuccessor(copy0MBB); 9780 BB->addSuccessor(sinkMBB); 9781 9782 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 9783 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 9784 MI.getOpcode() == PPC::SELECT_QFRC || 9785 MI.getOpcode() == PPC::SELECT_QSRC || 9786 MI.getOpcode() == PPC::SELECT_QBRC || 9787 MI.getOpcode() == PPC::SELECT_VRRC || 9788 MI.getOpcode() == PPC::SELECT_VSFRC || 9789 MI.getOpcode() == PPC::SELECT_VSSRC || 9790 MI.getOpcode() == PPC::SELECT_VSRC) { 9791 BuildMI(BB, dl, TII->get(PPC::BC)) 9792 .addReg(MI.getOperand(1).getReg()) 9793 .addMBB(sinkMBB); 9794 } else { 9795 unsigned SelectPred = MI.getOperand(4).getImm(); 9796 BuildMI(BB, dl, TII->get(PPC::BCC)) 9797 .addImm(SelectPred) 9798 .addReg(MI.getOperand(1).getReg()) 9799 .addMBB(sinkMBB); 9800 } 9801 9802 // copy0MBB: 9803 // %FalseValue = ... 9804 // # fallthrough to sinkMBB 9805 BB = copy0MBB; 9806 9807 // Update machine-CFG edges 9808 BB->addSuccessor(sinkMBB); 9809 9810 // sinkMBB: 9811 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9812 // ... 9813 BB = sinkMBB; 9814 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 9815 .addReg(MI.getOperand(3).getReg()) 9816 .addMBB(copy0MBB) 9817 .addReg(MI.getOperand(2).getReg()) 9818 .addMBB(thisMBB); 9819 } else if (MI.getOpcode() == PPC::ReadTB) { 9820 // To read the 64-bit time-base register on a 32-bit target, we read the 9821 // two halves. Should the counter have wrapped while it was being read, we 9822 // need to try again. 9823 // ... 9824 // readLoop: 9825 // mfspr Rx,TBU # load from TBU 9826 // mfspr Ry,TB # load from TB 9827 // mfspr Rz,TBU # load from TBU 9828 // cmpw crX,Rx,Rz # check if 'old'='new' 9829 // bne readLoop # branch if they're not equal 9830 // ... 9831 9832 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 9833 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9834 DebugLoc dl = MI.getDebugLoc(); 9835 F->insert(It, readMBB); 9836 F->insert(It, sinkMBB); 9837 9838 // Transfer the remainder of BB and its successor edges to sinkMBB. 9839 sinkMBB->splice(sinkMBB->begin(), BB, 9840 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9841 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9842 9843 BB->addSuccessor(readMBB); 9844 BB = readMBB; 9845 9846 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9847 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9848 unsigned LoReg = MI.getOperand(0).getReg(); 9849 unsigned HiReg = MI.getOperand(1).getReg(); 9850 9851 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 9852 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 9853 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 9854 9855 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 9856 9857 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 9858 .addReg(HiReg).addReg(ReadAgainReg); 9859 BuildMI(BB, dl, TII->get(PPC::BCC)) 9860 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 9861 9862 BB->addSuccessor(readMBB); 9863 BB->addSuccessor(sinkMBB); 9864 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 9865 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 9866 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 9867 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 9868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 9869 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 9870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 9871 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 9872 9873 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 9874 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 9875 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 9876 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 9877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 9878 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 9879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 9880 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 9881 9882 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 9883 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 9884 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 9885 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 9886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 9887 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 9888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 9889 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 9890 9891 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 9892 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 9893 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 9894 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 9895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 9896 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 9897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 9898 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 9899 9900 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 9901 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 9902 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 9903 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 9904 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 9905 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 9906 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 9907 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 9908 9909 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 9910 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 9911 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 9912 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 9913 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 9914 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 9915 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 9916 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 9917 9918 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 9919 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 9920 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 9921 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 9922 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 9923 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 9924 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 9925 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 9926 9927 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 9928 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 9929 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 9930 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 9931 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 9932 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 9933 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 9934 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 9935 9936 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 9937 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 9938 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 9939 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 9940 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 9941 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 9942 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 9943 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 9944 9945 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 9946 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 9947 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 9948 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 9949 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 9950 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 9951 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 9952 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 9953 9954 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 9955 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 9956 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 9957 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 9958 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 9959 BB = EmitAtomicBinary(MI, BB, 4, 0); 9960 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 9961 BB = EmitAtomicBinary(MI, BB, 8, 0); 9962 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 9963 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 9964 (Subtarget.hasPartwordAtomics() && 9965 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 9966 (Subtarget.hasPartwordAtomics() && 9967 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 9968 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 9969 9970 auto LoadMnemonic = PPC::LDARX; 9971 auto StoreMnemonic = PPC::STDCX; 9972 switch (MI.getOpcode()) { 9973 default: 9974 llvm_unreachable("Compare and swap of unknown size"); 9975 case PPC::ATOMIC_CMP_SWAP_I8: 9976 LoadMnemonic = PPC::LBARX; 9977 StoreMnemonic = PPC::STBCX; 9978 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9979 break; 9980 case PPC::ATOMIC_CMP_SWAP_I16: 9981 LoadMnemonic = PPC::LHARX; 9982 StoreMnemonic = PPC::STHCX; 9983 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 9984 break; 9985 case PPC::ATOMIC_CMP_SWAP_I32: 9986 LoadMnemonic = PPC::LWARX; 9987 StoreMnemonic = PPC::STWCX; 9988 break; 9989 case PPC::ATOMIC_CMP_SWAP_I64: 9990 LoadMnemonic = PPC::LDARX; 9991 StoreMnemonic = PPC::STDCX; 9992 break; 9993 } 9994 unsigned dest = MI.getOperand(0).getReg(); 9995 unsigned ptrA = MI.getOperand(1).getReg(); 9996 unsigned ptrB = MI.getOperand(2).getReg(); 9997 unsigned oldval = MI.getOperand(3).getReg(); 9998 unsigned newval = MI.getOperand(4).getReg(); 9999 DebugLoc dl = MI.getDebugLoc(); 10000 10001 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10002 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10003 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10004 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10005 F->insert(It, loop1MBB); 10006 F->insert(It, loop2MBB); 10007 F->insert(It, midMBB); 10008 F->insert(It, exitMBB); 10009 exitMBB->splice(exitMBB->begin(), BB, 10010 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10011 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10012 10013 // thisMBB: 10014 // ... 10015 // fallthrough --> loopMBB 10016 BB->addSuccessor(loop1MBB); 10017 10018 // loop1MBB: 10019 // l[bhwd]arx dest, ptr 10020 // cmp[wd] dest, oldval 10021 // bne- midMBB 10022 // loop2MBB: 10023 // st[bhwd]cx. newval, ptr 10024 // bne- loopMBB 10025 // b exitBB 10026 // midMBB: 10027 // st[bhwd]cx. dest, ptr 10028 // exitBB: 10029 BB = loop1MBB; 10030 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10031 .addReg(ptrA).addReg(ptrB); 10032 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10033 .addReg(oldval).addReg(dest); 10034 BuildMI(BB, dl, TII->get(PPC::BCC)) 10035 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10036 BB->addSuccessor(loop2MBB); 10037 BB->addSuccessor(midMBB); 10038 10039 BB = loop2MBB; 10040 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10041 .addReg(newval).addReg(ptrA).addReg(ptrB); 10042 BuildMI(BB, dl, TII->get(PPC::BCC)) 10043 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10044 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10045 BB->addSuccessor(loop1MBB); 10046 BB->addSuccessor(exitMBB); 10047 10048 BB = midMBB; 10049 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10050 .addReg(dest).addReg(ptrA).addReg(ptrB); 10051 BB->addSuccessor(exitMBB); 10052 10053 // exitMBB: 10054 // ... 10055 BB = exitMBB; 10056 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10057 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10058 // We must use 64-bit registers for addresses when targeting 64-bit, 10059 // since we're actually doing arithmetic on them. Other registers 10060 // can be 32-bit. 10061 bool is64bit = Subtarget.isPPC64(); 10062 bool isLittleEndian = Subtarget.isLittleEndian(); 10063 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10064 10065 unsigned dest = MI.getOperand(0).getReg(); 10066 unsigned ptrA = MI.getOperand(1).getReg(); 10067 unsigned ptrB = MI.getOperand(2).getReg(); 10068 unsigned oldval = MI.getOperand(3).getReg(); 10069 unsigned newval = MI.getOperand(4).getReg(); 10070 DebugLoc dl = MI.getDebugLoc(); 10071 10072 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10073 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10074 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10075 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10076 F->insert(It, loop1MBB); 10077 F->insert(It, loop2MBB); 10078 F->insert(It, midMBB); 10079 F->insert(It, exitMBB); 10080 exitMBB->splice(exitMBB->begin(), BB, 10081 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10082 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10083 10084 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10085 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10086 : &PPC::GPRCRegClass; 10087 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10088 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10089 unsigned ShiftReg = 10090 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10091 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10092 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10093 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10094 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10095 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10096 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10097 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10098 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10099 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10100 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10101 unsigned Ptr1Reg; 10102 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10103 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10104 // thisMBB: 10105 // ... 10106 // fallthrough --> loopMBB 10107 BB->addSuccessor(loop1MBB); 10108 10109 // The 4-byte load must be aligned, while a char or short may be 10110 // anywhere in the word. Hence all this nasty bookkeeping code. 10111 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10112 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10113 // xori shift, shift1, 24 [16] 10114 // rlwinm ptr, ptr1, 0, 0, 29 10115 // slw newval2, newval, shift 10116 // slw oldval2, oldval,shift 10117 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10118 // slw mask, mask2, shift 10119 // and newval3, newval2, mask 10120 // and oldval3, oldval2, mask 10121 // loop1MBB: 10122 // lwarx tmpDest, ptr 10123 // and tmp, tmpDest, mask 10124 // cmpw tmp, oldval3 10125 // bne- midMBB 10126 // loop2MBB: 10127 // andc tmp2, tmpDest, mask 10128 // or tmp4, tmp2, newval3 10129 // stwcx. tmp4, ptr 10130 // bne- loop1MBB 10131 // b exitBB 10132 // midMBB: 10133 // stwcx. tmpDest, ptr 10134 // exitBB: 10135 // srw dest, tmpDest, shift 10136 if (ptrA != ZeroReg) { 10137 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10138 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10139 .addReg(ptrA).addReg(ptrB); 10140 } else { 10141 Ptr1Reg = ptrB; 10142 } 10143 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10144 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10145 if (!isLittleEndian) 10146 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10147 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10148 if (is64bit) 10149 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10150 .addReg(Ptr1Reg).addImm(0).addImm(61); 10151 else 10152 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10153 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10154 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10155 .addReg(newval).addReg(ShiftReg); 10156 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10157 .addReg(oldval).addReg(ShiftReg); 10158 if (is8bit) 10159 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10160 else { 10161 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10162 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10163 .addReg(Mask3Reg).addImm(65535); 10164 } 10165 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10166 .addReg(Mask2Reg).addReg(ShiftReg); 10167 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10168 .addReg(NewVal2Reg).addReg(MaskReg); 10169 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10170 .addReg(OldVal2Reg).addReg(MaskReg); 10171 10172 BB = loop1MBB; 10173 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10174 .addReg(ZeroReg).addReg(PtrReg); 10175 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10176 .addReg(TmpDestReg).addReg(MaskReg); 10177 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10178 .addReg(TmpReg).addReg(OldVal3Reg); 10179 BuildMI(BB, dl, TII->get(PPC::BCC)) 10180 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10181 BB->addSuccessor(loop2MBB); 10182 BB->addSuccessor(midMBB); 10183 10184 BB = loop2MBB; 10185 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10186 .addReg(TmpDestReg).addReg(MaskReg); 10187 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10188 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10189 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10190 .addReg(ZeroReg).addReg(PtrReg); 10191 BuildMI(BB, dl, TII->get(PPC::BCC)) 10192 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10193 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10194 BB->addSuccessor(loop1MBB); 10195 BB->addSuccessor(exitMBB); 10196 10197 BB = midMBB; 10198 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10199 .addReg(ZeroReg).addReg(PtrReg); 10200 BB->addSuccessor(exitMBB); 10201 10202 // exitMBB: 10203 // ... 10204 BB = exitMBB; 10205 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10206 .addReg(ShiftReg); 10207 } else if (MI.getOpcode() == PPC::FADDrtz) { 10208 // This pseudo performs an FADD with rounding mode temporarily forced 10209 // to round-to-zero. We emit this via custom inserter since the FPSCR 10210 // is not modeled at the SelectionDAG level. 10211 unsigned Dest = MI.getOperand(0).getReg(); 10212 unsigned Src1 = MI.getOperand(1).getReg(); 10213 unsigned Src2 = MI.getOperand(2).getReg(); 10214 DebugLoc dl = MI.getDebugLoc(); 10215 10216 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10217 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10218 10219 // Save FPSCR value. 10220 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10221 10222 // Set rounding mode to round-to-zero. 10223 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10224 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10225 10226 // Perform addition. 10227 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10228 10229 // Restore FPSCR value. 10230 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10231 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10232 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10233 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10234 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10235 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10236 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10237 ? PPC::ANDIo8 10238 : PPC::ANDIo; 10239 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10240 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10241 10242 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10243 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10244 &PPC::GPRCRegClass : 10245 &PPC::G8RCRegClass); 10246 10247 DebugLoc dl = MI.getDebugLoc(); 10248 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10249 .addReg(MI.getOperand(1).getReg()) 10250 .addImm(1); 10251 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10252 MI.getOperand(0).getReg()) 10253 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10254 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10255 DebugLoc Dl = MI.getDebugLoc(); 10256 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10257 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10258 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10259 return BB; 10260 } else { 10261 llvm_unreachable("Unexpected instr type to insert"); 10262 } 10263 10264 MI.eraseFromParent(); // The pseudo instruction is gone now. 10265 return BB; 10266 } 10267 10268 //===----------------------------------------------------------------------===// 10269 // Target Optimization Hooks 10270 //===----------------------------------------------------------------------===// 10271 10272 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10273 // For the estimates, convergence is quadratic, so we essentially double the 10274 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10275 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10276 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10277 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10278 if (VT.getScalarType() == MVT::f64) 10279 RefinementSteps++; 10280 return RefinementSteps; 10281 } 10282 10283 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10284 int Enabled, int &RefinementSteps, 10285 bool &UseOneConstNR, 10286 bool Reciprocal) const { 10287 EVT VT = Operand.getValueType(); 10288 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10289 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10290 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10291 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10292 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10293 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10294 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10295 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10296 10297 UseOneConstNR = true; 10298 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10299 } 10300 return SDValue(); 10301 } 10302 10303 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10304 int Enabled, 10305 int &RefinementSteps) const { 10306 EVT VT = Operand.getValueType(); 10307 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10308 (VT == MVT::f64 && Subtarget.hasFRE()) || 10309 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10310 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10311 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10312 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10313 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10314 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10315 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10316 } 10317 return SDValue(); 10318 } 10319 10320 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10321 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10322 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10323 // enabled for division), this functionality is redundant with the default 10324 // combiner logic (once the division -> reciprocal/multiply transformation 10325 // has taken place). As a result, this matters more for older cores than for 10326 // newer ones. 10327 10328 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10329 // reciprocal if there are two or more FDIVs (for embedded cores with only 10330 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10331 switch (Subtarget.getDarwinDirective()) { 10332 default: 10333 return 3; 10334 case PPC::DIR_440: 10335 case PPC::DIR_A2: 10336 case PPC::DIR_E500mc: 10337 case PPC::DIR_E5500: 10338 return 2; 10339 } 10340 } 10341 10342 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10343 // collapsed, and so we need to look through chains of them. 10344 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10345 int64_t& Offset, SelectionDAG &DAG) { 10346 if (DAG.isBaseWithConstantOffset(Loc)) { 10347 Base = Loc.getOperand(0); 10348 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10349 10350 // The base might itself be a base plus an offset, and if so, accumulate 10351 // that as well. 10352 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10353 } 10354 } 10355 10356 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10357 unsigned Bytes, int Dist, 10358 SelectionDAG &DAG) { 10359 if (VT.getSizeInBits() / 8 != Bytes) 10360 return false; 10361 10362 SDValue BaseLoc = Base->getBasePtr(); 10363 if (Loc.getOpcode() == ISD::FrameIndex) { 10364 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10365 return false; 10366 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10367 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10368 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10369 int FS = MFI.getObjectSize(FI); 10370 int BFS = MFI.getObjectSize(BFI); 10371 if (FS != BFS || FS != (int)Bytes) return false; 10372 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10373 } 10374 10375 SDValue Base1 = Loc, Base2 = BaseLoc; 10376 int64_t Offset1 = 0, Offset2 = 0; 10377 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10378 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10379 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10380 return true; 10381 10382 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10383 const GlobalValue *GV1 = nullptr; 10384 const GlobalValue *GV2 = nullptr; 10385 Offset1 = 0; 10386 Offset2 = 0; 10387 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10388 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10389 if (isGA1 && isGA2 && GV1 == GV2) 10390 return Offset1 == (Offset2 + Dist*Bytes); 10391 return false; 10392 } 10393 10394 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10395 // not enforce equality of the chain operands. 10396 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10397 unsigned Bytes, int Dist, 10398 SelectionDAG &DAG) { 10399 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10400 EVT VT = LS->getMemoryVT(); 10401 SDValue Loc = LS->getBasePtr(); 10402 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10403 } 10404 10405 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10406 EVT VT; 10407 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10408 default: return false; 10409 case Intrinsic::ppc_qpx_qvlfd: 10410 case Intrinsic::ppc_qpx_qvlfda: 10411 VT = MVT::v4f64; 10412 break; 10413 case Intrinsic::ppc_qpx_qvlfs: 10414 case Intrinsic::ppc_qpx_qvlfsa: 10415 VT = MVT::v4f32; 10416 break; 10417 case Intrinsic::ppc_qpx_qvlfcd: 10418 case Intrinsic::ppc_qpx_qvlfcda: 10419 VT = MVT::v2f64; 10420 break; 10421 case Intrinsic::ppc_qpx_qvlfcs: 10422 case Intrinsic::ppc_qpx_qvlfcsa: 10423 VT = MVT::v2f32; 10424 break; 10425 case Intrinsic::ppc_qpx_qvlfiwa: 10426 case Intrinsic::ppc_qpx_qvlfiwz: 10427 case Intrinsic::ppc_altivec_lvx: 10428 case Intrinsic::ppc_altivec_lvxl: 10429 case Intrinsic::ppc_vsx_lxvw4x: 10430 case Intrinsic::ppc_vsx_lxvw4x_be: 10431 VT = MVT::v4i32; 10432 break; 10433 case Intrinsic::ppc_vsx_lxvd2x: 10434 case Intrinsic::ppc_vsx_lxvd2x_be: 10435 VT = MVT::v2f64; 10436 break; 10437 case Intrinsic::ppc_altivec_lvebx: 10438 VT = MVT::i8; 10439 break; 10440 case Intrinsic::ppc_altivec_lvehx: 10441 VT = MVT::i16; 10442 break; 10443 case Intrinsic::ppc_altivec_lvewx: 10444 VT = MVT::i32; 10445 break; 10446 } 10447 10448 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10449 } 10450 10451 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10452 EVT VT; 10453 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10454 default: return false; 10455 case Intrinsic::ppc_qpx_qvstfd: 10456 case Intrinsic::ppc_qpx_qvstfda: 10457 VT = MVT::v4f64; 10458 break; 10459 case Intrinsic::ppc_qpx_qvstfs: 10460 case Intrinsic::ppc_qpx_qvstfsa: 10461 VT = MVT::v4f32; 10462 break; 10463 case Intrinsic::ppc_qpx_qvstfcd: 10464 case Intrinsic::ppc_qpx_qvstfcda: 10465 VT = MVT::v2f64; 10466 break; 10467 case Intrinsic::ppc_qpx_qvstfcs: 10468 case Intrinsic::ppc_qpx_qvstfcsa: 10469 VT = MVT::v2f32; 10470 break; 10471 case Intrinsic::ppc_qpx_qvstfiw: 10472 case Intrinsic::ppc_qpx_qvstfiwa: 10473 case Intrinsic::ppc_altivec_stvx: 10474 case Intrinsic::ppc_altivec_stvxl: 10475 case Intrinsic::ppc_vsx_stxvw4x: 10476 VT = MVT::v4i32; 10477 break; 10478 case Intrinsic::ppc_vsx_stxvd2x: 10479 VT = MVT::v2f64; 10480 break; 10481 case Intrinsic::ppc_vsx_stxvw4x_be: 10482 VT = MVT::v4i32; 10483 break; 10484 case Intrinsic::ppc_vsx_stxvd2x_be: 10485 VT = MVT::v2f64; 10486 break; 10487 case Intrinsic::ppc_altivec_stvebx: 10488 VT = MVT::i8; 10489 break; 10490 case Intrinsic::ppc_altivec_stvehx: 10491 VT = MVT::i16; 10492 break; 10493 case Intrinsic::ppc_altivec_stvewx: 10494 VT = MVT::i32; 10495 break; 10496 } 10497 10498 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10499 } 10500 10501 return false; 10502 } 10503 10504 // Return true is there is a nearyby consecutive load to the one provided 10505 // (regardless of alignment). We search up and down the chain, looking though 10506 // token factors and other loads (but nothing else). As a result, a true result 10507 // indicates that it is safe to create a new consecutive load adjacent to the 10508 // load provided. 10509 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10510 SDValue Chain = LD->getChain(); 10511 EVT VT = LD->getMemoryVT(); 10512 10513 SmallSet<SDNode *, 16> LoadRoots; 10514 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10515 SmallSet<SDNode *, 16> Visited; 10516 10517 // First, search up the chain, branching to follow all token-factor operands. 10518 // If we find a consecutive load, then we're done, otherwise, record all 10519 // nodes just above the top-level loads and token factors. 10520 while (!Queue.empty()) { 10521 SDNode *ChainNext = Queue.pop_back_val(); 10522 if (!Visited.insert(ChainNext).second) 10523 continue; 10524 10525 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10526 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10527 return true; 10528 10529 if (!Visited.count(ChainLD->getChain().getNode())) 10530 Queue.push_back(ChainLD->getChain().getNode()); 10531 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10532 for (const SDUse &O : ChainNext->ops()) 10533 if (!Visited.count(O.getNode())) 10534 Queue.push_back(O.getNode()); 10535 } else 10536 LoadRoots.insert(ChainNext); 10537 } 10538 10539 // Second, search down the chain, starting from the top-level nodes recorded 10540 // in the first phase. These top-level nodes are the nodes just above all 10541 // loads and token factors. Starting with their uses, recursively look though 10542 // all loads (just the chain uses) and token factors to find a consecutive 10543 // load. 10544 Visited.clear(); 10545 Queue.clear(); 10546 10547 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10548 IE = LoadRoots.end(); I != IE; ++I) { 10549 Queue.push_back(*I); 10550 10551 while (!Queue.empty()) { 10552 SDNode *LoadRoot = Queue.pop_back_val(); 10553 if (!Visited.insert(LoadRoot).second) 10554 continue; 10555 10556 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10557 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10558 return true; 10559 10560 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10561 UE = LoadRoot->use_end(); UI != UE; ++UI) 10562 if (((isa<MemSDNode>(*UI) && 10563 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10564 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10565 Queue.push_back(*UI); 10566 } 10567 } 10568 10569 return false; 10570 } 10571 10572 /// This function is called when we have proved that a SETCC node can be replaced 10573 /// by subtraction (and other supporting instructions) so that the result of 10574 /// comparison is kept in a GPR instead of CR. This function is purely for 10575 /// codegen purposes and has some flags to guide the codegen process. 10576 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10577 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10578 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10579 10580 // Zero extend the operands to the largest legal integer. Originally, they 10581 // must be of a strictly smaller size. 10582 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10583 DAG.getConstant(Size, DL, MVT::i32)); 10584 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10585 DAG.getConstant(Size, DL, MVT::i32)); 10586 10587 // Swap if needed. Depends on the condition code. 10588 if (Swap) 10589 std::swap(Op0, Op1); 10590 10591 // Subtract extended integers. 10592 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10593 10594 // Move the sign bit to the least significant position and zero out the rest. 10595 // Now the least significant bit carries the result of original comparison. 10596 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10597 DAG.getConstant(Size - 1, DL, MVT::i32)); 10598 auto Final = Shifted; 10599 10600 // Complement the result if needed. Based on the condition code. 10601 if (Complement) 10602 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10603 DAG.getConstant(1, DL, MVT::i64)); 10604 10605 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 10606 } 10607 10608 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 10609 DAGCombinerInfo &DCI) const { 10610 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10611 10612 SelectionDAG &DAG = DCI.DAG; 10613 SDLoc DL(N); 10614 10615 // Size of integers being compared has a critical role in the following 10616 // analysis, so we prefer to do this when all types are legal. 10617 if (!DCI.isAfterLegalizeVectorOps()) 10618 return SDValue(); 10619 10620 // If all users of SETCC extend its value to a legal integer type 10621 // then we replace SETCC with a subtraction 10622 for (SDNode::use_iterator UI = N->use_begin(), 10623 UE = N->use_end(); UI != UE; ++UI) { 10624 if (UI->getOpcode() != ISD::ZERO_EXTEND) 10625 return SDValue(); 10626 } 10627 10628 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10629 auto OpSize = N->getOperand(0).getValueSizeInBits(); 10630 10631 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 10632 10633 if (OpSize < Size) { 10634 switch (CC) { 10635 default: break; 10636 case ISD::SETULT: 10637 return generateEquivalentSub(N, Size, false, false, DL, DAG); 10638 case ISD::SETULE: 10639 return generateEquivalentSub(N, Size, true, true, DL, DAG); 10640 case ISD::SETUGT: 10641 return generateEquivalentSub(N, Size, false, true, DL, DAG); 10642 case ISD::SETUGE: 10643 return generateEquivalentSub(N, Size, true, false, DL, DAG); 10644 } 10645 } 10646 10647 return SDValue(); 10648 } 10649 10650 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 10651 DAGCombinerInfo &DCI) const { 10652 SelectionDAG &DAG = DCI.DAG; 10653 SDLoc dl(N); 10654 10655 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 10656 // If we're tracking CR bits, we need to be careful that we don't have: 10657 // trunc(binary-ops(zext(x), zext(y))) 10658 // or 10659 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 10660 // such that we're unnecessarily moving things into GPRs when it would be 10661 // better to keep them in CR bits. 10662 10663 // Note that trunc here can be an actual i1 trunc, or can be the effective 10664 // truncation that comes from a setcc or select_cc. 10665 if (N->getOpcode() == ISD::TRUNCATE && 10666 N->getValueType(0) != MVT::i1) 10667 return SDValue(); 10668 10669 if (N->getOperand(0).getValueType() != MVT::i32 && 10670 N->getOperand(0).getValueType() != MVT::i64) 10671 return SDValue(); 10672 10673 if (N->getOpcode() == ISD::SETCC || 10674 N->getOpcode() == ISD::SELECT_CC) { 10675 // If we're looking at a comparison, then we need to make sure that the 10676 // high bits (all except for the first) don't matter the result. 10677 ISD::CondCode CC = 10678 cast<CondCodeSDNode>(N->getOperand( 10679 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 10680 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 10681 10682 if (ISD::isSignedIntSetCC(CC)) { 10683 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 10684 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 10685 return SDValue(); 10686 } else if (ISD::isUnsignedIntSetCC(CC)) { 10687 if (!DAG.MaskedValueIsZero(N->getOperand(0), 10688 APInt::getHighBitsSet(OpBits, OpBits-1)) || 10689 !DAG.MaskedValueIsZero(N->getOperand(1), 10690 APInt::getHighBitsSet(OpBits, OpBits-1))) 10691 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 10692 : SDValue()); 10693 } else { 10694 // This is neither a signed nor an unsigned comparison, just make sure 10695 // that the high bits are equal. 10696 KnownBits Op1Known, Op2Known; 10697 DAG.computeKnownBits(N->getOperand(0), Op1Known); 10698 DAG.computeKnownBits(N->getOperand(1), Op2Known); 10699 10700 // We don't really care about what is known about the first bit (if 10701 // anything), so clear it in all masks prior to comparing them. 10702 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 10703 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 10704 10705 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 10706 return SDValue(); 10707 } 10708 } 10709 10710 // We now know that the higher-order bits are irrelevant, we just need to 10711 // make sure that all of the intermediate operations are bit operations, and 10712 // all inputs are extensions. 10713 if (N->getOperand(0).getOpcode() != ISD::AND && 10714 N->getOperand(0).getOpcode() != ISD::OR && 10715 N->getOperand(0).getOpcode() != ISD::XOR && 10716 N->getOperand(0).getOpcode() != ISD::SELECT && 10717 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 10718 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 10719 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 10720 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 10721 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 10722 return SDValue(); 10723 10724 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 10725 N->getOperand(1).getOpcode() != ISD::AND && 10726 N->getOperand(1).getOpcode() != ISD::OR && 10727 N->getOperand(1).getOpcode() != ISD::XOR && 10728 N->getOperand(1).getOpcode() != ISD::SELECT && 10729 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 10730 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 10731 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 10732 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 10733 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 10734 return SDValue(); 10735 10736 SmallVector<SDValue, 4> Inputs; 10737 SmallVector<SDValue, 8> BinOps, PromOps; 10738 SmallPtrSet<SDNode *, 16> Visited; 10739 10740 for (unsigned i = 0; i < 2; ++i) { 10741 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10742 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10743 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10744 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10745 isa<ConstantSDNode>(N->getOperand(i))) 10746 Inputs.push_back(N->getOperand(i)); 10747 else 10748 BinOps.push_back(N->getOperand(i)); 10749 10750 if (N->getOpcode() == ISD::TRUNCATE) 10751 break; 10752 } 10753 10754 // Visit all inputs, collect all binary operations (and, or, xor and 10755 // select) that are all fed by extensions. 10756 while (!BinOps.empty()) { 10757 SDValue BinOp = BinOps.back(); 10758 BinOps.pop_back(); 10759 10760 if (!Visited.insert(BinOp.getNode()).second) 10761 continue; 10762 10763 PromOps.push_back(BinOp); 10764 10765 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10766 // The condition of the select is not promoted. 10767 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10768 continue; 10769 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10770 continue; 10771 10772 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10773 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10774 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 10775 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 10776 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10777 Inputs.push_back(BinOp.getOperand(i)); 10778 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10779 BinOp.getOperand(i).getOpcode() == ISD::OR || 10780 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10781 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10782 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 10783 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10784 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 10785 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 10786 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 10787 BinOps.push_back(BinOp.getOperand(i)); 10788 } else { 10789 // We have an input that is not an extension or another binary 10790 // operation; we'll abort this transformation. 10791 return SDValue(); 10792 } 10793 } 10794 } 10795 10796 // Make sure that this is a self-contained cluster of operations (which 10797 // is not quite the same thing as saying that everything has only one 10798 // use). 10799 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10800 if (isa<ConstantSDNode>(Inputs[i])) 10801 continue; 10802 10803 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 10804 UE = Inputs[i].getNode()->use_end(); 10805 UI != UE; ++UI) { 10806 SDNode *User = *UI; 10807 if (User != N && !Visited.count(User)) 10808 return SDValue(); 10809 10810 // Make sure that we're not going to promote the non-output-value 10811 // operand(s) or SELECT or SELECT_CC. 10812 // FIXME: Although we could sometimes handle this, and it does occur in 10813 // practice that one of the condition inputs to the select is also one of 10814 // the outputs, we currently can't deal with this. 10815 if (User->getOpcode() == ISD::SELECT) { 10816 if (User->getOperand(0) == Inputs[i]) 10817 return SDValue(); 10818 } else if (User->getOpcode() == ISD::SELECT_CC) { 10819 if (User->getOperand(0) == Inputs[i] || 10820 User->getOperand(1) == Inputs[i]) 10821 return SDValue(); 10822 } 10823 } 10824 } 10825 10826 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 10827 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 10828 UE = PromOps[i].getNode()->use_end(); 10829 UI != UE; ++UI) { 10830 SDNode *User = *UI; 10831 if (User != N && !Visited.count(User)) 10832 return SDValue(); 10833 10834 // Make sure that we're not going to promote the non-output-value 10835 // operand(s) or SELECT or SELECT_CC. 10836 // FIXME: Although we could sometimes handle this, and it does occur in 10837 // practice that one of the condition inputs to the select is also one of 10838 // the outputs, we currently can't deal with this. 10839 if (User->getOpcode() == ISD::SELECT) { 10840 if (User->getOperand(0) == PromOps[i]) 10841 return SDValue(); 10842 } else if (User->getOpcode() == ISD::SELECT_CC) { 10843 if (User->getOperand(0) == PromOps[i] || 10844 User->getOperand(1) == PromOps[i]) 10845 return SDValue(); 10846 } 10847 } 10848 } 10849 10850 // Replace all inputs with the extension operand. 10851 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 10852 // Constants may have users outside the cluster of to-be-promoted nodes, 10853 // and so we need to replace those as we do the promotions. 10854 if (isa<ConstantSDNode>(Inputs[i])) 10855 continue; 10856 else 10857 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 10858 } 10859 10860 std::list<HandleSDNode> PromOpHandles; 10861 for (auto &PromOp : PromOps) 10862 PromOpHandles.emplace_back(PromOp); 10863 10864 // Replace all operations (these are all the same, but have a different 10865 // (i1) return type). DAG.getNode will validate that the types of 10866 // a binary operator match, so go through the list in reverse so that 10867 // we've likely promoted both operands first. Any intermediate truncations or 10868 // extensions disappear. 10869 while (!PromOpHandles.empty()) { 10870 SDValue PromOp = PromOpHandles.back().getValue(); 10871 PromOpHandles.pop_back(); 10872 10873 if (PromOp.getOpcode() == ISD::TRUNCATE || 10874 PromOp.getOpcode() == ISD::SIGN_EXTEND || 10875 PromOp.getOpcode() == ISD::ZERO_EXTEND || 10876 PromOp.getOpcode() == ISD::ANY_EXTEND) { 10877 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 10878 PromOp.getOperand(0).getValueType() != MVT::i1) { 10879 // The operand is not yet ready (see comment below). 10880 PromOpHandles.emplace_front(PromOp); 10881 continue; 10882 } 10883 10884 SDValue RepValue = PromOp.getOperand(0); 10885 if (isa<ConstantSDNode>(RepValue)) 10886 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 10887 10888 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 10889 continue; 10890 } 10891 10892 unsigned C; 10893 switch (PromOp.getOpcode()) { 10894 default: C = 0; break; 10895 case ISD::SELECT: C = 1; break; 10896 case ISD::SELECT_CC: C = 2; break; 10897 } 10898 10899 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 10900 PromOp.getOperand(C).getValueType() != MVT::i1) || 10901 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 10902 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 10903 // The to-be-promoted operands of this node have not yet been 10904 // promoted (this should be rare because we're going through the 10905 // list backward, but if one of the operands has several users in 10906 // this cluster of to-be-promoted nodes, it is possible). 10907 PromOpHandles.emplace_front(PromOp); 10908 continue; 10909 } 10910 10911 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 10912 PromOp.getNode()->op_end()); 10913 10914 // If there are any constant inputs, make sure they're replaced now. 10915 for (unsigned i = 0; i < 2; ++i) 10916 if (isa<ConstantSDNode>(Ops[C+i])) 10917 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 10918 10919 DAG.ReplaceAllUsesOfValueWith(PromOp, 10920 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 10921 } 10922 10923 // Now we're left with the initial truncation itself. 10924 if (N->getOpcode() == ISD::TRUNCATE) 10925 return N->getOperand(0); 10926 10927 // Otherwise, this is a comparison. The operands to be compared have just 10928 // changed type (to i1), but everything else is the same. 10929 return SDValue(N, 0); 10930 } 10931 10932 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 10933 DAGCombinerInfo &DCI) const { 10934 SelectionDAG &DAG = DCI.DAG; 10935 SDLoc dl(N); 10936 10937 // If we're tracking CR bits, we need to be careful that we don't have: 10938 // zext(binary-ops(trunc(x), trunc(y))) 10939 // or 10940 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 10941 // such that we're unnecessarily moving things into CR bits that can more 10942 // efficiently stay in GPRs. Note that if we're not certain that the high 10943 // bits are set as required by the final extension, we still may need to do 10944 // some masking to get the proper behavior. 10945 10946 // This same functionality is important on PPC64 when dealing with 10947 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 10948 // the return values of functions. Because it is so similar, it is handled 10949 // here as well. 10950 10951 if (N->getValueType(0) != MVT::i32 && 10952 N->getValueType(0) != MVT::i64) 10953 return SDValue(); 10954 10955 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 10956 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 10957 return SDValue(); 10958 10959 if (N->getOperand(0).getOpcode() != ISD::AND && 10960 N->getOperand(0).getOpcode() != ISD::OR && 10961 N->getOperand(0).getOpcode() != ISD::XOR && 10962 N->getOperand(0).getOpcode() != ISD::SELECT && 10963 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 10964 return SDValue(); 10965 10966 SmallVector<SDValue, 4> Inputs; 10967 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 10968 SmallPtrSet<SDNode *, 16> Visited; 10969 10970 // Visit all inputs, collect all binary operations (and, or, xor and 10971 // select) that are all fed by truncations. 10972 while (!BinOps.empty()) { 10973 SDValue BinOp = BinOps.back(); 10974 BinOps.pop_back(); 10975 10976 if (!Visited.insert(BinOp.getNode()).second) 10977 continue; 10978 10979 PromOps.push_back(BinOp); 10980 10981 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 10982 // The condition of the select is not promoted. 10983 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 10984 continue; 10985 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 10986 continue; 10987 10988 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 10989 isa<ConstantSDNode>(BinOp.getOperand(i))) { 10990 Inputs.push_back(BinOp.getOperand(i)); 10991 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 10992 BinOp.getOperand(i).getOpcode() == ISD::OR || 10993 BinOp.getOperand(i).getOpcode() == ISD::XOR || 10994 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 10995 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 10996 BinOps.push_back(BinOp.getOperand(i)); 10997 } else { 10998 // We have an input that is not a truncation or another binary 10999 // operation; we'll abort this transformation. 11000 return SDValue(); 11001 } 11002 } 11003 } 11004 11005 // The operands of a select that must be truncated when the select is 11006 // promoted because the operand is actually part of the to-be-promoted set. 11007 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11008 11009 // Make sure that this is a self-contained cluster of operations (which 11010 // is not quite the same thing as saying that everything has only one 11011 // use). 11012 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11013 if (isa<ConstantSDNode>(Inputs[i])) 11014 continue; 11015 11016 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11017 UE = Inputs[i].getNode()->use_end(); 11018 UI != UE; ++UI) { 11019 SDNode *User = *UI; 11020 if (User != N && !Visited.count(User)) 11021 return SDValue(); 11022 11023 // If we're going to promote the non-output-value operand(s) or SELECT or 11024 // SELECT_CC, record them for truncation. 11025 if (User->getOpcode() == ISD::SELECT) { 11026 if (User->getOperand(0) == Inputs[i]) 11027 SelectTruncOp[0].insert(std::make_pair(User, 11028 User->getOperand(0).getValueType())); 11029 } else if (User->getOpcode() == ISD::SELECT_CC) { 11030 if (User->getOperand(0) == Inputs[i]) 11031 SelectTruncOp[0].insert(std::make_pair(User, 11032 User->getOperand(0).getValueType())); 11033 if (User->getOperand(1) == Inputs[i]) 11034 SelectTruncOp[1].insert(std::make_pair(User, 11035 User->getOperand(1).getValueType())); 11036 } 11037 } 11038 } 11039 11040 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11041 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11042 UE = PromOps[i].getNode()->use_end(); 11043 UI != UE; ++UI) { 11044 SDNode *User = *UI; 11045 if (User != N && !Visited.count(User)) 11046 return SDValue(); 11047 11048 // If we're going to promote the non-output-value operand(s) or SELECT or 11049 // SELECT_CC, record them for truncation. 11050 if (User->getOpcode() == ISD::SELECT) { 11051 if (User->getOperand(0) == PromOps[i]) 11052 SelectTruncOp[0].insert(std::make_pair(User, 11053 User->getOperand(0).getValueType())); 11054 } else if (User->getOpcode() == ISD::SELECT_CC) { 11055 if (User->getOperand(0) == PromOps[i]) 11056 SelectTruncOp[0].insert(std::make_pair(User, 11057 User->getOperand(0).getValueType())); 11058 if (User->getOperand(1) == PromOps[i]) 11059 SelectTruncOp[1].insert(std::make_pair(User, 11060 User->getOperand(1).getValueType())); 11061 } 11062 } 11063 } 11064 11065 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11066 bool ReallyNeedsExt = false; 11067 if (N->getOpcode() != ISD::ANY_EXTEND) { 11068 // If all of the inputs are not already sign/zero extended, then 11069 // we'll still need to do that at the end. 11070 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11071 if (isa<ConstantSDNode>(Inputs[i])) 11072 continue; 11073 11074 unsigned OpBits = 11075 Inputs[i].getOperand(0).getValueSizeInBits(); 11076 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11077 11078 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11079 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11080 APInt::getHighBitsSet(OpBits, 11081 OpBits-PromBits))) || 11082 (N->getOpcode() == ISD::SIGN_EXTEND && 11083 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11084 (OpBits-(PromBits-1)))) { 11085 ReallyNeedsExt = true; 11086 break; 11087 } 11088 } 11089 } 11090 11091 // Replace all inputs, either with the truncation operand, or a 11092 // truncation or extension to the final output type. 11093 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11094 // Constant inputs need to be replaced with the to-be-promoted nodes that 11095 // use them because they might have users outside of the cluster of 11096 // promoted nodes. 11097 if (isa<ConstantSDNode>(Inputs[i])) 11098 continue; 11099 11100 SDValue InSrc = Inputs[i].getOperand(0); 11101 if (Inputs[i].getValueType() == N->getValueType(0)) 11102 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11103 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11104 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11105 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11106 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11107 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11108 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11109 else 11110 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11111 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11112 } 11113 11114 std::list<HandleSDNode> PromOpHandles; 11115 for (auto &PromOp : PromOps) 11116 PromOpHandles.emplace_back(PromOp); 11117 11118 // Replace all operations (these are all the same, but have a different 11119 // (promoted) return type). DAG.getNode will validate that the types of 11120 // a binary operator match, so go through the list in reverse so that 11121 // we've likely promoted both operands first. 11122 while (!PromOpHandles.empty()) { 11123 SDValue PromOp = PromOpHandles.back().getValue(); 11124 PromOpHandles.pop_back(); 11125 11126 unsigned C; 11127 switch (PromOp.getOpcode()) { 11128 default: C = 0; break; 11129 case ISD::SELECT: C = 1; break; 11130 case ISD::SELECT_CC: C = 2; break; 11131 } 11132 11133 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11134 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11135 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11136 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11137 // The to-be-promoted operands of this node have not yet been 11138 // promoted (this should be rare because we're going through the 11139 // list backward, but if one of the operands has several users in 11140 // this cluster of to-be-promoted nodes, it is possible). 11141 PromOpHandles.emplace_front(PromOp); 11142 continue; 11143 } 11144 11145 // For SELECT and SELECT_CC nodes, we do a similar check for any 11146 // to-be-promoted comparison inputs. 11147 if (PromOp.getOpcode() == ISD::SELECT || 11148 PromOp.getOpcode() == ISD::SELECT_CC) { 11149 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11150 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11151 (SelectTruncOp[1].count(PromOp.getNode()) && 11152 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11153 PromOpHandles.emplace_front(PromOp); 11154 continue; 11155 } 11156 } 11157 11158 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11159 PromOp.getNode()->op_end()); 11160 11161 // If this node has constant inputs, then they'll need to be promoted here. 11162 for (unsigned i = 0; i < 2; ++i) { 11163 if (!isa<ConstantSDNode>(Ops[C+i])) 11164 continue; 11165 if (Ops[C+i].getValueType() == N->getValueType(0)) 11166 continue; 11167 11168 if (N->getOpcode() == ISD::SIGN_EXTEND) 11169 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11170 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11171 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11172 else 11173 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11174 } 11175 11176 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11177 // truncate them again to the original value type. 11178 if (PromOp.getOpcode() == ISD::SELECT || 11179 PromOp.getOpcode() == ISD::SELECT_CC) { 11180 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11181 if (SI0 != SelectTruncOp[0].end()) 11182 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11183 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11184 if (SI1 != SelectTruncOp[1].end()) 11185 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11186 } 11187 11188 DAG.ReplaceAllUsesOfValueWith(PromOp, 11189 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11190 } 11191 11192 // Now we're left with the initial extension itself. 11193 if (!ReallyNeedsExt) 11194 return N->getOperand(0); 11195 11196 // To zero extend, just mask off everything except for the first bit (in the 11197 // i1 case). 11198 if (N->getOpcode() == ISD::ZERO_EXTEND) 11199 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11200 DAG.getConstant(APInt::getLowBitsSet( 11201 N->getValueSizeInBits(0), PromBits), 11202 dl, N->getValueType(0))); 11203 11204 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11205 "Invalid extension type"); 11206 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11207 SDValue ShiftCst = 11208 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11209 return DAG.getNode( 11210 ISD::SRA, dl, N->getValueType(0), 11211 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11212 ShiftCst); 11213 } 11214 11215 /// \brief Reduces the number of fp-to-int conversion when building a vector. 11216 /// 11217 /// If this vector is built out of floating to integer conversions, 11218 /// transform it to a vector built out of floating point values followed by a 11219 /// single floating to integer conversion of the vector. 11220 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11221 /// becomes (fptosi (build_vector ($A, $B, ...))) 11222 SDValue PPCTargetLowering:: 11223 combineElementTruncationToVectorTruncation(SDNode *N, 11224 DAGCombinerInfo &DCI) const { 11225 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11226 "Should be called with a BUILD_VECTOR node"); 11227 11228 SelectionDAG &DAG = DCI.DAG; 11229 SDLoc dl(N); 11230 11231 SDValue FirstInput = N->getOperand(0); 11232 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11233 "The input operand must be an fp-to-int conversion."); 11234 11235 // This combine happens after legalization so the fp_to_[su]i nodes are 11236 // already converted to PPCSISD nodes. 11237 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11238 if (FirstConversion == PPCISD::FCTIDZ || 11239 FirstConversion == PPCISD::FCTIDUZ || 11240 FirstConversion == PPCISD::FCTIWZ || 11241 FirstConversion == PPCISD::FCTIWUZ) { 11242 bool IsSplat = true; 11243 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11244 FirstConversion == PPCISD::FCTIWUZ; 11245 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11246 SmallVector<SDValue, 4> Ops; 11247 EVT TargetVT = N->getValueType(0); 11248 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11249 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 11250 return SDValue(); 11251 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 11252 if (NextConversion != FirstConversion) 11253 return SDValue(); 11254 if (N->getOperand(i) != FirstInput) 11255 IsSplat = false; 11256 } 11257 11258 // If this is a splat, we leave it as-is since there will be only a single 11259 // fp-to-int conversion followed by a splat of the integer. This is better 11260 // for 32-bit and smaller ints and neutral for 64-bit ints. 11261 if (IsSplat) 11262 return SDValue(); 11263 11264 // Now that we know we have the right type of node, get its operands 11265 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11266 SDValue In = N->getOperand(i).getOperand(0); 11267 // For 32-bit values, we need to add an FP_ROUND node. 11268 if (Is32Bit) { 11269 if (In.isUndef()) 11270 Ops.push_back(DAG.getUNDEF(SrcVT)); 11271 else { 11272 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11273 MVT::f32, In.getOperand(0), 11274 DAG.getIntPtrConstant(1, dl)); 11275 Ops.push_back(Trunc); 11276 } 11277 } else 11278 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11279 } 11280 11281 unsigned Opcode; 11282 if (FirstConversion == PPCISD::FCTIDZ || 11283 FirstConversion == PPCISD::FCTIWZ) 11284 Opcode = ISD::FP_TO_SINT; 11285 else 11286 Opcode = ISD::FP_TO_UINT; 11287 11288 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11289 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11290 return DAG.getNode(Opcode, dl, TargetVT, BV); 11291 } 11292 return SDValue(); 11293 } 11294 11295 /// \brief Reduce the number of loads when building a vector. 11296 /// 11297 /// Building a vector out of multiple loads can be converted to a load 11298 /// of the vector type if the loads are consecutive. If the loads are 11299 /// consecutive but in descending order, a shuffle is added at the end 11300 /// to reorder the vector. 11301 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11302 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11303 "Should be called with a BUILD_VECTOR node"); 11304 11305 SDLoc dl(N); 11306 bool InputsAreConsecutiveLoads = true; 11307 bool InputsAreReverseConsecutive = true; 11308 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11309 SDValue FirstInput = N->getOperand(0); 11310 bool IsRoundOfExtLoad = false; 11311 11312 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11313 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11314 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11315 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11316 } 11317 // Not a build vector of (possibly fp_rounded) loads. 11318 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 11319 return SDValue(); 11320 11321 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11322 // If any inputs are fp_round(extload), they all must be. 11323 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11324 return SDValue(); 11325 11326 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11327 N->getOperand(i); 11328 if (NextInput.getOpcode() != ISD::LOAD) 11329 return SDValue(); 11330 11331 SDValue PreviousInput = 11332 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11333 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11334 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11335 11336 // If any inputs are fp_round(extload), they all must be. 11337 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11338 return SDValue(); 11339 11340 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11341 InputsAreConsecutiveLoads = false; 11342 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11343 InputsAreReverseConsecutive = false; 11344 11345 // Exit early if the loads are neither consecutive nor reverse consecutive. 11346 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 11347 return SDValue(); 11348 } 11349 11350 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 11351 "The loads cannot be both consecutive and reverse consecutive."); 11352 11353 SDValue FirstLoadOp = 11354 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 11355 SDValue LastLoadOp = 11356 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 11357 N->getOperand(N->getNumOperands()-1); 11358 11359 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 11360 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 11361 if (InputsAreConsecutiveLoads) { 11362 assert(LD1 && "Input needs to be a LoadSDNode."); 11363 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 11364 LD1->getBasePtr(), LD1->getPointerInfo(), 11365 LD1->getAlignment()); 11366 } 11367 if (InputsAreReverseConsecutive) { 11368 assert(LDL && "Input needs to be a LoadSDNode."); 11369 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 11370 LDL->getBasePtr(), LDL->getPointerInfo(), 11371 LDL->getAlignment()); 11372 SmallVector<int, 16> Ops; 11373 for (int i = N->getNumOperands() - 1; i >= 0; i--) 11374 Ops.push_back(i); 11375 11376 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 11377 DAG.getUNDEF(N->getValueType(0)), Ops); 11378 } 11379 return SDValue(); 11380 } 11381 11382 // This function adds the required vector_shuffle needed to get 11383 // the elements of the vector extract in the correct position 11384 // as specified by the CorrectElems encoding. 11385 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 11386 SDValue Input, uint64_t Elems, 11387 uint64_t CorrectElems) { 11388 SDLoc dl(N); 11389 11390 unsigned NumElems = Input.getValueType().getVectorNumElements(); 11391 SmallVector<int, 16> ShuffleMask(NumElems, -1); 11392 11393 // Knowing the element indices being extracted from the original 11394 // vector and the order in which they're being inserted, just put 11395 // them at element indices required for the instruction. 11396 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11397 if (DAG.getDataLayout().isLittleEndian()) 11398 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 11399 else 11400 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 11401 CorrectElems = CorrectElems >> 8; 11402 Elems = Elems >> 8; 11403 } 11404 11405 SDValue Shuffle = 11406 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 11407 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 11408 11409 EVT Ty = N->getValueType(0); 11410 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 11411 return BV; 11412 } 11413 11414 // Look for build vector patterns where input operands come from sign 11415 // extended vector_extract elements of specific indices. If the correct indices 11416 // aren't used, add a vector shuffle to fix up the indices and create a new 11417 // PPCISD:SExtVElems node which selects the vector sign extend instructions 11418 // during instruction selection. 11419 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 11420 // This array encodes the indices that the vector sign extend instructions 11421 // extract from when extending from one type to another for both BE and LE. 11422 // The right nibble of each byte corresponds to the LE incides. 11423 // and the left nibble of each byte corresponds to the BE incides. 11424 // For example: 0x3074B8FC byte->word 11425 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 11426 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 11427 // For example: 0x000070F8 byte->double word 11428 // For LE: the allowed indices are: 0x0,0x8 11429 // For BE: the allowed indices are: 0x7,0xF 11430 uint64_t TargetElems[] = { 11431 0x3074B8FC, // b->w 11432 0x000070F8, // b->d 11433 0x10325476, // h->w 11434 0x00003074, // h->d 11435 0x00001032, // w->d 11436 }; 11437 11438 uint64_t Elems = 0; 11439 int Index; 11440 SDValue Input; 11441 11442 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 11443 if (!Op) 11444 return false; 11445 if (Op.getOpcode() != ISD::SIGN_EXTEND) 11446 return false; 11447 11448 SDValue Extract = Op.getOperand(0); 11449 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11450 return false; 11451 11452 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 11453 if (!ExtOp) 11454 return false; 11455 11456 Index = ExtOp->getZExtValue(); 11457 if (Input && Input != Extract.getOperand(0)) 11458 return false; 11459 11460 if (!Input) 11461 Input = Extract.getOperand(0); 11462 11463 Elems = Elems << 8; 11464 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 11465 Elems |= Index; 11466 11467 return true; 11468 }; 11469 11470 // If the build vector operands aren't sign extended vector extracts, 11471 // of the same input vector, then return. 11472 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11473 if (!isSExtOfVecExtract(N->getOperand(i))) { 11474 return SDValue(); 11475 } 11476 } 11477 11478 // If the vector extract indicies are not correct, add the appropriate 11479 // vector_shuffle. 11480 int TgtElemArrayIdx; 11481 int InputSize = Input.getValueType().getScalarSizeInBits(); 11482 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 11483 if (InputSize + OutputSize == 40) 11484 TgtElemArrayIdx = 0; 11485 else if (InputSize + OutputSize == 72) 11486 TgtElemArrayIdx = 1; 11487 else if (InputSize + OutputSize == 48) 11488 TgtElemArrayIdx = 2; 11489 else if (InputSize + OutputSize == 80) 11490 TgtElemArrayIdx = 3; 11491 else if (InputSize + OutputSize == 96) 11492 TgtElemArrayIdx = 4; 11493 else 11494 return SDValue(); 11495 11496 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 11497 CorrectElems = DAG.getDataLayout().isLittleEndian() 11498 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 11499 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 11500 if (Elems != CorrectElems) { 11501 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 11502 } 11503 11504 // Regular lowering will catch cases where a shuffle is not needed. 11505 return SDValue(); 11506 } 11507 11508 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11509 DAGCombinerInfo &DCI) const { 11510 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11511 "Should be called with a BUILD_VECTOR node"); 11512 11513 SelectionDAG &DAG = DCI.DAG; 11514 SDLoc dl(N); 11515 11516 if (!Subtarget.hasVSX()) 11517 return SDValue(); 11518 11519 // The target independent DAG combiner will leave a build_vector of 11520 // float-to-int conversions intact. We can generate MUCH better code for 11521 // a float-to-int conversion of a vector of floats. 11522 SDValue FirstInput = N->getOperand(0); 11523 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11524 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11525 if (Reduced) 11526 return Reduced; 11527 } 11528 11529 // If we're building a vector out of consecutive loads, just load that 11530 // vector type. 11531 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11532 if (Reduced) 11533 return Reduced; 11534 11535 // If we're building a vector out of extended elements from another vector 11536 // we have P9 vector integer extend instructions. 11537 if (Subtarget.hasP9Altivec()) { 11538 Reduced = combineBVOfVecSExt(N, DAG); 11539 if (Reduced) 11540 return Reduced; 11541 } 11542 11543 11544 if (N->getValueType(0) != MVT::v2f64) 11545 return SDValue(); 11546 11547 // Looking for: 11548 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11549 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11550 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11551 return SDValue(); 11552 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11553 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11554 return SDValue(); 11555 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11556 return SDValue(); 11557 11558 SDValue Ext1 = FirstInput.getOperand(0); 11559 SDValue Ext2 = N->getOperand(1).getOperand(0); 11560 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11561 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11562 return SDValue(); 11563 11564 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11565 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11566 if (!Ext1Op || !Ext2Op) 11567 return SDValue(); 11568 if (Ext1.getValueType() != MVT::i32 || 11569 Ext2.getValueType() != MVT::i32) 11570 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11571 return SDValue(); 11572 11573 int FirstElem = Ext1Op->getZExtValue(); 11574 int SecondElem = Ext2Op->getZExtValue(); 11575 int SubvecIdx; 11576 if (FirstElem == 0 && SecondElem == 1) 11577 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11578 else if (FirstElem == 2 && SecondElem == 3) 11579 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11580 else 11581 return SDValue(); 11582 11583 SDValue SrcVec = Ext1.getOperand(0); 11584 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11585 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11586 return DAG.getNode(NodeType, dl, MVT::v2f64, 11587 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11588 } 11589 11590 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11591 DAGCombinerInfo &DCI) const { 11592 assert((N->getOpcode() == ISD::SINT_TO_FP || 11593 N->getOpcode() == ISD::UINT_TO_FP) && 11594 "Need an int -> FP conversion node here"); 11595 11596 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11597 return SDValue(); 11598 11599 SelectionDAG &DAG = DCI.DAG; 11600 SDLoc dl(N); 11601 SDValue Op(N, 0); 11602 11603 SDValue FirstOperand(Op.getOperand(0)); 11604 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 11605 (FirstOperand.getValueType() == MVT::i8 || 11606 FirstOperand.getValueType() == MVT::i16); 11607 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 11608 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 11609 bool DstDouble = Op.getValueType() == MVT::f64; 11610 unsigned ConvOp = Signed ? 11611 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 11612 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 11613 SDValue WidthConst = 11614 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 11615 dl, false); 11616 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 11617 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 11618 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 11619 DAG.getVTList(MVT::f64, MVT::Other), 11620 Ops, MVT::i8, LDN->getMemOperand()); 11621 11622 // For signed conversion, we need to sign-extend the value in the VSR 11623 if (Signed) { 11624 SDValue ExtOps[] = { Ld, WidthConst }; 11625 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 11626 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 11627 } else 11628 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 11629 } 11630 11631 // Don't handle ppc_fp128 here or i1 conversions. 11632 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 11633 return SDValue(); 11634 if (Op.getOperand(0).getValueType() == MVT::i1) 11635 return SDValue(); 11636 11637 // For i32 intermediate values, unfortunately, the conversion functions 11638 // leave the upper 32 bits of the value are undefined. Within the set of 11639 // scalar instructions, we have no method for zero- or sign-extending the 11640 // value. Thus, we cannot handle i32 intermediate values here. 11641 if (Op.getOperand(0).getValueType() == MVT::i32) 11642 return SDValue(); 11643 11644 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 11645 "UINT_TO_FP is supported only with FPCVT"); 11646 11647 // If we have FCFIDS, then use it when converting to single-precision. 11648 // Otherwise, convert to double-precision and then round. 11649 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11650 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 11651 : PPCISD::FCFIDS) 11652 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 11653 : PPCISD::FCFID); 11654 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11655 ? MVT::f32 11656 : MVT::f64; 11657 11658 // If we're converting from a float, to an int, and back to a float again, 11659 // then we don't need the store/load pair at all. 11660 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 11661 Subtarget.hasFPCVT()) || 11662 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 11663 SDValue Src = Op.getOperand(0).getOperand(0); 11664 if (Src.getValueType() == MVT::f32) { 11665 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 11666 DCI.AddToWorklist(Src.getNode()); 11667 } else if (Src.getValueType() != MVT::f64) { 11668 // Make sure that we don't pick up a ppc_fp128 source value. 11669 return SDValue(); 11670 } 11671 11672 unsigned FCTOp = 11673 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 11674 PPCISD::FCTIDUZ; 11675 11676 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 11677 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 11678 11679 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 11680 FP = DAG.getNode(ISD::FP_ROUND, dl, 11681 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 11682 DCI.AddToWorklist(FP.getNode()); 11683 } 11684 11685 return FP; 11686 } 11687 11688 return SDValue(); 11689 } 11690 11691 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 11692 // builtins) into loads with swaps. 11693 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 11694 DAGCombinerInfo &DCI) const { 11695 SelectionDAG &DAG = DCI.DAG; 11696 SDLoc dl(N); 11697 SDValue Chain; 11698 SDValue Base; 11699 MachineMemOperand *MMO; 11700 11701 switch (N->getOpcode()) { 11702 default: 11703 llvm_unreachable("Unexpected opcode for little endian VSX load"); 11704 case ISD::LOAD: { 11705 LoadSDNode *LD = cast<LoadSDNode>(N); 11706 Chain = LD->getChain(); 11707 Base = LD->getBasePtr(); 11708 MMO = LD->getMemOperand(); 11709 // If the MMO suggests this isn't a load of a full vector, leave 11710 // things alone. For a built-in, we have to make the change for 11711 // correctness, so if there is a size problem that will be a bug. 11712 if (MMO->getSize() < 16) 11713 return SDValue(); 11714 break; 11715 } 11716 case ISD::INTRINSIC_W_CHAIN: { 11717 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11718 Chain = Intrin->getChain(); 11719 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 11720 // us what we want. Get operand 2 instead. 11721 Base = Intrin->getOperand(2); 11722 MMO = Intrin->getMemOperand(); 11723 break; 11724 } 11725 } 11726 11727 MVT VecTy = N->getValueType(0).getSimpleVT(); 11728 11729 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 11730 // aligned and the type is a vector with elements up to 4 bytes 11731 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 11732 && VecTy.getScalarSizeInBits() <= 32 ) { 11733 return SDValue(); 11734 } 11735 11736 SDValue LoadOps[] = { Chain, Base }; 11737 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 11738 DAG.getVTList(MVT::v2f64, MVT::Other), 11739 LoadOps, MVT::v2f64, MMO); 11740 11741 DCI.AddToWorklist(Load.getNode()); 11742 Chain = Load.getValue(1); 11743 SDValue Swap = DAG.getNode( 11744 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 11745 DCI.AddToWorklist(Swap.getNode()); 11746 11747 // Add a bitcast if the resulting load type doesn't match v2f64. 11748 if (VecTy != MVT::v2f64) { 11749 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 11750 DCI.AddToWorklist(N.getNode()); 11751 // Package {bitcast value, swap's chain} to match Load's shape. 11752 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 11753 N, Swap.getValue(1)); 11754 } 11755 11756 return Swap; 11757 } 11758 11759 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 11760 // builtins) into stores with swaps. 11761 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 11762 DAGCombinerInfo &DCI) const { 11763 SelectionDAG &DAG = DCI.DAG; 11764 SDLoc dl(N); 11765 SDValue Chain; 11766 SDValue Base; 11767 unsigned SrcOpnd; 11768 MachineMemOperand *MMO; 11769 11770 switch (N->getOpcode()) { 11771 default: 11772 llvm_unreachable("Unexpected opcode for little endian VSX store"); 11773 case ISD::STORE: { 11774 StoreSDNode *ST = cast<StoreSDNode>(N); 11775 Chain = ST->getChain(); 11776 Base = ST->getBasePtr(); 11777 MMO = ST->getMemOperand(); 11778 SrcOpnd = 1; 11779 // If the MMO suggests this isn't a store of a full vector, leave 11780 // things alone. For a built-in, we have to make the change for 11781 // correctness, so if there is a size problem that will be a bug. 11782 if (MMO->getSize() < 16) 11783 return SDValue(); 11784 break; 11785 } 11786 case ISD::INTRINSIC_VOID: { 11787 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11788 Chain = Intrin->getChain(); 11789 // Intrin->getBasePtr() oddly does not get what we want. 11790 Base = Intrin->getOperand(3); 11791 MMO = Intrin->getMemOperand(); 11792 SrcOpnd = 2; 11793 break; 11794 } 11795 } 11796 11797 SDValue Src = N->getOperand(SrcOpnd); 11798 MVT VecTy = Src.getValueType().getSimpleVT(); 11799 11800 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 11801 // aligned and the type is a vector with elements up to 4 bytes 11802 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 11803 && VecTy.getScalarSizeInBits() <= 32 ) { 11804 return SDValue(); 11805 } 11806 11807 // All stores are done as v2f64 and possible bit cast. 11808 if (VecTy != MVT::v2f64) { 11809 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 11810 DCI.AddToWorklist(Src.getNode()); 11811 } 11812 11813 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 11814 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 11815 DCI.AddToWorklist(Swap.getNode()); 11816 Chain = Swap.getValue(1); 11817 SDValue StoreOps[] = { Chain, Swap, Base }; 11818 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 11819 DAG.getVTList(MVT::Other), 11820 StoreOps, VecTy, MMO); 11821 DCI.AddToWorklist(Store.getNode()); 11822 return Store; 11823 } 11824 11825 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 11826 DAGCombinerInfo &DCI) const { 11827 SelectionDAG &DAG = DCI.DAG; 11828 SDLoc dl(N); 11829 switch (N->getOpcode()) { 11830 default: break; 11831 case ISD::SHL: 11832 return combineSHL(N, DCI); 11833 case ISD::SRA: 11834 return combineSRA(N, DCI); 11835 case ISD::SRL: 11836 return combineSRL(N, DCI); 11837 case PPCISD::SHL: 11838 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 11839 return N->getOperand(0); 11840 break; 11841 case PPCISD::SRL: 11842 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 11843 return N->getOperand(0); 11844 break; 11845 case PPCISD::SRA: 11846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11847 if (C->isNullValue() || // 0 >>s V -> 0. 11848 C->isAllOnesValue()) // -1 >>s V -> -1. 11849 return N->getOperand(0); 11850 } 11851 break; 11852 case ISD::SIGN_EXTEND: 11853 case ISD::ZERO_EXTEND: 11854 case ISD::ANY_EXTEND: 11855 return DAGCombineExtBoolTrunc(N, DCI); 11856 case ISD::TRUNCATE: 11857 case ISD::SETCC: 11858 case ISD::SELECT_CC: 11859 return DAGCombineTruncBoolExt(N, DCI); 11860 case ISD::SINT_TO_FP: 11861 case ISD::UINT_TO_FP: 11862 return combineFPToIntToFP(N, DCI); 11863 case ISD::STORE: { 11864 EVT Op1VT = N->getOperand(1).getValueType(); 11865 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 11866 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 11867 11868 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 11869 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 11870 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 11871 ValidTypeForStoreFltAsInt && 11872 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 11873 SDValue Val = N->getOperand(1).getOperand(0); 11874 if (Val.getValueType() == MVT::f32) { 11875 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 11876 DCI.AddToWorklist(Val.getNode()); 11877 } 11878 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 11879 DCI.AddToWorklist(Val.getNode()); 11880 11881 if (Op1VT == MVT::i32) { 11882 SDValue Ops[] = { 11883 N->getOperand(0), Val, N->getOperand(2), 11884 DAG.getValueType(N->getOperand(1).getValueType()) 11885 }; 11886 11887 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 11888 DAG.getVTList(MVT::Other), Ops, 11889 cast<StoreSDNode>(N)->getMemoryVT(), 11890 cast<StoreSDNode>(N)->getMemOperand()); 11891 } else { 11892 unsigned WidthInBytes = 11893 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 11894 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 11895 11896 SDValue Ops[] = { 11897 N->getOperand(0), Val, N->getOperand(2), WidthConst, 11898 DAG.getValueType(N->getOperand(1).getValueType()) 11899 }; 11900 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 11901 DAG.getVTList(MVT::Other), Ops, 11902 cast<StoreSDNode>(N)->getMemoryVT(), 11903 cast<StoreSDNode>(N)->getMemOperand()); 11904 } 11905 11906 DCI.AddToWorklist(Val.getNode()); 11907 return Val; 11908 } 11909 11910 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 11911 if (cast<StoreSDNode>(N)->isUnindexed() && 11912 N->getOperand(1).getOpcode() == ISD::BSWAP && 11913 N->getOperand(1).getNode()->hasOneUse() && 11914 (N->getOperand(1).getValueType() == MVT::i32 || 11915 N->getOperand(1).getValueType() == MVT::i16 || 11916 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 11917 N->getOperand(1).getValueType() == MVT::i64))) { 11918 SDValue BSwapOp = N->getOperand(1).getOperand(0); 11919 // Do an any-extend to 32-bits if this is a half-word input. 11920 if (BSwapOp.getValueType() == MVT::i16) 11921 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 11922 11923 // If the type of BSWAP operand is wider than stored memory width 11924 // it need to be shifted to the right side before STBRX. 11925 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 11926 if (Op1VT.bitsGT(mVT)) { 11927 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 11928 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 11929 DAG.getConstant(Shift, dl, MVT::i32)); 11930 // Need to truncate if this is a bswap of i64 stored as i32/i16. 11931 if (Op1VT == MVT::i64) 11932 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 11933 } 11934 11935 SDValue Ops[] = { 11936 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 11937 }; 11938 return 11939 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 11940 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 11941 cast<StoreSDNode>(N)->getMemOperand()); 11942 } 11943 11944 // For little endian, VSX stores require generating xxswapd/lxvd2x. 11945 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 11946 EVT VT = N->getOperand(1).getValueType(); 11947 if (VT.isSimple()) { 11948 MVT StoreVT = VT.getSimpleVT(); 11949 if (Subtarget.needsSwapsForVSXMemOps() && 11950 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 11951 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 11952 return expandVSXStoreForLE(N, DCI); 11953 } 11954 break; 11955 } 11956 case ISD::LOAD: { 11957 LoadSDNode *LD = cast<LoadSDNode>(N); 11958 EVT VT = LD->getValueType(0); 11959 11960 // For little endian, VSX loads require generating lxvd2x/xxswapd. 11961 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 11962 if (VT.isSimple()) { 11963 MVT LoadVT = VT.getSimpleVT(); 11964 if (Subtarget.needsSwapsForVSXMemOps() && 11965 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 11966 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 11967 return expandVSXLoadForLE(N, DCI); 11968 } 11969 11970 // We sometimes end up with a 64-bit integer load, from which we extract 11971 // two single-precision floating-point numbers. This happens with 11972 // std::complex<float>, and other similar structures, because of the way we 11973 // canonicalize structure copies. However, if we lack direct moves, 11974 // then the final bitcasts from the extracted integer values to the 11975 // floating-point numbers turn into store/load pairs. Even with direct moves, 11976 // just loading the two floating-point numbers is likely better. 11977 auto ReplaceTwoFloatLoad = [&]() { 11978 if (VT != MVT::i64) 11979 return false; 11980 11981 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 11982 LD->isVolatile()) 11983 return false; 11984 11985 // We're looking for a sequence like this: 11986 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 11987 // t16: i64 = srl t13, Constant:i32<32> 11988 // t17: i32 = truncate t16 11989 // t18: f32 = bitcast t17 11990 // t19: i32 = truncate t13 11991 // t20: f32 = bitcast t19 11992 11993 if (!LD->hasNUsesOfValue(2, 0)) 11994 return false; 11995 11996 auto UI = LD->use_begin(); 11997 while (UI.getUse().getResNo() != 0) ++UI; 11998 SDNode *Trunc = *UI++; 11999 while (UI.getUse().getResNo() != 0) ++UI; 12000 SDNode *RightShift = *UI; 12001 if (Trunc->getOpcode() != ISD::TRUNCATE) 12002 std::swap(Trunc, RightShift); 12003 12004 if (Trunc->getOpcode() != ISD::TRUNCATE || 12005 Trunc->getValueType(0) != MVT::i32 || 12006 !Trunc->hasOneUse()) 12007 return false; 12008 if (RightShift->getOpcode() != ISD::SRL || 12009 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12010 RightShift->getConstantOperandVal(1) != 32 || 12011 !RightShift->hasOneUse()) 12012 return false; 12013 12014 SDNode *Trunc2 = *RightShift->use_begin(); 12015 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12016 Trunc2->getValueType(0) != MVT::i32 || 12017 !Trunc2->hasOneUse()) 12018 return false; 12019 12020 SDNode *Bitcast = *Trunc->use_begin(); 12021 SDNode *Bitcast2 = *Trunc2->use_begin(); 12022 12023 if (Bitcast->getOpcode() != ISD::BITCAST || 12024 Bitcast->getValueType(0) != MVT::f32) 12025 return false; 12026 if (Bitcast2->getOpcode() != ISD::BITCAST || 12027 Bitcast2->getValueType(0) != MVT::f32) 12028 return false; 12029 12030 if (Subtarget.isLittleEndian()) 12031 std::swap(Bitcast, Bitcast2); 12032 12033 // Bitcast has the second float (in memory-layout order) and Bitcast2 12034 // has the first one. 12035 12036 SDValue BasePtr = LD->getBasePtr(); 12037 if (LD->isIndexed()) { 12038 assert(LD->getAddressingMode() == ISD::PRE_INC && 12039 "Non-pre-inc AM on PPC?"); 12040 BasePtr = 12041 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12042 LD->getOffset()); 12043 } 12044 12045 auto MMOFlags = 12046 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12047 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12048 LD->getPointerInfo(), LD->getAlignment(), 12049 MMOFlags, LD->getAAInfo()); 12050 SDValue AddPtr = 12051 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12052 BasePtr, DAG.getIntPtrConstant(4, dl)); 12053 SDValue FloatLoad2 = DAG.getLoad( 12054 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12055 LD->getPointerInfo().getWithOffset(4), 12056 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12057 12058 if (LD->isIndexed()) { 12059 // Note that DAGCombine should re-form any pre-increment load(s) from 12060 // what is produced here if that makes sense. 12061 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12062 } 12063 12064 DCI.CombineTo(Bitcast2, FloatLoad); 12065 DCI.CombineTo(Bitcast, FloatLoad2); 12066 12067 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12068 SDValue(FloatLoad2.getNode(), 1)); 12069 return true; 12070 }; 12071 12072 if (ReplaceTwoFloatLoad()) 12073 return SDValue(N, 0); 12074 12075 EVT MemVT = LD->getMemoryVT(); 12076 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12077 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12078 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12079 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12080 if (LD->isUnindexed() && VT.isVector() && 12081 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12082 // P8 and later hardware should just use LOAD. 12083 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12084 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12085 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12086 LD->getAlignment() >= ScalarABIAlignment)) && 12087 LD->getAlignment() < ABIAlignment) { 12088 // This is a type-legal unaligned Altivec or QPX load. 12089 SDValue Chain = LD->getChain(); 12090 SDValue Ptr = LD->getBasePtr(); 12091 bool isLittleEndian = Subtarget.isLittleEndian(); 12092 12093 // This implements the loading of unaligned vectors as described in 12094 // the venerable Apple Velocity Engine overview. Specifically: 12095 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12096 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12097 // 12098 // The general idea is to expand a sequence of one or more unaligned 12099 // loads into an alignment-based permutation-control instruction (lvsl 12100 // or lvsr), a series of regular vector loads (which always truncate 12101 // their input address to an aligned address), and a series of 12102 // permutations. The results of these permutations are the requested 12103 // loaded values. The trick is that the last "extra" load is not taken 12104 // from the address you might suspect (sizeof(vector) bytes after the 12105 // last requested load), but rather sizeof(vector) - 1 bytes after the 12106 // last requested vector. The point of this is to avoid a page fault if 12107 // the base address happened to be aligned. This works because if the 12108 // base address is aligned, then adding less than a full vector length 12109 // will cause the last vector in the sequence to be (re)loaded. 12110 // Otherwise, the next vector will be fetched as you might suspect was 12111 // necessary. 12112 12113 // We might be able to reuse the permutation generation from 12114 // a different base address offset from this one by an aligned amount. 12115 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12116 // optimization later. 12117 Intrinsic::ID Intr, IntrLD, IntrPerm; 12118 MVT PermCntlTy, PermTy, LDTy; 12119 if (Subtarget.hasAltivec()) { 12120 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12121 Intrinsic::ppc_altivec_lvsl; 12122 IntrLD = Intrinsic::ppc_altivec_lvx; 12123 IntrPerm = Intrinsic::ppc_altivec_vperm; 12124 PermCntlTy = MVT::v16i8; 12125 PermTy = MVT::v4i32; 12126 LDTy = MVT::v4i32; 12127 } else { 12128 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12129 Intrinsic::ppc_qpx_qvlpcls; 12130 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12131 Intrinsic::ppc_qpx_qvlfs; 12132 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12133 PermCntlTy = MVT::v4f64; 12134 PermTy = MVT::v4f64; 12135 LDTy = MemVT.getSimpleVT(); 12136 } 12137 12138 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12139 12140 // Create the new MMO for the new base load. It is like the original MMO, 12141 // but represents an area in memory almost twice the vector size centered 12142 // on the original address. If the address is unaligned, we might start 12143 // reading up to (sizeof(vector)-1) bytes below the address of the 12144 // original unaligned load. 12145 MachineFunction &MF = DAG.getMachineFunction(); 12146 MachineMemOperand *BaseMMO = 12147 MF.getMachineMemOperand(LD->getMemOperand(), 12148 -(long)MemVT.getStoreSize()+1, 12149 2*MemVT.getStoreSize()-1); 12150 12151 // Create the new base load. 12152 SDValue LDXIntID = 12153 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12154 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12155 SDValue BaseLoad = 12156 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12157 DAG.getVTList(PermTy, MVT::Other), 12158 BaseLoadOps, LDTy, BaseMMO); 12159 12160 // Note that the value of IncOffset (which is provided to the next 12161 // load's pointer info offset value, and thus used to calculate the 12162 // alignment), and the value of IncValue (which is actually used to 12163 // increment the pointer value) are different! This is because we 12164 // require the next load to appear to be aligned, even though it 12165 // is actually offset from the base pointer by a lesser amount. 12166 int IncOffset = VT.getSizeInBits() / 8; 12167 int IncValue = IncOffset; 12168 12169 // Walk (both up and down) the chain looking for another load at the real 12170 // (aligned) offset (the alignment of the other load does not matter in 12171 // this case). If found, then do not use the offset reduction trick, as 12172 // that will prevent the loads from being later combined (as they would 12173 // otherwise be duplicates). 12174 if (!findConsecutiveLoad(LD, DAG)) 12175 --IncValue; 12176 12177 SDValue Increment = 12178 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12179 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12180 12181 MachineMemOperand *ExtraMMO = 12182 MF.getMachineMemOperand(LD->getMemOperand(), 12183 1, 2*MemVT.getStoreSize()-1); 12184 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12185 SDValue ExtraLoad = 12186 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12187 DAG.getVTList(PermTy, MVT::Other), 12188 ExtraLoadOps, LDTy, ExtraMMO); 12189 12190 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12191 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12192 12193 // Because vperm has a big-endian bias, we must reverse the order 12194 // of the input vectors and complement the permute control vector 12195 // when generating little endian code. We have already handled the 12196 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12197 // and ExtraLoad here. 12198 SDValue Perm; 12199 if (isLittleEndian) 12200 Perm = BuildIntrinsicOp(IntrPerm, 12201 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12202 else 12203 Perm = BuildIntrinsicOp(IntrPerm, 12204 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12205 12206 if (VT != PermTy) 12207 Perm = Subtarget.hasAltivec() ? 12208 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12209 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12210 DAG.getTargetConstant(1, dl, MVT::i64)); 12211 // second argument is 1 because this rounding 12212 // is always exact. 12213 12214 // The output of the permutation is our loaded result, the TokenFactor is 12215 // our new chain. 12216 DCI.CombineTo(N, Perm, TF); 12217 return SDValue(N, 0); 12218 } 12219 } 12220 break; 12221 case ISD::INTRINSIC_WO_CHAIN: { 12222 bool isLittleEndian = Subtarget.isLittleEndian(); 12223 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12224 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12225 : Intrinsic::ppc_altivec_lvsl); 12226 if ((IID == Intr || 12227 IID == Intrinsic::ppc_qpx_qvlpcld || 12228 IID == Intrinsic::ppc_qpx_qvlpcls) && 12229 N->getOperand(1)->getOpcode() == ISD::ADD) { 12230 SDValue Add = N->getOperand(1); 12231 12232 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12233 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12234 12235 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12236 APInt::getAllOnesValue(Bits /* alignment */) 12237 .zext(Add.getScalarValueSizeInBits()))) { 12238 SDNode *BasePtr = Add->getOperand(0).getNode(); 12239 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12240 UE = BasePtr->use_end(); 12241 UI != UE; ++UI) { 12242 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12243 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12244 // We've found another LVSL/LVSR, and this address is an aligned 12245 // multiple of that one. The results will be the same, so use the 12246 // one we've just found instead. 12247 12248 return SDValue(*UI, 0); 12249 } 12250 } 12251 } 12252 12253 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12254 SDNode *BasePtr = Add->getOperand(0).getNode(); 12255 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12256 UE = BasePtr->use_end(); UI != UE; ++UI) { 12257 if (UI->getOpcode() == ISD::ADD && 12258 isa<ConstantSDNode>(UI->getOperand(1)) && 12259 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12260 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12261 (1ULL << Bits) == 0) { 12262 SDNode *OtherAdd = *UI; 12263 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12264 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12265 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12266 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12267 return SDValue(*VI, 0); 12268 } 12269 } 12270 } 12271 } 12272 } 12273 } 12274 } 12275 12276 break; 12277 case ISD::INTRINSIC_W_CHAIN: 12278 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12279 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12280 if (Subtarget.needsSwapsForVSXMemOps()) { 12281 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12282 default: 12283 break; 12284 case Intrinsic::ppc_vsx_lxvw4x: 12285 case Intrinsic::ppc_vsx_lxvd2x: 12286 return expandVSXLoadForLE(N, DCI); 12287 } 12288 } 12289 break; 12290 case ISD::INTRINSIC_VOID: 12291 // For little endian, VSX stores require generating xxswapd/stxvd2x. 12292 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12293 if (Subtarget.needsSwapsForVSXMemOps()) { 12294 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12295 default: 12296 break; 12297 case Intrinsic::ppc_vsx_stxvw4x: 12298 case Intrinsic::ppc_vsx_stxvd2x: 12299 return expandVSXStoreForLE(N, DCI); 12300 } 12301 } 12302 break; 12303 case ISD::BSWAP: 12304 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 12305 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 12306 N->getOperand(0).hasOneUse() && 12307 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 12308 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12309 N->getValueType(0) == MVT::i64))) { 12310 SDValue Load = N->getOperand(0); 12311 LoadSDNode *LD = cast<LoadSDNode>(Load); 12312 // Create the byte-swapping load. 12313 SDValue Ops[] = { 12314 LD->getChain(), // Chain 12315 LD->getBasePtr(), // Ptr 12316 DAG.getValueType(N->getValueType(0)) // VT 12317 }; 12318 SDValue BSLoad = 12319 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 12320 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 12321 MVT::i64 : MVT::i32, MVT::Other), 12322 Ops, LD->getMemoryVT(), LD->getMemOperand()); 12323 12324 // If this is an i16 load, insert the truncate. 12325 SDValue ResVal = BSLoad; 12326 if (N->getValueType(0) == MVT::i16) 12327 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 12328 12329 // First, combine the bswap away. This makes the value produced by the 12330 // load dead. 12331 DCI.CombineTo(N, ResVal); 12332 12333 // Next, combine the load away, we give it a bogus result value but a real 12334 // chain result. The result value is dead because the bswap is dead. 12335 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 12336 12337 // Return N so it doesn't get rechecked! 12338 return SDValue(N, 0); 12339 } 12340 break; 12341 case PPCISD::VCMP: 12342 // If a VCMPo node already exists with exactly the same operands as this 12343 // node, use its result instead of this node (VCMPo computes both a CR6 and 12344 // a normal output). 12345 // 12346 if (!N->getOperand(0).hasOneUse() && 12347 !N->getOperand(1).hasOneUse() && 12348 !N->getOperand(2).hasOneUse()) { 12349 12350 // Scan all of the users of the LHS, looking for VCMPo's that match. 12351 SDNode *VCMPoNode = nullptr; 12352 12353 SDNode *LHSN = N->getOperand(0).getNode(); 12354 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 12355 UI != E; ++UI) 12356 if (UI->getOpcode() == PPCISD::VCMPo && 12357 UI->getOperand(1) == N->getOperand(1) && 12358 UI->getOperand(2) == N->getOperand(2) && 12359 UI->getOperand(0) == N->getOperand(0)) { 12360 VCMPoNode = *UI; 12361 break; 12362 } 12363 12364 // If there is no VCMPo node, or if the flag value has a single use, don't 12365 // transform this. 12366 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 12367 break; 12368 12369 // Look at the (necessarily single) use of the flag value. If it has a 12370 // chain, this transformation is more complex. Note that multiple things 12371 // could use the value result, which we should ignore. 12372 SDNode *FlagUser = nullptr; 12373 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 12374 FlagUser == nullptr; ++UI) { 12375 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 12376 SDNode *User = *UI; 12377 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 12378 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 12379 FlagUser = User; 12380 break; 12381 } 12382 } 12383 } 12384 12385 // If the user is a MFOCRF instruction, we know this is safe. 12386 // Otherwise we give up for right now. 12387 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 12388 return SDValue(VCMPoNode, 0); 12389 } 12390 break; 12391 case ISD::BRCOND: { 12392 SDValue Cond = N->getOperand(1); 12393 SDValue Target = N->getOperand(2); 12394 12395 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12396 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 12397 Intrinsic::ppc_is_decremented_ctr_nonzero) { 12398 12399 // We now need to make the intrinsic dead (it cannot be instruction 12400 // selected). 12401 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 12402 assert(Cond.getNode()->hasOneUse() && 12403 "Counter decrement has more than one use"); 12404 12405 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 12406 N->getOperand(0), Target); 12407 } 12408 } 12409 break; 12410 case ISD::BR_CC: { 12411 // If this is a branch on an altivec predicate comparison, lower this so 12412 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 12413 // lowering is done pre-legalize, because the legalizer lowers the predicate 12414 // compare down to code that is difficult to reassemble. 12415 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 12416 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 12417 12418 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 12419 // value. If so, pass-through the AND to get to the intrinsic. 12420 if (LHS.getOpcode() == ISD::AND && 12421 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 12422 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 12423 Intrinsic::ppc_is_decremented_ctr_nonzero && 12424 isa<ConstantSDNode>(LHS.getOperand(1)) && 12425 !isNullConstant(LHS.getOperand(1))) 12426 LHS = LHS.getOperand(0); 12427 12428 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12429 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 12430 Intrinsic::ppc_is_decremented_ctr_nonzero && 12431 isa<ConstantSDNode>(RHS)) { 12432 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 12433 "Counter decrement comparison is not EQ or NE"); 12434 12435 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12436 bool isBDNZ = (CC == ISD::SETEQ && Val) || 12437 (CC == ISD::SETNE && !Val); 12438 12439 // We now need to make the intrinsic dead (it cannot be instruction 12440 // selected). 12441 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 12442 assert(LHS.getNode()->hasOneUse() && 12443 "Counter decrement has more than one use"); 12444 12445 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 12446 N->getOperand(0), N->getOperand(4)); 12447 } 12448 12449 int CompareOpc; 12450 bool isDot; 12451 12452 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12453 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 12454 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 12455 assert(isDot && "Can't compare against a vector result!"); 12456 12457 // If this is a comparison against something other than 0/1, then we know 12458 // that the condition is never/always true. 12459 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12460 if (Val != 0 && Val != 1) { 12461 if (CC == ISD::SETEQ) // Cond never true, remove branch. 12462 return N->getOperand(0); 12463 // Always !=, turn it into an unconditional branch. 12464 return DAG.getNode(ISD::BR, dl, MVT::Other, 12465 N->getOperand(0), N->getOperand(4)); 12466 } 12467 12468 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 12469 12470 // Create the PPCISD altivec 'dot' comparison node. 12471 SDValue Ops[] = { 12472 LHS.getOperand(2), // LHS of compare 12473 LHS.getOperand(3), // RHS of compare 12474 DAG.getConstant(CompareOpc, dl, MVT::i32) 12475 }; 12476 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 12477 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 12478 12479 // Unpack the result based on how the target uses it. 12480 PPC::Predicate CompOpc; 12481 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 12482 default: // Can't happen, don't crash on invalid number though. 12483 case 0: // Branch on the value of the EQ bit of CR6. 12484 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 12485 break; 12486 case 1: // Branch on the inverted value of the EQ bit of CR6. 12487 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 12488 break; 12489 case 2: // Branch on the value of the LT bit of CR6. 12490 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 12491 break; 12492 case 3: // Branch on the inverted value of the LT bit of CR6. 12493 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 12494 break; 12495 } 12496 12497 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 12498 DAG.getConstant(CompOpc, dl, MVT::i32), 12499 DAG.getRegister(PPC::CR6, MVT::i32), 12500 N->getOperand(4), CompNode.getValue(1)); 12501 } 12502 break; 12503 } 12504 case ISD::BUILD_VECTOR: 12505 return DAGCombineBuildVector(N, DCI); 12506 } 12507 12508 return SDValue(); 12509 } 12510 12511 SDValue 12512 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12513 SelectionDAG &DAG, 12514 std::vector<SDNode *> *Created) const { 12515 // fold (sdiv X, pow2) 12516 EVT VT = N->getValueType(0); 12517 if (VT == MVT::i64 && !Subtarget.isPPC64()) 12518 return SDValue(); 12519 if ((VT != MVT::i32 && VT != MVT::i64) || 12520 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 12521 return SDValue(); 12522 12523 SDLoc DL(N); 12524 SDValue N0 = N->getOperand(0); 12525 12526 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12527 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12528 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12529 12530 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12531 if (Created) 12532 Created->push_back(Op.getNode()); 12533 12534 if (IsNegPow2) { 12535 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12536 if (Created) 12537 Created->push_back(Op.getNode()); 12538 } 12539 12540 return Op; 12541 } 12542 12543 //===----------------------------------------------------------------------===// 12544 // Inline Assembly Support 12545 //===----------------------------------------------------------------------===// 12546 12547 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12548 KnownBits &Known, 12549 const APInt &DemandedElts, 12550 const SelectionDAG &DAG, 12551 unsigned Depth) const { 12552 Known.resetAll(); 12553 switch (Op.getOpcode()) { 12554 default: break; 12555 case PPCISD::LBRX: { 12556 // lhbrx is known to have the top bits cleared out. 12557 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12558 Known.Zero = 0xFFFF0000; 12559 break; 12560 } 12561 case ISD::INTRINSIC_WO_CHAIN: { 12562 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12563 default: break; 12564 case Intrinsic::ppc_altivec_vcmpbfp_p: 12565 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12566 case Intrinsic::ppc_altivec_vcmpequb_p: 12567 case Intrinsic::ppc_altivec_vcmpequh_p: 12568 case Intrinsic::ppc_altivec_vcmpequw_p: 12569 case Intrinsic::ppc_altivec_vcmpequd_p: 12570 case Intrinsic::ppc_altivec_vcmpgefp_p: 12571 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12572 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12573 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12574 case Intrinsic::ppc_altivec_vcmpgtsw_p: 12575 case Intrinsic::ppc_altivec_vcmpgtsd_p: 12576 case Intrinsic::ppc_altivec_vcmpgtub_p: 12577 case Intrinsic::ppc_altivec_vcmpgtuh_p: 12578 case Intrinsic::ppc_altivec_vcmpgtuw_p: 12579 case Intrinsic::ppc_altivec_vcmpgtud_p: 12580 Known.Zero = ~1U; // All bits but the low one are known to be zero. 12581 break; 12582 } 12583 } 12584 } 12585 } 12586 12587 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12588 switch (Subtarget.getDarwinDirective()) { 12589 default: break; 12590 case PPC::DIR_970: 12591 case PPC::DIR_PWR4: 12592 case PPC::DIR_PWR5: 12593 case PPC::DIR_PWR5X: 12594 case PPC::DIR_PWR6: 12595 case PPC::DIR_PWR6X: 12596 case PPC::DIR_PWR7: 12597 case PPC::DIR_PWR8: 12598 case PPC::DIR_PWR9: { 12599 if (!ML) 12600 break; 12601 12602 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 12603 12604 // For small loops (between 5 and 8 instructions), align to a 32-byte 12605 // boundary so that the entire loop fits in one instruction-cache line. 12606 uint64_t LoopSize = 0; 12607 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 12608 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 12609 LoopSize += TII->getInstSizeInBytes(*J); 12610 if (LoopSize > 32) 12611 break; 12612 } 12613 12614 if (LoopSize > 16 && LoopSize <= 32) 12615 return 5; 12616 12617 break; 12618 } 12619 } 12620 12621 return TargetLowering::getPrefLoopAlignment(ML); 12622 } 12623 12624 /// getConstraintType - Given a constraint, return the type of 12625 /// constraint it is for this target. 12626 PPCTargetLowering::ConstraintType 12627 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 12628 if (Constraint.size() == 1) { 12629 switch (Constraint[0]) { 12630 default: break; 12631 case 'b': 12632 case 'r': 12633 case 'f': 12634 case 'd': 12635 case 'v': 12636 case 'y': 12637 return C_RegisterClass; 12638 case 'Z': 12639 // FIXME: While Z does indicate a memory constraint, it specifically 12640 // indicates an r+r address (used in conjunction with the 'y' modifier 12641 // in the replacement string). Currently, we're forcing the base 12642 // register to be r0 in the asm printer (which is interpreted as zero) 12643 // and forming the complete address in the second register. This is 12644 // suboptimal. 12645 return C_Memory; 12646 } 12647 } else if (Constraint == "wc") { // individual CR bits. 12648 return C_RegisterClass; 12649 } else if (Constraint == "wa" || Constraint == "wd" || 12650 Constraint == "wf" || Constraint == "ws") { 12651 return C_RegisterClass; // VSX registers. 12652 } 12653 return TargetLowering::getConstraintType(Constraint); 12654 } 12655 12656 /// Examine constraint type and operand type and determine a weight value. 12657 /// This object must already have been set up with the operand type 12658 /// and the current alternative constraint selected. 12659 TargetLowering::ConstraintWeight 12660 PPCTargetLowering::getSingleConstraintMatchWeight( 12661 AsmOperandInfo &info, const char *constraint) const { 12662 ConstraintWeight weight = CW_Invalid; 12663 Value *CallOperandVal = info.CallOperandVal; 12664 // If we don't have a value, we can't do a match, 12665 // but allow it at the lowest weight. 12666 if (!CallOperandVal) 12667 return CW_Default; 12668 Type *type = CallOperandVal->getType(); 12669 12670 // Look at the constraint type. 12671 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 12672 return CW_Register; // an individual CR bit. 12673 else if ((StringRef(constraint) == "wa" || 12674 StringRef(constraint) == "wd" || 12675 StringRef(constraint) == "wf") && 12676 type->isVectorTy()) 12677 return CW_Register; 12678 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 12679 return CW_Register; 12680 12681 switch (*constraint) { 12682 default: 12683 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12684 break; 12685 case 'b': 12686 if (type->isIntegerTy()) 12687 weight = CW_Register; 12688 break; 12689 case 'f': 12690 if (type->isFloatTy()) 12691 weight = CW_Register; 12692 break; 12693 case 'd': 12694 if (type->isDoubleTy()) 12695 weight = CW_Register; 12696 break; 12697 case 'v': 12698 if (type->isVectorTy()) 12699 weight = CW_Register; 12700 break; 12701 case 'y': 12702 weight = CW_Register; 12703 break; 12704 case 'Z': 12705 weight = CW_Memory; 12706 break; 12707 } 12708 return weight; 12709 } 12710 12711 std::pair<unsigned, const TargetRegisterClass *> 12712 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 12713 StringRef Constraint, 12714 MVT VT) const { 12715 if (Constraint.size() == 1) { 12716 // GCC RS6000 Constraint Letters 12717 switch (Constraint[0]) { 12718 case 'b': // R1-R31 12719 if (VT == MVT::i64 && Subtarget.isPPC64()) 12720 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 12721 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 12722 case 'r': // R0-R31 12723 if (VT == MVT::i64 && Subtarget.isPPC64()) 12724 return std::make_pair(0U, &PPC::G8RCRegClass); 12725 return std::make_pair(0U, &PPC::GPRCRegClass); 12726 // 'd' and 'f' constraints are both defined to be "the floating point 12727 // registers", where one is for 32-bit and the other for 64-bit. We don't 12728 // really care overly much here so just give them all the same reg classes. 12729 case 'd': 12730 case 'f': 12731 if (VT == MVT::f32 || VT == MVT::i32) 12732 return std::make_pair(0U, &PPC::F4RCRegClass); 12733 if (VT == MVT::f64 || VT == MVT::i64) 12734 return std::make_pair(0U, &PPC::F8RCRegClass); 12735 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12736 return std::make_pair(0U, &PPC::QFRCRegClass); 12737 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12738 return std::make_pair(0U, &PPC::QSRCRegClass); 12739 break; 12740 case 'v': 12741 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 12742 return std::make_pair(0U, &PPC::QFRCRegClass); 12743 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 12744 return std::make_pair(0U, &PPC::QSRCRegClass); 12745 if (Subtarget.hasAltivec()) 12746 return std::make_pair(0U, &PPC::VRRCRegClass); 12747 case 'y': // crrc 12748 return std::make_pair(0U, &PPC::CRRCRegClass); 12749 } 12750 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 12751 // An individual CR bit. 12752 return std::make_pair(0U, &PPC::CRBITRCRegClass); 12753 } else if ((Constraint == "wa" || Constraint == "wd" || 12754 Constraint == "wf") && Subtarget.hasVSX()) { 12755 return std::make_pair(0U, &PPC::VSRCRegClass); 12756 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 12757 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 12758 return std::make_pair(0U, &PPC::VSSRCRegClass); 12759 else 12760 return std::make_pair(0U, &PPC::VSFRCRegClass); 12761 } 12762 12763 std::pair<unsigned, const TargetRegisterClass *> R = 12764 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12765 12766 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 12767 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 12768 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 12769 // register. 12770 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 12771 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 12772 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 12773 PPC::GPRCRegClass.contains(R.first)) 12774 return std::make_pair(TRI->getMatchingSuperReg(R.first, 12775 PPC::sub_32, &PPC::G8RCRegClass), 12776 &PPC::G8RCRegClass); 12777 12778 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 12779 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 12780 R.first = PPC::CR0; 12781 R.second = &PPC::CRRCRegClass; 12782 } 12783 12784 return R; 12785 } 12786 12787 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12788 /// vector. If it is invalid, don't add anything to Ops. 12789 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12790 std::string &Constraint, 12791 std::vector<SDValue>&Ops, 12792 SelectionDAG &DAG) const { 12793 SDValue Result; 12794 12795 // Only support length 1 constraints. 12796 if (Constraint.length() > 1) return; 12797 12798 char Letter = Constraint[0]; 12799 switch (Letter) { 12800 default: break; 12801 case 'I': 12802 case 'J': 12803 case 'K': 12804 case 'L': 12805 case 'M': 12806 case 'N': 12807 case 'O': 12808 case 'P': { 12809 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 12810 if (!CST) return; // Must be an immediate to match. 12811 SDLoc dl(Op); 12812 int64_t Value = CST->getSExtValue(); 12813 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 12814 // numbers are printed as such. 12815 switch (Letter) { 12816 default: llvm_unreachable("Unknown constraint letter!"); 12817 case 'I': // "I" is a signed 16-bit constant. 12818 if (isInt<16>(Value)) 12819 Result = DAG.getTargetConstant(Value, dl, TCVT); 12820 break; 12821 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 12822 if (isShiftedUInt<16, 16>(Value)) 12823 Result = DAG.getTargetConstant(Value, dl, TCVT); 12824 break; 12825 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 12826 if (isShiftedInt<16, 16>(Value)) 12827 Result = DAG.getTargetConstant(Value, dl, TCVT); 12828 break; 12829 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 12830 if (isUInt<16>(Value)) 12831 Result = DAG.getTargetConstant(Value, dl, TCVT); 12832 break; 12833 case 'M': // "M" is a constant that is greater than 31. 12834 if (Value > 31) 12835 Result = DAG.getTargetConstant(Value, dl, TCVT); 12836 break; 12837 case 'N': // "N" is a positive constant that is an exact power of two. 12838 if (Value > 0 && isPowerOf2_64(Value)) 12839 Result = DAG.getTargetConstant(Value, dl, TCVT); 12840 break; 12841 case 'O': // "O" is the constant zero. 12842 if (Value == 0) 12843 Result = DAG.getTargetConstant(Value, dl, TCVT); 12844 break; 12845 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 12846 if (isInt<16>(-Value)) 12847 Result = DAG.getTargetConstant(Value, dl, TCVT); 12848 break; 12849 } 12850 break; 12851 } 12852 } 12853 12854 if (Result.getNode()) { 12855 Ops.push_back(Result); 12856 return; 12857 } 12858 12859 // Handle standard constraint letters. 12860 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12861 } 12862 12863 // isLegalAddressingMode - Return true if the addressing mode represented 12864 // by AM is legal for this target, for a load/store of the specified type. 12865 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12866 const AddrMode &AM, Type *Ty, 12867 unsigned AS, Instruction *I) const { 12868 // PPC does not allow r+i addressing modes for vectors! 12869 if (Ty->isVectorTy() && AM.BaseOffs != 0) 12870 return false; 12871 12872 // PPC allows a sign-extended 16-bit immediate field. 12873 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 12874 return false; 12875 12876 // No global is ever allowed as a base. 12877 if (AM.BaseGV) 12878 return false; 12879 12880 // PPC only support r+r, 12881 switch (AM.Scale) { 12882 case 0: // "r+i" or just "i", depending on HasBaseReg. 12883 break; 12884 case 1: 12885 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 12886 return false; 12887 // Otherwise we have r+r or r+i. 12888 break; 12889 case 2: 12890 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 12891 return false; 12892 // Allow 2*r as r+r. 12893 break; 12894 default: 12895 // No other scales are supported. 12896 return false; 12897 } 12898 12899 return true; 12900 } 12901 12902 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 12903 SelectionDAG &DAG) const { 12904 MachineFunction &MF = DAG.getMachineFunction(); 12905 MachineFrameInfo &MFI = MF.getFrameInfo(); 12906 MFI.setReturnAddressIsTaken(true); 12907 12908 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 12909 return SDValue(); 12910 12911 SDLoc dl(Op); 12912 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12913 12914 // Make sure the function does not optimize away the store of the RA to 12915 // the stack. 12916 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 12917 FuncInfo->setLRStoreRequired(); 12918 bool isPPC64 = Subtarget.isPPC64(); 12919 auto PtrVT = getPointerTy(MF.getDataLayout()); 12920 12921 if (Depth > 0) { 12922 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 12923 SDValue Offset = 12924 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 12925 isPPC64 ? MVT::i64 : MVT::i32); 12926 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 12927 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 12928 MachinePointerInfo()); 12929 } 12930 12931 // Just load the return address off the stack. 12932 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 12933 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 12934 MachinePointerInfo()); 12935 } 12936 12937 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 12938 SelectionDAG &DAG) const { 12939 SDLoc dl(Op); 12940 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12941 12942 MachineFunction &MF = DAG.getMachineFunction(); 12943 MachineFrameInfo &MFI = MF.getFrameInfo(); 12944 MFI.setFrameAddressIsTaken(true); 12945 12946 EVT PtrVT = getPointerTy(MF.getDataLayout()); 12947 bool isPPC64 = PtrVT == MVT::i64; 12948 12949 // Naked functions never have a frame pointer, and so we use r1. For all 12950 // other functions, this decision must be delayed until during PEI. 12951 unsigned FrameReg; 12952 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 12953 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 12954 else 12955 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 12956 12957 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 12958 PtrVT); 12959 while (Depth--) 12960 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 12961 FrameAddr, MachinePointerInfo()); 12962 return FrameAddr; 12963 } 12964 12965 // FIXME? Maybe this could be a TableGen attribute on some registers and 12966 // this table could be generated automatically from RegInfo. 12967 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 12968 SelectionDAG &DAG) const { 12969 bool isPPC64 = Subtarget.isPPC64(); 12970 bool isDarwinABI = Subtarget.isDarwinABI(); 12971 12972 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 12973 (!isPPC64 && VT != MVT::i32)) 12974 report_fatal_error("Invalid register global variable type"); 12975 12976 bool is64Bit = isPPC64 && VT == MVT::i64; 12977 unsigned Reg = StringSwitch<unsigned>(RegName) 12978 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 12979 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 12980 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 12981 (is64Bit ? PPC::X13 : PPC::R13)) 12982 .Default(0); 12983 12984 if (Reg) 12985 return Reg; 12986 report_fatal_error("Invalid register name global variable"); 12987 } 12988 12989 bool 12990 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12991 // The PowerPC target isn't yet aware of offsets. 12992 return false; 12993 } 12994 12995 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12996 const CallInst &I, 12997 unsigned Intrinsic) const { 12998 switch (Intrinsic) { 12999 case Intrinsic::ppc_qpx_qvlfd: 13000 case Intrinsic::ppc_qpx_qvlfs: 13001 case Intrinsic::ppc_qpx_qvlfcd: 13002 case Intrinsic::ppc_qpx_qvlfcs: 13003 case Intrinsic::ppc_qpx_qvlfiwa: 13004 case Intrinsic::ppc_qpx_qvlfiwz: 13005 case Intrinsic::ppc_altivec_lvx: 13006 case Intrinsic::ppc_altivec_lvxl: 13007 case Intrinsic::ppc_altivec_lvebx: 13008 case Intrinsic::ppc_altivec_lvehx: 13009 case Intrinsic::ppc_altivec_lvewx: 13010 case Intrinsic::ppc_vsx_lxvd2x: 13011 case Intrinsic::ppc_vsx_lxvw4x: { 13012 EVT VT; 13013 switch (Intrinsic) { 13014 case Intrinsic::ppc_altivec_lvebx: 13015 VT = MVT::i8; 13016 break; 13017 case Intrinsic::ppc_altivec_lvehx: 13018 VT = MVT::i16; 13019 break; 13020 case Intrinsic::ppc_altivec_lvewx: 13021 VT = MVT::i32; 13022 break; 13023 case Intrinsic::ppc_vsx_lxvd2x: 13024 VT = MVT::v2f64; 13025 break; 13026 case Intrinsic::ppc_qpx_qvlfd: 13027 VT = MVT::v4f64; 13028 break; 13029 case Intrinsic::ppc_qpx_qvlfs: 13030 VT = MVT::v4f32; 13031 break; 13032 case Intrinsic::ppc_qpx_qvlfcd: 13033 VT = MVT::v2f64; 13034 break; 13035 case Intrinsic::ppc_qpx_qvlfcs: 13036 VT = MVT::v2f32; 13037 break; 13038 default: 13039 VT = MVT::v4i32; 13040 break; 13041 } 13042 13043 Info.opc = ISD::INTRINSIC_W_CHAIN; 13044 Info.memVT = VT; 13045 Info.ptrVal = I.getArgOperand(0); 13046 Info.offset = -VT.getStoreSize()+1; 13047 Info.size = 2*VT.getStoreSize()-1; 13048 Info.align = 1; 13049 Info.vol = false; 13050 Info.readMem = true; 13051 Info.writeMem = false; 13052 return true; 13053 } 13054 case Intrinsic::ppc_qpx_qvlfda: 13055 case Intrinsic::ppc_qpx_qvlfsa: 13056 case Intrinsic::ppc_qpx_qvlfcda: 13057 case Intrinsic::ppc_qpx_qvlfcsa: 13058 case Intrinsic::ppc_qpx_qvlfiwaa: 13059 case Intrinsic::ppc_qpx_qvlfiwza: { 13060 EVT VT; 13061 switch (Intrinsic) { 13062 case Intrinsic::ppc_qpx_qvlfda: 13063 VT = MVT::v4f64; 13064 break; 13065 case Intrinsic::ppc_qpx_qvlfsa: 13066 VT = MVT::v4f32; 13067 break; 13068 case Intrinsic::ppc_qpx_qvlfcda: 13069 VT = MVT::v2f64; 13070 break; 13071 case Intrinsic::ppc_qpx_qvlfcsa: 13072 VT = MVT::v2f32; 13073 break; 13074 default: 13075 VT = MVT::v4i32; 13076 break; 13077 } 13078 13079 Info.opc = ISD::INTRINSIC_W_CHAIN; 13080 Info.memVT = VT; 13081 Info.ptrVal = I.getArgOperand(0); 13082 Info.offset = 0; 13083 Info.size = VT.getStoreSize(); 13084 Info.align = 1; 13085 Info.vol = false; 13086 Info.readMem = true; 13087 Info.writeMem = false; 13088 return true; 13089 } 13090 case Intrinsic::ppc_qpx_qvstfd: 13091 case Intrinsic::ppc_qpx_qvstfs: 13092 case Intrinsic::ppc_qpx_qvstfcd: 13093 case Intrinsic::ppc_qpx_qvstfcs: 13094 case Intrinsic::ppc_qpx_qvstfiw: 13095 case Intrinsic::ppc_altivec_stvx: 13096 case Intrinsic::ppc_altivec_stvxl: 13097 case Intrinsic::ppc_altivec_stvebx: 13098 case Intrinsic::ppc_altivec_stvehx: 13099 case Intrinsic::ppc_altivec_stvewx: 13100 case Intrinsic::ppc_vsx_stxvd2x: 13101 case Intrinsic::ppc_vsx_stxvw4x: { 13102 EVT VT; 13103 switch (Intrinsic) { 13104 case Intrinsic::ppc_altivec_stvebx: 13105 VT = MVT::i8; 13106 break; 13107 case Intrinsic::ppc_altivec_stvehx: 13108 VT = MVT::i16; 13109 break; 13110 case Intrinsic::ppc_altivec_stvewx: 13111 VT = MVT::i32; 13112 break; 13113 case Intrinsic::ppc_vsx_stxvd2x: 13114 VT = MVT::v2f64; 13115 break; 13116 case Intrinsic::ppc_qpx_qvstfd: 13117 VT = MVT::v4f64; 13118 break; 13119 case Intrinsic::ppc_qpx_qvstfs: 13120 VT = MVT::v4f32; 13121 break; 13122 case Intrinsic::ppc_qpx_qvstfcd: 13123 VT = MVT::v2f64; 13124 break; 13125 case Intrinsic::ppc_qpx_qvstfcs: 13126 VT = MVT::v2f32; 13127 break; 13128 default: 13129 VT = MVT::v4i32; 13130 break; 13131 } 13132 13133 Info.opc = ISD::INTRINSIC_VOID; 13134 Info.memVT = VT; 13135 Info.ptrVal = I.getArgOperand(1); 13136 Info.offset = -VT.getStoreSize()+1; 13137 Info.size = 2*VT.getStoreSize()-1; 13138 Info.align = 1; 13139 Info.vol = false; 13140 Info.readMem = false; 13141 Info.writeMem = true; 13142 return true; 13143 } 13144 case Intrinsic::ppc_qpx_qvstfda: 13145 case Intrinsic::ppc_qpx_qvstfsa: 13146 case Intrinsic::ppc_qpx_qvstfcda: 13147 case Intrinsic::ppc_qpx_qvstfcsa: 13148 case Intrinsic::ppc_qpx_qvstfiwa: { 13149 EVT VT; 13150 switch (Intrinsic) { 13151 case Intrinsic::ppc_qpx_qvstfda: 13152 VT = MVT::v4f64; 13153 break; 13154 case Intrinsic::ppc_qpx_qvstfsa: 13155 VT = MVT::v4f32; 13156 break; 13157 case Intrinsic::ppc_qpx_qvstfcda: 13158 VT = MVT::v2f64; 13159 break; 13160 case Intrinsic::ppc_qpx_qvstfcsa: 13161 VT = MVT::v2f32; 13162 break; 13163 default: 13164 VT = MVT::v4i32; 13165 break; 13166 } 13167 13168 Info.opc = ISD::INTRINSIC_VOID; 13169 Info.memVT = VT; 13170 Info.ptrVal = I.getArgOperand(1); 13171 Info.offset = 0; 13172 Info.size = VT.getStoreSize(); 13173 Info.align = 1; 13174 Info.vol = false; 13175 Info.readMem = false; 13176 Info.writeMem = true; 13177 return true; 13178 } 13179 default: 13180 break; 13181 } 13182 13183 return false; 13184 } 13185 13186 /// getOptimalMemOpType - Returns the target specific optimal type for load 13187 /// and store operations as a result of memset, memcpy, and memmove 13188 /// lowering. If DstAlign is zero that means it's safe to destination 13189 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13190 /// means there isn't a need to check it against alignment requirement, 13191 /// probably because the source does not need to be loaded. If 'IsMemset' is 13192 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13193 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13194 /// source is constant so it does not need to be loaded. 13195 /// It returns EVT::Other if the type should be determined using generic 13196 /// target-independent logic. 13197 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13198 unsigned DstAlign, unsigned SrcAlign, 13199 bool IsMemset, bool ZeroMemset, 13200 bool MemcpyStrSrc, 13201 MachineFunction &MF) const { 13202 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13203 const Function *F = MF.getFunction(); 13204 // When expanding a memset, require at least two QPX instructions to cover 13205 // the cost of loading the value to be stored from the constant pool. 13206 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13207 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13208 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 13209 return MVT::v4f64; 13210 } 13211 13212 // We should use Altivec/VSX loads and stores when available. For unaligned 13213 // addresses, unaligned VSX loads are only fast starting with the P8. 13214 if (Subtarget.hasAltivec() && Size >= 16 && 13215 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13216 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13217 return MVT::v4i32; 13218 } 13219 13220 if (Subtarget.isPPC64()) { 13221 return MVT::i64; 13222 } 13223 13224 return MVT::i32; 13225 } 13226 13227 /// \brief Returns true if it is beneficial to convert a load of a constant 13228 /// to just the constant itself. 13229 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13230 Type *Ty) const { 13231 assert(Ty->isIntegerTy()); 13232 13233 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13234 return !(BitSize == 0 || BitSize > 64); 13235 } 13236 13237 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13238 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13239 return false; 13240 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13241 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13242 return NumBits1 == 64 && NumBits2 == 32; 13243 } 13244 13245 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13246 if (!VT1.isInteger() || !VT2.isInteger()) 13247 return false; 13248 unsigned NumBits1 = VT1.getSizeInBits(); 13249 unsigned NumBits2 = VT2.getSizeInBits(); 13250 return NumBits1 == 64 && NumBits2 == 32; 13251 } 13252 13253 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13254 // Generally speaking, zexts are not free, but they are free when they can be 13255 // folded with other operations. 13256 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13257 EVT MemVT = LD->getMemoryVT(); 13258 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13259 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13260 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13261 LD->getExtensionType() == ISD::ZEXTLOAD)) 13262 return true; 13263 } 13264 13265 // FIXME: Add other cases... 13266 // - 32-bit shifts with a zext to i64 13267 // - zext after ctlz, bswap, etc. 13268 // - zext after and by a constant mask 13269 13270 return TargetLowering::isZExtFree(Val, VT2); 13271 } 13272 13273 bool PPCTargetLowering::isFPExtFree(EVT VT) const { 13274 assert(VT.isFloatingPoint()); 13275 return true; 13276 } 13277 13278 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13279 return isInt<16>(Imm) || isUInt<16>(Imm); 13280 } 13281 13282 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13283 return isInt<16>(Imm) || isUInt<16>(Imm); 13284 } 13285 13286 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13287 unsigned, 13288 unsigned, 13289 bool *Fast) const { 13290 if (DisablePPCUnaligned) 13291 return false; 13292 13293 // PowerPC supports unaligned memory access for simple non-vector types. 13294 // Although accessing unaligned addresses is not as efficient as accessing 13295 // aligned addresses, it is generally more efficient than manual expansion, 13296 // and generally only traps for software emulation when crossing page 13297 // boundaries. 13298 13299 if (!VT.isSimple()) 13300 return false; 13301 13302 if (VT.getSimpleVT().isVector()) { 13303 if (Subtarget.hasVSX()) { 13304 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 13305 VT != MVT::v4f32 && VT != MVT::v4i32) 13306 return false; 13307 } else { 13308 return false; 13309 } 13310 } 13311 13312 if (VT == MVT::ppcf128) 13313 return false; 13314 13315 if (Fast) 13316 *Fast = true; 13317 13318 return true; 13319 } 13320 13321 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13322 VT = VT.getScalarType(); 13323 13324 if (!VT.isSimple()) 13325 return false; 13326 13327 switch (VT.getSimpleVT().SimpleTy) { 13328 case MVT::f32: 13329 case MVT::f64: 13330 return true; 13331 default: 13332 break; 13333 } 13334 13335 return false; 13336 } 13337 13338 const MCPhysReg * 13339 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 13340 // LR is a callee-save register, but we must treat it as clobbered by any call 13341 // site. Hence we include LR in the scratch registers, which are in turn added 13342 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 13343 // to CTR, which is used by any indirect call. 13344 static const MCPhysReg ScratchRegs[] = { 13345 PPC::X12, PPC::LR8, PPC::CTR8, 0 13346 }; 13347 13348 return ScratchRegs; 13349 } 13350 13351 unsigned PPCTargetLowering::getExceptionPointerRegister( 13352 const Constant *PersonalityFn) const { 13353 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 13354 } 13355 13356 unsigned PPCTargetLowering::getExceptionSelectorRegister( 13357 const Constant *PersonalityFn) const { 13358 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 13359 } 13360 13361 bool 13362 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 13363 EVT VT , unsigned DefinedValues) const { 13364 if (VT == MVT::v2i64) 13365 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 13366 13367 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 13368 return true; 13369 13370 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 13371 } 13372 13373 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 13374 if (DisableILPPref || Subtarget.enableMachineScheduler()) 13375 return TargetLowering::getSchedulingPreference(N); 13376 13377 return Sched::ILP; 13378 } 13379 13380 // Create a fast isel object. 13381 FastISel * 13382 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 13383 const TargetLibraryInfo *LibInfo) const { 13384 return PPC::createFastISel(FuncInfo, LibInfo); 13385 } 13386 13387 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13388 if (Subtarget.isDarwinABI()) return; 13389 if (!Subtarget.isPPC64()) return; 13390 13391 // Update IsSplitCSR in PPCFunctionInfo 13392 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 13393 PFI->setIsSplitCSR(true); 13394 } 13395 13396 void PPCTargetLowering::insertCopiesSplitCSR( 13397 MachineBasicBlock *Entry, 13398 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13399 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13400 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13401 if (!IStart) 13402 return; 13403 13404 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 13405 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13406 MachineBasicBlock::iterator MBBI = Entry->begin(); 13407 for (const MCPhysReg *I = IStart; *I; ++I) { 13408 const TargetRegisterClass *RC = nullptr; 13409 if (PPC::G8RCRegClass.contains(*I)) 13410 RC = &PPC::G8RCRegClass; 13411 else if (PPC::F8RCRegClass.contains(*I)) 13412 RC = &PPC::F8RCRegClass; 13413 else if (PPC::CRRCRegClass.contains(*I)) 13414 RC = &PPC::CRRCRegClass; 13415 else if (PPC::VRRCRegClass.contains(*I)) 13416 RC = &PPC::VRRCRegClass; 13417 else 13418 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13419 13420 unsigned NewVR = MRI->createVirtualRegister(RC); 13421 // Create copy from CSR to a virtual register. 13422 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13423 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13424 // nounwind. If we want to generalize this later, we may need to emit 13425 // CFI pseudo-instructions. 13426 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13427 Attribute::NoUnwind) && 13428 "Function should be nounwind in insertCopiesSplitCSR!"); 13429 Entry->addLiveIn(*I); 13430 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13431 .addReg(*I); 13432 13433 // Insert the copy-back instructions right before the terminator 13434 for (auto *Exit : Exits) 13435 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13436 TII->get(TargetOpcode::COPY), *I) 13437 .addReg(NewVR); 13438 } 13439 } 13440 13441 // Override to enable LOAD_STACK_GUARD lowering on Linux. 13442 bool PPCTargetLowering::useLoadStackGuardNode() const { 13443 if (!Subtarget.isTargetLinux()) 13444 return TargetLowering::useLoadStackGuardNode(); 13445 return true; 13446 } 13447 13448 // Override to disable global variable loading on Linux. 13449 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 13450 if (!Subtarget.isTargetLinux()) 13451 return TargetLowering::insertSSPDeclarations(M); 13452 } 13453 13454 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13455 if (!VT.isSimple() || !Subtarget.hasVSX()) 13456 return false; 13457 13458 switch(VT.getSimpleVT().SimpleTy) { 13459 default: 13460 // For FP types that are currently not supported by PPC backend, return 13461 // false. Examples: f16, f80. 13462 return false; 13463 case MVT::f32: 13464 case MVT::f64: 13465 case MVT::ppcf128: 13466 return Imm.isPosZero(); 13467 } 13468 } 13469 13470 // For vector shift operation op, fold 13471 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 13472 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 13473 SelectionDAG &DAG) { 13474 SDValue N0 = N->getOperand(0); 13475 SDValue N1 = N->getOperand(1); 13476 EVT VT = N0.getValueType(); 13477 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 13478 unsigned Opcode = N->getOpcode(); 13479 unsigned TargetOpcode; 13480 13481 switch (Opcode) { 13482 default: 13483 llvm_unreachable("Unexpected shift operation"); 13484 case ISD::SHL: 13485 TargetOpcode = PPCISD::SHL; 13486 break; 13487 case ISD::SRL: 13488 TargetOpcode = PPCISD::SRL; 13489 break; 13490 case ISD::SRA: 13491 TargetOpcode = PPCISD::SRA; 13492 break; 13493 } 13494 13495 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 13496 N1->getOpcode() == ISD::AND) 13497 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 13498 if (Mask->getZExtValue() == OpSizeInBits - 1) 13499 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 13500 13501 return SDValue(); 13502 } 13503 13504 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 13505 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13506 return Value; 13507 13508 return SDValue(); 13509 } 13510 13511 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 13512 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13513 return Value; 13514 13515 return SDValue(); 13516 } 13517 13518 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 13519 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13520 return Value; 13521 13522 return SDValue(); 13523 } 13524