1 //===-- VEISelLowering.cpp - VE DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the interfaces that VE uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "VEISelLowering.h" 15 #include "MCTargetDesc/VEMCExpr.h" 16 #include "VEMachineFunctionInfo.h" 17 #include "VERegisterInfo.h" 18 #include "VETargetMachine.h" 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/CodeGen/CallingConvLower.h" 21 #include "llvm/CodeGen/MachineFrameInfo.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineInstrBuilder.h" 24 #include "llvm/CodeGen/MachineModuleInfo.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/CodeGen/SelectionDAG.h" 27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/KnownBits.h" 33 using namespace llvm; 34 35 #define DEBUG_TYPE "ve-lower" 36 37 //===----------------------------------------------------------------------===// 38 // Calling Convention Implementation 39 //===----------------------------------------------------------------------===// 40 41 #include "VEGenCallingConv.inc" 42 43 bool VETargetLowering::CanLowerReturn( 44 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 45 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 46 CCAssignFn *RetCC = RetCC_VE; 47 SmallVector<CCValAssign, 16> RVLocs; 48 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 49 return CCInfo.CheckReturn(Outs, RetCC); 50 } 51 52 SDValue 53 VETargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 54 bool IsVarArg, 55 const SmallVectorImpl<ISD::OutputArg> &Outs, 56 const SmallVectorImpl<SDValue> &OutVals, 57 const SDLoc &DL, SelectionDAG &DAG) const { 58 // CCValAssign - represent the assignment of the return value to locations. 59 SmallVector<CCValAssign, 16> RVLocs; 60 61 // CCState - Info about the registers and stack slot. 62 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 63 *DAG.getContext()); 64 65 // Analyze return values. 66 CCInfo.AnalyzeReturn(Outs, RetCC_VE); 67 68 SDValue Flag; 69 SmallVector<SDValue, 4> RetOps(1, Chain); 70 71 // Copy the result values into the output registers. 72 for (unsigned i = 0; i != RVLocs.size(); ++i) { 73 CCValAssign &VA = RVLocs[i]; 74 assert(VA.isRegLoc() && "Can only return in registers!"); 75 SDValue OutVal = OutVals[i]; 76 77 // Integer return values must be sign or zero extended by the callee. 78 switch (VA.getLocInfo()) { 79 case CCValAssign::Full: 80 break; 81 case CCValAssign::SExt: 82 OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal); 83 break; 84 case CCValAssign::ZExt: 85 OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal); 86 break; 87 case CCValAssign::AExt: 88 OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal); 89 break; 90 case CCValAssign::BCvt: { 91 // Convert a float return value to i64 with padding. 92 // 63 31 0 93 // +------+------+ 94 // | float| 0 | 95 // +------+------+ 96 assert(VA.getLocVT() == MVT::i64); 97 assert(VA.getValVT() == MVT::f32); 98 SDValue Undef = SDValue( 99 DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0); 100 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 101 OutVal = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 102 MVT::i64, Undef, OutVal, Sub_f32), 103 0); 104 break; 105 } 106 default: 107 llvm_unreachable("Unknown loc info!"); 108 } 109 110 assert(!VA.needsCustom() && "Unexpected custom lowering"); 111 112 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag); 113 114 // Guarantee that all emitted copies are stuck together with flags. 115 Flag = Chain.getValue(1); 116 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 117 } 118 119 RetOps[0] = Chain; // Update chain. 120 121 // Add the flag if we have it. 122 if (Flag.getNode()) 123 RetOps.push_back(Flag); 124 125 return DAG.getNode(VEISD::RET_FLAG, DL, MVT::Other, RetOps); 126 } 127 128 SDValue VETargetLowering::LowerFormalArguments( 129 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 130 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 131 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 132 MachineFunction &MF = DAG.getMachineFunction(); 133 134 // Get the base offset of the incoming arguments stack space. 135 unsigned ArgsBaseOffset = 176; 136 // Get the size of the preserved arguments area 137 unsigned ArgsPreserved = 64; 138 139 // Analyze arguments according to CC_VE. 140 SmallVector<CCValAssign, 16> ArgLocs; 141 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 142 *DAG.getContext()); 143 // Allocate the preserved area first. 144 CCInfo.AllocateStack(ArgsPreserved, Align(8)); 145 // We already allocated the preserved area, so the stack offset computed 146 // by CC_VE would be correct now. 147 CCInfo.AnalyzeFormalArguments(Ins, CC_VE); 148 149 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 150 CCValAssign &VA = ArgLocs[i]; 151 if (VA.isRegLoc()) { 152 // This argument is passed in a register. 153 // All integer register arguments are promoted by the caller to i64. 154 155 // Create a virtual register for the promoted live-in value. 156 unsigned VReg = 157 MF.addLiveIn(VA.getLocReg(), getRegClassFor(VA.getLocVT())); 158 SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT()); 159 160 // Get the high bits for i32 struct elements. 161 if (VA.getValVT() == MVT::i32 && VA.needsCustom()) 162 Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg, 163 DAG.getConstant(32, DL, MVT::i32)); 164 165 // The caller promoted the argument, so insert an Assert?ext SDNode so we 166 // won't promote the value again in this function. 167 switch (VA.getLocInfo()) { 168 case CCValAssign::SExt: 169 Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg, 170 DAG.getValueType(VA.getValVT())); 171 break; 172 case CCValAssign::ZExt: 173 Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg, 174 DAG.getValueType(VA.getValVT())); 175 break; 176 case CCValAssign::BCvt: { 177 // Extract a float argument from i64 with padding. 178 // 63 31 0 179 // +------+------+ 180 // | float| 0 | 181 // +------+------+ 182 assert(VA.getLocVT() == MVT::i64); 183 assert(VA.getValVT() == MVT::f32); 184 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 185 Arg = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 186 MVT::f32, Arg, Sub_f32), 187 0); 188 break; 189 } 190 default: 191 break; 192 } 193 194 // Truncate the register down to the argument type. 195 if (VA.isExtInLoc()) 196 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 197 198 InVals.push_back(Arg); 199 continue; 200 } 201 202 // The registers are exhausted. This argument was passed on the stack. 203 assert(VA.isMemLoc()); 204 // The CC_VE_Full/Half functions compute stack offsets relative to the 205 // beginning of the arguments area at %fp+176. 206 unsigned Offset = VA.getLocMemOffset() + ArgsBaseOffset; 207 unsigned ValSize = VA.getValVT().getSizeInBits() / 8; 208 209 // Adjust offset for a float argument by adding 4 since the argument is 210 // stored in 8 bytes buffer with offset like below. LLVM generates 211 // 4 bytes load instruction, so need to adjust offset here. This 212 // adjustment is required in only LowerFormalArguments. In LowerCall, 213 // a float argument is converted to i64 first, and stored as 8 bytes 214 // data, which is required by ABI, so no need for adjustment. 215 // 0 4 216 // +------+------+ 217 // | empty| float| 218 // +------+------+ 219 if (VA.getValVT() == MVT::f32) 220 Offset += 4; 221 222 int FI = MF.getFrameInfo().CreateFixedObject(ValSize, Offset, true); 223 InVals.push_back( 224 DAG.getLoad(VA.getValVT(), DL, Chain, 225 DAG.getFrameIndex(FI, getPointerTy(MF.getDataLayout())), 226 MachinePointerInfo::getFixedStack(MF, FI))); 227 } 228 229 if (!IsVarArg) 230 return Chain; 231 232 // This function takes variable arguments, some of which may have been passed 233 // in registers %s0-%s8. 234 // 235 // The va_start intrinsic needs to know the offset to the first variable 236 // argument. 237 // TODO: need to calculate offset correctly once we support f128. 238 unsigned ArgOffset = ArgLocs.size() * 8; 239 VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>(); 240 // Skip the 176 bytes of register save area. 241 FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgsBaseOffset); 242 243 return Chain; 244 } 245 246 // FIXME? Maybe this could be a TableGen attribute on some registers and 247 // this table could be generated automatically from RegInfo. 248 Register VETargetLowering::getRegisterByName(const char *RegName, LLT VT, 249 const MachineFunction &MF) const { 250 Register Reg = StringSwitch<Register>(RegName) 251 .Case("sp", VE::SX11) // Stack pointer 252 .Case("fp", VE::SX9) // Frame pointer 253 .Case("sl", VE::SX8) // Stack limit 254 .Case("lr", VE::SX10) // Link register 255 .Case("tp", VE::SX14) // Thread pointer 256 .Case("outer", VE::SX12) // Outer regiser 257 .Case("info", VE::SX17) // Info area register 258 .Case("got", VE::SX15) // Global offset table register 259 .Case("plt", VE::SX16) // Procedure linkage table register 260 .Default(0); 261 262 if (Reg) 263 return Reg; 264 265 report_fatal_error("Invalid register name global variable"); 266 } 267 268 //===----------------------------------------------------------------------===// 269 // TargetLowering Implementation 270 //===----------------------------------------------------------------------===// 271 272 SDValue VETargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 273 SmallVectorImpl<SDValue> &InVals) const { 274 SelectionDAG &DAG = CLI.DAG; 275 SDLoc DL = CLI.DL; 276 SDValue Chain = CLI.Chain; 277 auto PtrVT = getPointerTy(DAG.getDataLayout()); 278 279 // VE target does not yet support tail call optimization. 280 CLI.IsTailCall = false; 281 282 // Get the base offset of the outgoing arguments stack space. 283 unsigned ArgsBaseOffset = 176; 284 // Get the size of the preserved arguments area 285 unsigned ArgsPreserved = 8 * 8u; 286 287 // Analyze operands of the call, assigning locations to each operand. 288 SmallVector<CCValAssign, 16> ArgLocs; 289 CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), ArgLocs, 290 *DAG.getContext()); 291 // Allocate the preserved area first. 292 CCInfo.AllocateStack(ArgsPreserved, Align(8)); 293 // We already allocated the preserved area, so the stack offset computed 294 // by CC_VE would be correct now. 295 CCInfo.AnalyzeCallOperands(CLI.Outs, CC_VE); 296 297 // VE requires to use both register and stack for varargs or no-prototyped 298 // functions. 299 bool UseBoth = CLI.IsVarArg; 300 301 // Analyze operands again if it is required to store BOTH. 302 SmallVector<CCValAssign, 16> ArgLocs2; 303 CCState CCInfo2(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), 304 ArgLocs2, *DAG.getContext()); 305 if (UseBoth) 306 CCInfo2.AnalyzeCallOperands(CLI.Outs, CC_VE2); 307 308 // Get the size of the outgoing arguments stack space requirement. 309 unsigned ArgsSize = CCInfo.getNextStackOffset(); 310 311 // Keep stack frames 16-byte aligned. 312 ArgsSize = alignTo(ArgsSize, 16); 313 314 // Adjust the stack pointer to make room for the arguments. 315 // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls 316 // with more than 6 arguments. 317 Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, DL); 318 319 // Collect the set of registers to pass to the function and their values. 320 // This will be emitted as a sequence of CopyToReg nodes glued to the call 321 // instruction. 322 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 323 324 // Collect chains from all the memory opeations that copy arguments to the 325 // stack. They must follow the stack pointer adjustment above and precede the 326 // call instruction itself. 327 SmallVector<SDValue, 8> MemOpChains; 328 329 // VE needs to get address of callee function in a register 330 // So, prepare to copy it to SX12 here. 331 332 // If the callee is a GlobalAddress node (quite common, every direct call is) 333 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it. 334 // Likewise ExternalSymbol -> TargetExternalSymbol. 335 SDValue Callee = CLI.Callee; 336 337 bool IsPICCall = isPositionIndependent(); 338 339 // PC-relative references to external symbols should go through $stub. 340 // If so, we need to prepare GlobalBaseReg first. 341 const TargetMachine &TM = DAG.getTarget(); 342 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 343 const GlobalValue *GV = nullptr; 344 auto *CalleeG = dyn_cast<GlobalAddressSDNode>(Callee); 345 if (CalleeG) 346 GV = CalleeG->getGlobal(); 347 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 348 bool UsePlt = !Local; 349 MachineFunction &MF = DAG.getMachineFunction(); 350 351 // Turn GlobalAddress/ExternalSymbol node into a value node 352 // containing the address of them here. 353 if (CalleeG) { 354 if (IsPICCall) { 355 if (UsePlt) 356 Subtarget->getInstrInfo()->getGlobalBaseReg(&MF); 357 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 358 Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee); 359 } else { 360 Callee = 361 makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 362 } 363 } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) { 364 if (IsPICCall) { 365 if (UsePlt) 366 Subtarget->getInstrInfo()->getGlobalBaseReg(&MF); 367 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0); 368 Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee); 369 } else { 370 Callee = 371 makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 372 } 373 } 374 375 RegsToPass.push_back(std::make_pair(VE::SX12, Callee)); 376 377 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 378 CCValAssign &VA = ArgLocs[i]; 379 SDValue Arg = CLI.OutVals[i]; 380 381 // Promote the value if needed. 382 switch (VA.getLocInfo()) { 383 default: 384 llvm_unreachable("Unknown location info!"); 385 case CCValAssign::Full: 386 break; 387 case CCValAssign::SExt: 388 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 389 break; 390 case CCValAssign::ZExt: 391 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 392 break; 393 case CCValAssign::AExt: 394 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 395 break; 396 case CCValAssign::BCvt: { 397 // Convert a float argument to i64 with padding. 398 // 63 31 0 399 // +------+------+ 400 // | float| 0 | 401 // +------+------+ 402 assert(VA.getLocVT() == MVT::i64); 403 assert(VA.getValVT() == MVT::f32); 404 SDValue Undef = SDValue( 405 DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0); 406 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 407 Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 408 MVT::i64, Undef, Arg, Sub_f32), 409 0); 410 break; 411 } 412 } 413 414 if (VA.isRegLoc()) { 415 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 416 if (!UseBoth) 417 continue; 418 VA = ArgLocs2[i]; 419 } 420 421 assert(VA.isMemLoc()); 422 423 // Create a store off the stack pointer for this argument. 424 SDValue StackPtr = DAG.getRegister(VE::SX11, PtrVT); 425 // The argument area starts at %fp+176 in the callee frame, 426 // %sp+176 in ours. 427 SDValue PtrOff = 428 DAG.getIntPtrConstant(VA.getLocMemOffset() + ArgsBaseOffset, DL); 429 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 430 MemOpChains.push_back( 431 DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo())); 432 } 433 434 // Emit all stores, make sure they occur before the call. 435 if (!MemOpChains.empty()) 436 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 437 438 // Build a sequence of CopyToReg nodes glued together with token chain and 439 // glue operands which copy the outgoing args into registers. The InGlue is 440 // necessary since all emitted instructions must be stuck together in order 441 // to pass the live physical registers. 442 SDValue InGlue; 443 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 444 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first, 445 RegsToPass[i].second, InGlue); 446 InGlue = Chain.getValue(1); 447 } 448 449 // Build the operands for the call instruction itself. 450 SmallVector<SDValue, 8> Ops; 451 Ops.push_back(Chain); 452 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 453 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 454 RegsToPass[i].second.getValueType())); 455 456 // Add a register mask operand representing the call-preserved registers. 457 const VERegisterInfo *TRI = Subtarget->getRegisterInfo(); 458 const uint32_t *Mask = 459 TRI->getCallPreservedMask(DAG.getMachineFunction(), CLI.CallConv); 460 assert(Mask && "Missing call preserved mask for calling convention"); 461 Ops.push_back(DAG.getRegisterMask(Mask)); 462 463 // Make sure the CopyToReg nodes are glued to the call instruction which 464 // consumes the registers. 465 if (InGlue.getNode()) 466 Ops.push_back(InGlue); 467 468 // Now the call itself. 469 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 470 Chain = DAG.getNode(VEISD::CALL, DL, NodeTys, Ops); 471 InGlue = Chain.getValue(1); 472 473 // Revert the stack pointer immediately after the call. 474 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, DL, true), 475 DAG.getIntPtrConstant(0, DL, true), InGlue, DL); 476 InGlue = Chain.getValue(1); 477 478 // Now extract the return values. This is more or less the same as 479 // LowerFormalArguments. 480 481 // Assign locations to each value returned by this call. 482 SmallVector<CCValAssign, 16> RVLocs; 483 CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), RVLocs, 484 *DAG.getContext()); 485 486 // Set inreg flag manually for codegen generated library calls that 487 // return float. 488 if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && !CLI.CB) 489 CLI.Ins[0].Flags.setInReg(); 490 491 RVInfo.AnalyzeCallResult(CLI.Ins, RetCC_VE); 492 493 // Copy all of the result registers out of their specified physreg. 494 for (unsigned i = 0; i != RVLocs.size(); ++i) { 495 CCValAssign &VA = RVLocs[i]; 496 unsigned Reg = VA.getLocReg(); 497 498 // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can 499 // reside in the same register in the high and low bits. Reuse the 500 // CopyFromReg previous node to avoid duplicate copies. 501 SDValue RV; 502 if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1))) 503 if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg) 504 RV = Chain.getValue(0); 505 506 // But usually we'll create a new CopyFromReg for a different register. 507 if (!RV.getNode()) { 508 RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue); 509 Chain = RV.getValue(1); 510 InGlue = Chain.getValue(2); 511 } 512 513 // Get the high bits for i32 struct elements. 514 if (VA.getValVT() == MVT::i32 && VA.needsCustom()) 515 RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV, 516 DAG.getConstant(32, DL, MVT::i32)); 517 518 // The callee promoted the return value, so insert an Assert?ext SDNode so 519 // we won't promote the value again in this function. 520 switch (VA.getLocInfo()) { 521 case CCValAssign::SExt: 522 RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV, 523 DAG.getValueType(VA.getValVT())); 524 break; 525 case CCValAssign::ZExt: 526 RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV, 527 DAG.getValueType(VA.getValVT())); 528 break; 529 case CCValAssign::BCvt: { 530 // Extract a float return value from i64 with padding. 531 // 63 31 0 532 // +------+------+ 533 // | float| 0 | 534 // +------+------+ 535 assert(VA.getLocVT() == MVT::i64); 536 assert(VA.getValVT() == MVT::f32); 537 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 538 RV = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 539 MVT::f32, RV, Sub_f32), 540 0); 541 break; 542 } 543 default: 544 break; 545 } 546 547 // Truncate the register down to the return value type. 548 if (VA.isExtInLoc()) 549 RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV); 550 551 InVals.push_back(RV); 552 } 553 554 return Chain; 555 } 556 557 bool VETargetLowering::isOffsetFoldingLegal( 558 const GlobalAddressSDNode *GA) const { 559 // VE uses 64 bit addressing, so we need multiple instructions to generate 560 // an address. Folding address with offset increases the number of 561 // instructions, so that we disable it here. Offsets will be folded in 562 // the DAG combine later if it worth to do so. 563 return false; 564 } 565 566 /// isFPImmLegal - Returns true if the target can instruction select the 567 /// specified FP immediate natively. If false, the legalizer will 568 /// materialize the FP immediate as a load from a constant pool. 569 bool VETargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 570 bool ForCodeSize) const { 571 return VT == MVT::f32 || VT == MVT::f64; 572 } 573 574 /// Determine if the target supports unaligned memory accesses. 575 /// 576 /// This function returns true if the target allows unaligned memory accesses 577 /// of the specified type in the given address space. If true, it also returns 578 /// whether the unaligned memory access is "fast" in the last argument by 579 /// reference. This is used, for example, in situations where an array 580 /// copy/move/set is converted to a sequence of store operations. Its use 581 /// helps to ensure that such replacements don't generate code that causes an 582 /// alignment error (trap) on the target machine. 583 bool VETargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 584 unsigned AddrSpace, 585 unsigned Align, 586 MachineMemOperand::Flags, 587 bool *Fast) const { 588 if (Fast) { 589 // It's fast anytime on VE 590 *Fast = true; 591 } 592 return true; 593 } 594 595 bool VETargetLowering::hasAndNot(SDValue Y) const { 596 EVT VT = Y.getValueType(); 597 598 // VE doesn't have vector and not instruction. 599 if (VT.isVector()) 600 return false; 601 602 // VE allows different immediate values for X and Y where ~X & Y. 603 // Only simm7 works for X, and only mimm works for Y on VE. However, this 604 // function is used to check whether an immediate value is OK for and-not 605 // instruction as both X and Y. Generating additional instruction to 606 // retrieve an immediate value is no good since the purpose of this 607 // function is to convert a series of 3 instructions to another series of 608 // 3 instructions with better parallelism. Therefore, we return false 609 // for all immediate values now. 610 // FIXME: Change hasAndNot function to have two operands to make it work 611 // correctly with Aurora VE. 612 if (isa<ConstantSDNode>(Y)) 613 return false; 614 615 // It's ok for generic registers. 616 return true; 617 } 618 619 VETargetLowering::VETargetLowering(const TargetMachine &TM, 620 const VESubtarget &STI) 621 : TargetLowering(TM), Subtarget(&STI) { 622 // Instructions which use registers as conditionals examine all the 623 // bits (as does the pseudo SELECT_CC expansion). I don't think it 624 // matters much whether it's ZeroOrOneBooleanContent, or 625 // ZeroOrNegativeOneBooleanContent, so, arbitrarily choose the 626 // former. 627 setBooleanContents(ZeroOrOneBooleanContent); 628 setBooleanVectorContents(ZeroOrOneBooleanContent); 629 630 // Set up the register classes. 631 addRegisterClass(MVT::i32, &VE::I32RegClass); 632 addRegisterClass(MVT::i64, &VE::I64RegClass); 633 addRegisterClass(MVT::f32, &VE::F32RegClass); 634 addRegisterClass(MVT::f64, &VE::I64RegClass); 635 addRegisterClass(MVT::f128, &VE::F128RegClass); 636 637 addRegisterClass(MVT::v2i32, &VE::V64RegClass); 638 addRegisterClass(MVT::v4i32, &VE::V64RegClass); 639 addRegisterClass(MVT::v8i32, &VE::V64RegClass); 640 addRegisterClass(MVT::v16i32, &VE::V64RegClass); 641 addRegisterClass(MVT::v32i32, &VE::V64RegClass); 642 addRegisterClass(MVT::v64i32, &VE::V64RegClass); 643 addRegisterClass(MVT::v128i32, &VE::V64RegClass); 644 addRegisterClass(MVT::v256i32, &VE::V64RegClass); 645 addRegisterClass(MVT::v512i32, &VE::V64RegClass); 646 647 addRegisterClass(MVT::v2i64, &VE::V64RegClass); 648 addRegisterClass(MVT::v4i64, &VE::V64RegClass); 649 addRegisterClass(MVT::v8i64, &VE::V64RegClass); 650 addRegisterClass(MVT::v16i64, &VE::V64RegClass); 651 addRegisterClass(MVT::v32i64, &VE::V64RegClass); 652 addRegisterClass(MVT::v64i64, &VE::V64RegClass); 653 addRegisterClass(MVT::v128i64, &VE::V64RegClass); 654 addRegisterClass(MVT::v256i64, &VE::V64RegClass); 655 656 addRegisterClass(MVT::v2f32, &VE::V64RegClass); 657 addRegisterClass(MVT::v4f32, &VE::V64RegClass); 658 addRegisterClass(MVT::v8f32, &VE::V64RegClass); 659 addRegisterClass(MVT::v16f32, &VE::V64RegClass); 660 addRegisterClass(MVT::v32f32, &VE::V64RegClass); 661 addRegisterClass(MVT::v64f32, &VE::V64RegClass); 662 addRegisterClass(MVT::v128f32, &VE::V64RegClass); 663 addRegisterClass(MVT::v256f32, &VE::V64RegClass); 664 addRegisterClass(MVT::v512f32, &VE::V64RegClass); 665 666 addRegisterClass(MVT::v2f64, &VE::V64RegClass); 667 addRegisterClass(MVT::v4f64, &VE::V64RegClass); 668 addRegisterClass(MVT::v8f64, &VE::V64RegClass); 669 addRegisterClass(MVT::v16f64, &VE::V64RegClass); 670 addRegisterClass(MVT::v32f64, &VE::V64RegClass); 671 addRegisterClass(MVT::v64f64, &VE::V64RegClass); 672 addRegisterClass(MVT::v128f64, &VE::V64RegClass); 673 addRegisterClass(MVT::v256f64, &VE::V64RegClass); 674 675 addRegisterClass(MVT::v256i1, &VE::VMRegClass); 676 addRegisterClass(MVT::v512i1, &VE::VM512RegClass); 677 678 /// Load & Store { 679 680 // VE doesn't have i1 sign extending load. 681 for (MVT VT : MVT::integer_valuetypes()) { 682 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 683 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 684 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 685 setTruncStoreAction(VT, MVT::i1, Expand); 686 } 687 688 // VE doesn't have floating point extload/truncstore, so expand them. 689 for (MVT FPVT : MVT::fp_valuetypes()) { 690 for (MVT OtherFPVT : MVT::fp_valuetypes()) { 691 setLoadExtAction(ISD::EXTLOAD, FPVT, OtherFPVT, Expand); 692 setTruncStoreAction(FPVT, OtherFPVT, Expand); 693 } 694 } 695 696 // VE doesn't have fp128 load/store, so expand them in custom lower. 697 setOperationAction(ISD::LOAD, MVT::f128, Custom); 698 setOperationAction(ISD::STORE, MVT::f128, Custom); 699 700 /// } Load & Store 701 702 // Custom legalize address nodes into LO/HI parts. 703 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0)); 704 setOperationAction(ISD::BlockAddress, PtrVT, Custom); 705 setOperationAction(ISD::GlobalAddress, PtrVT, Custom); 706 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom); 707 setOperationAction(ISD::ConstantPool, PtrVT, Custom); 708 709 /// VAARG handling { 710 setOperationAction(ISD::VASTART, MVT::Other, Custom); 711 // VAARG needs to be lowered to access with 8 bytes alignment. 712 setOperationAction(ISD::VAARG, MVT::Other, Custom); 713 // Use the default implementation. 714 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 715 setOperationAction(ISD::VAEND, MVT::Other, Expand); 716 /// } VAARG handling 717 718 /// Stack { 719 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 720 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 721 /// } Stack 722 723 /// Branch { 724 // VE doesn't have BRCOND 725 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 726 /// } Branch 727 728 /// Int Ops { 729 for (MVT IntVT : {MVT::i32, MVT::i64}) { 730 // VE has no REM or DIVREM operations. 731 setOperationAction(ISD::UREM, IntVT, Expand); 732 setOperationAction(ISD::SREM, IntVT, Expand); 733 setOperationAction(ISD::SDIVREM, IntVT, Expand); 734 setOperationAction(ISD::UDIVREM, IntVT, Expand); 735 736 // VE has no SHL_PARTS/SRA_PARTS/SRL_PARTS operations. 737 setOperationAction(ISD::SHL_PARTS, IntVT, Expand); 738 setOperationAction(ISD::SRA_PARTS, IntVT, Expand); 739 setOperationAction(ISD::SRL_PARTS, IntVT, Expand); 740 741 // VE has no MULHU/S or U/SMUL_LOHI operations. 742 // TODO: Use MPD instruction to implement SMUL_LOHI for i32 type. 743 setOperationAction(ISD::MULHU, IntVT, Expand); 744 setOperationAction(ISD::MULHS, IntVT, Expand); 745 setOperationAction(ISD::UMUL_LOHI, IntVT, Expand); 746 setOperationAction(ISD::SMUL_LOHI, IntVT, Expand); 747 748 // VE has no CTTZ, ROTL, ROTR operations. 749 setOperationAction(ISD::CTTZ, IntVT, Expand); 750 setOperationAction(ISD::ROTL, IntVT, Expand); 751 setOperationAction(ISD::ROTR, IntVT, Expand); 752 753 // VE has 64 bits instruction which works as i64 BSWAP operation. This 754 // instruction works fine as i32 BSWAP operation with an additional 755 // parameter. Use isel patterns to lower BSWAP. 756 setOperationAction(ISD::BSWAP, IntVT, Legal); 757 758 // VE has only 64 bits instructions which work as i64 BITREVERSE/CTLZ/CTPOP 759 // operations. Use isel patterns for i64, promote for i32. 760 LegalizeAction Act = (IntVT == MVT::i32) ? Promote : Legal; 761 setOperationAction(ISD::BITREVERSE, IntVT, Act); 762 setOperationAction(ISD::CTLZ, IntVT, Act); 763 setOperationAction(ISD::CTLZ_ZERO_UNDEF, IntVT, Act); 764 setOperationAction(ISD::CTPOP, IntVT, Act); 765 766 // VE has only 64 bits instructions which work as i64 AND/OR/XOR operations. 767 // Use isel patterns for i64, promote for i32. 768 setOperationAction(ISD::AND, IntVT, Act); 769 setOperationAction(ISD::OR, IntVT, Act); 770 setOperationAction(ISD::XOR, IntVT, Act); 771 } 772 /// } Int Ops 773 774 /// Conversion { 775 // VE doesn't have instructions for fp<->uint, so expand them by llvm 776 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote); // use i64 777 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote); // use i64 778 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 779 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 780 781 // fp16 not supported 782 for (MVT FPVT : MVT::fp_valuetypes()) { 783 setOperationAction(ISD::FP16_TO_FP, FPVT, Expand); 784 setOperationAction(ISD::FP_TO_FP16, FPVT, Expand); 785 } 786 /// } Conversion 787 788 /// Floating-point Ops { 789 /// Note: Floating-point operations are fneg, fadd, fsub, fmul, fdiv, frem, 790 /// and fcmp. 791 792 // VE doesn't have following floating point operations. 793 for (MVT VT : MVT::fp_valuetypes()) { 794 setOperationAction(ISD::FNEG, VT, Expand); 795 setOperationAction(ISD::FREM, VT, Expand); 796 } 797 798 // VE doesn't have fdiv of f128. 799 setOperationAction(ISD::FDIV, MVT::f128, Expand); 800 801 for (MVT FPVT : {MVT::f32, MVT::f64}) { 802 // f32 and f64 uses ConstantFP. f128 uses ConstantPool. 803 setOperationAction(ISD::ConstantFP, FPVT, Legal); 804 } 805 /// } Floating-point Ops 806 807 /// Floating-point math functions { 808 809 // VE doesn't have following floating point math functions. 810 for (MVT VT : MVT::fp_valuetypes()) { 811 setOperationAction(ISD::FABS, VT, Expand); 812 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 813 setOperationAction(ISD::FCOS, VT, Expand); 814 setOperationAction(ISD::FSIN, VT, Expand); 815 setOperationAction(ISD::FSQRT, VT, Expand); 816 } 817 818 /// } Floating-point math functions 819 820 /// Atomic instructions { 821 822 setMaxAtomicSizeInBitsSupported(64); 823 setMinCmpXchgSizeInBits(32); 824 setSupportsUnalignedAtomics(false); 825 826 // Use custom inserter for ATOMIC_FENCE. 827 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 828 829 /// } Atomic isntructions 830 831 setStackPointerRegisterToSaveRestore(VE::SX11); 832 833 // We have target-specific dag combine patterns for the following nodes: 834 setTargetDAGCombine(ISD::TRUNCATE); 835 836 // Set function alignment to 16 bytes 837 setMinFunctionAlignment(Align(16)); 838 839 // VE stores all argument by 8 bytes alignment 840 setMinStackArgumentAlignment(Align(8)); 841 842 computeRegisterProperties(Subtarget->getRegisterInfo()); 843 } 844 845 const char *VETargetLowering::getTargetNodeName(unsigned Opcode) const { 846 #define TARGET_NODE_CASE(NAME) \ 847 case VEISD::NAME: \ 848 return "VEISD::" #NAME; 849 switch ((VEISD::NodeType)Opcode) { 850 case VEISD::FIRST_NUMBER: 851 break; 852 TARGET_NODE_CASE(Lo) 853 TARGET_NODE_CASE(Hi) 854 TARGET_NODE_CASE(GETFUNPLT) 855 TARGET_NODE_CASE(GETSTACKTOP) 856 TARGET_NODE_CASE(GETTLSADDR) 857 TARGET_NODE_CASE(MEMBARRIER) 858 TARGET_NODE_CASE(CALL) 859 TARGET_NODE_CASE(RET_FLAG) 860 TARGET_NODE_CASE(GLOBAL_BASE_REG) 861 } 862 #undef TARGET_NODE_CASE 863 return nullptr; 864 } 865 866 EVT VETargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 867 EVT VT) const { 868 return MVT::i32; 869 } 870 871 // Convert to a target node and set target flags. 872 SDValue VETargetLowering::withTargetFlags(SDValue Op, unsigned TF, 873 SelectionDAG &DAG) const { 874 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) 875 return DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA), 876 GA->getValueType(0), GA->getOffset(), TF); 877 878 if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) 879 return DAG.getTargetBlockAddress(BA->getBlockAddress(), Op.getValueType(), 880 0, TF); 881 882 if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) 883 return DAG.getTargetConstantPool(CP->getConstVal(), CP->getValueType(0), 884 CP->getAlign(), CP->getOffset(), TF); 885 886 if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) 887 return DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0), 888 TF); 889 890 llvm_unreachable("Unhandled address SDNode"); 891 } 892 893 // Split Op into high and low parts according to HiTF and LoTF. 894 // Return an ADD node combining the parts. 895 SDValue VETargetLowering::makeHiLoPair(SDValue Op, unsigned HiTF, unsigned LoTF, 896 SelectionDAG &DAG) const { 897 SDLoc DL(Op); 898 EVT VT = Op.getValueType(); 899 SDValue Hi = DAG.getNode(VEISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG)); 900 SDValue Lo = DAG.getNode(VEISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG)); 901 return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo); 902 } 903 904 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool, 905 // or ExternalSymbol SDNode. 906 SDValue VETargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const { 907 SDLoc DL(Op); 908 EVT PtrVT = Op.getValueType(); 909 910 // Handle PIC mode first. VE needs a got load for every variable! 911 if (isPositionIndependent()) { 912 // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this 913 // function has calls. 914 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 915 MFI.setHasCalls(true); 916 auto GlobalN = dyn_cast<GlobalAddressSDNode>(Op); 917 918 if (isa<ConstantPoolSDNode>(Op) || 919 (GlobalN && GlobalN->getGlobal()->hasLocalLinkage())) { 920 // Create following instructions for local linkage PIC code. 921 // lea %s35, %gotoff_lo(.LCPI0_0) 922 // and %s35, %s35, (32)0 923 // lea.sl %s35, %gotoff_hi(.LCPI0_0)(%s35) 924 // adds.l %s35, %s15, %s35 ; %s15 is GOT 925 // FIXME: use lea.sl %s35, %gotoff_hi(.LCPI0_0)(%s35, %s15) 926 SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOTOFF_HI32, 927 VEMCExpr::VK_VE_GOTOFF_LO32, DAG); 928 SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT); 929 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo); 930 } 931 // Create following instructions for not local linkage PIC code. 932 // lea %s35, %got_lo(.LCPI0_0) 933 // and %s35, %s35, (32)0 934 // lea.sl %s35, %got_hi(.LCPI0_0)(%s35) 935 // adds.l %s35, %s15, %s35 ; %s15 is GOT 936 // ld %s35, (,%s35) 937 // FIXME: use lea.sl %s35, %gotoff_hi(.LCPI0_0)(%s35, %s15) 938 SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOT_HI32, 939 VEMCExpr::VK_VE_GOT_LO32, DAG); 940 SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT); 941 SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo); 942 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), AbsAddr, 943 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 944 } 945 946 // This is one of the absolute code models. 947 switch (getTargetMachine().getCodeModel()) { 948 default: 949 llvm_unreachable("Unsupported absolute code model"); 950 case CodeModel::Small: 951 case CodeModel::Medium: 952 case CodeModel::Large: 953 // abs64. 954 return makeHiLoPair(Op, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 955 } 956 } 957 958 /// Custom Lower { 959 960 // The mappings for emitLeading/TrailingFence for VE is designed by folling 961 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 962 Instruction *VETargetLowering::emitLeadingFence(IRBuilder<> &Builder, 963 Instruction *Inst, 964 AtomicOrdering Ord) const { 965 switch (Ord) { 966 case AtomicOrdering::NotAtomic: 967 case AtomicOrdering::Unordered: 968 llvm_unreachable("Invalid fence: unordered/non-atomic"); 969 case AtomicOrdering::Monotonic: 970 case AtomicOrdering::Acquire: 971 return nullptr; // Nothing to do 972 case AtomicOrdering::Release: 973 case AtomicOrdering::AcquireRelease: 974 return Builder.CreateFence(AtomicOrdering::Release); 975 case AtomicOrdering::SequentiallyConsistent: 976 if (!Inst->hasAtomicStore()) 977 return nullptr; // Nothing to do 978 return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent); 979 } 980 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 981 } 982 983 Instruction *VETargetLowering::emitTrailingFence(IRBuilder<> &Builder, 984 Instruction *Inst, 985 AtomicOrdering Ord) const { 986 switch (Ord) { 987 case AtomicOrdering::NotAtomic: 988 case AtomicOrdering::Unordered: 989 llvm_unreachable("Invalid fence: unordered/not-atomic"); 990 case AtomicOrdering::Monotonic: 991 case AtomicOrdering::Release: 992 return nullptr; // Nothing to do 993 case AtomicOrdering::Acquire: 994 case AtomicOrdering::AcquireRelease: 995 return Builder.CreateFence(AtomicOrdering::Acquire); 996 case AtomicOrdering::SequentiallyConsistent: 997 return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent); 998 } 999 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 1000 } 1001 1002 SDValue VETargetLowering::lowerATOMIC_FENCE(SDValue Op, 1003 SelectionDAG &DAG) const { 1004 SDLoc DL(Op); 1005 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 1006 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 1007 SyncScope::ID FenceSSID = static_cast<SyncScope::ID>( 1008 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 1009 1010 // VE uses Release consistency, so need a fence instruction if it is a 1011 // cross-thread fence. 1012 if (FenceSSID == SyncScope::System) { 1013 switch (FenceOrdering) { 1014 case AtomicOrdering::NotAtomic: 1015 case AtomicOrdering::Unordered: 1016 case AtomicOrdering::Monotonic: 1017 // No need to generate fencem instruction here. 1018 break; 1019 case AtomicOrdering::Acquire: 1020 // Generate "fencem 2" as acquire fence. 1021 return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other, 1022 DAG.getTargetConstant(2, DL, MVT::i32), 1023 Op.getOperand(0)), 1024 0); 1025 case AtomicOrdering::Release: 1026 // Generate "fencem 1" as release fence. 1027 return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other, 1028 DAG.getTargetConstant(1, DL, MVT::i32), 1029 Op.getOperand(0)), 1030 0); 1031 case AtomicOrdering::AcquireRelease: 1032 case AtomicOrdering::SequentiallyConsistent: 1033 // Generate "fencem 3" as acq_rel and seq_cst fence. 1034 // FIXME: "fencem 3" doesn't wait for for PCIe deveices accesses, 1035 // so seq_cst may require more instruction for them. 1036 return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other, 1037 DAG.getTargetConstant(3, DL, MVT::i32), 1038 Op.getOperand(0)), 1039 0); 1040 } 1041 } 1042 1043 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 1044 return DAG.getNode(VEISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0)); 1045 } 1046 1047 SDValue VETargetLowering::lowerGlobalAddress(SDValue Op, 1048 SelectionDAG &DAG) const { 1049 return makeAddress(Op, DAG); 1050 } 1051 1052 SDValue VETargetLowering::lowerBlockAddress(SDValue Op, 1053 SelectionDAG &DAG) const { 1054 return makeAddress(Op, DAG); 1055 } 1056 1057 SDValue VETargetLowering::lowerConstantPool(SDValue Op, 1058 SelectionDAG &DAG) const { 1059 return makeAddress(Op, DAG); 1060 } 1061 1062 SDValue 1063 VETargetLowering::lowerToTLSGeneralDynamicModel(SDValue Op, 1064 SelectionDAG &DAG) const { 1065 SDLoc DL(Op); 1066 1067 // Generate the following code: 1068 // t1: ch,glue = callseq_start t0, 0, 0 1069 // t2: i64,ch,glue = VEISD::GETTLSADDR t1, label, t1:1 1070 // t3: ch,glue = callseq_end t2, 0, 0, t2:2 1071 // t4: i64,ch,glue = CopyFromReg t3, Register:i64 $sx0, t3:1 1072 SDValue Label = withTargetFlags(Op, 0, DAG); 1073 EVT PtrVT = Op.getValueType(); 1074 1075 // Lowering the machine isd will make sure everything is in the right 1076 // location. 1077 SDValue Chain = DAG.getEntryNode(); 1078 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1079 const uint32_t *Mask = Subtarget->getRegisterInfo()->getCallPreservedMask( 1080 DAG.getMachineFunction(), CallingConv::C); 1081 Chain = DAG.getCALLSEQ_START(Chain, 64, 0, DL); 1082 SDValue Args[] = {Chain, Label, DAG.getRegisterMask(Mask), Chain.getValue(1)}; 1083 Chain = DAG.getNode(VEISD::GETTLSADDR, DL, NodeTys, Args); 1084 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(64, DL, true), 1085 DAG.getIntPtrConstant(0, DL, true), 1086 Chain.getValue(1), DL); 1087 Chain = DAG.getCopyFromReg(Chain, DL, VE::SX0, PtrVT, Chain.getValue(1)); 1088 1089 // GETTLSADDR will be codegen'ed as call. Inform MFI that function has calls. 1090 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 1091 MFI.setHasCalls(true); 1092 1093 // Also generate code to prepare a GOT register if it is PIC. 1094 if (isPositionIndependent()) { 1095 MachineFunction &MF = DAG.getMachineFunction(); 1096 Subtarget->getInstrInfo()->getGlobalBaseReg(&MF); 1097 } 1098 1099 return Chain; 1100 } 1101 1102 SDValue VETargetLowering::lowerGlobalTLSAddress(SDValue Op, 1103 SelectionDAG &DAG) const { 1104 // The current implementation of nld (2.26) doesn't allow local exec model 1105 // code described in VE-tls_v1.1.pdf (*1) as its input. Instead, we always 1106 // generate the general dynamic model code sequence. 1107 // 1108 // *1: https://www.nec.com/en/global/prod/hpc/aurora/document/VE-tls_v1.1.pdf 1109 return lowerToTLSGeneralDynamicModel(Op, DAG); 1110 } 1111 1112 // Lower a f128 load into two f64 loads. 1113 static SDValue lowerLoadF128(SDValue Op, SelectionDAG &DAG) { 1114 SDLoc DL(Op); 1115 LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode()); 1116 assert(LdNode && LdNode->getOffset().isUndef() && "Unexpected node type"); 1117 unsigned Alignment = LdNode->getAlign().value(); 1118 if (Alignment > 8) 1119 Alignment = 8; 1120 1121 SDValue Lo64 = 1122 DAG.getLoad(MVT::f64, DL, LdNode->getChain(), LdNode->getBasePtr(), 1123 LdNode->getPointerInfo(), Alignment, 1124 LdNode->isVolatile() ? MachineMemOperand::MOVolatile 1125 : MachineMemOperand::MONone); 1126 EVT AddrVT = LdNode->getBasePtr().getValueType(); 1127 SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, LdNode->getBasePtr(), 1128 DAG.getConstant(8, DL, AddrVT)); 1129 SDValue Hi64 = 1130 DAG.getLoad(MVT::f64, DL, LdNode->getChain(), HiPtr, 1131 LdNode->getPointerInfo(), Alignment, 1132 LdNode->isVolatile() ? MachineMemOperand::MOVolatile 1133 : MachineMemOperand::MONone); 1134 1135 SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32); 1136 SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32); 1137 1138 // VE stores Hi64 to 8(addr) and Lo64 to 0(addr) 1139 SDNode *InFP128 = 1140 DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f128); 1141 InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128, 1142 SDValue(InFP128, 0), Hi64, SubRegEven); 1143 InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128, 1144 SDValue(InFP128, 0), Lo64, SubRegOdd); 1145 SDValue OutChains[2] = {SDValue(Lo64.getNode(), 1), 1146 SDValue(Hi64.getNode(), 1)}; 1147 SDValue OutChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 1148 SDValue Ops[2] = {SDValue(InFP128, 0), OutChain}; 1149 return DAG.getMergeValues(Ops, DL); 1150 } 1151 1152 SDValue VETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const { 1153 LoadSDNode *LdNode = cast<LoadSDNode>(Op.getNode()); 1154 1155 SDValue BasePtr = LdNode->getBasePtr(); 1156 if (isa<FrameIndexSDNode>(BasePtr.getNode())) { 1157 // Do not expand store instruction with frame index here because of 1158 // dependency problems. We expand it later in eliminateFrameIndex(). 1159 return Op; 1160 } 1161 1162 EVT MemVT = LdNode->getMemoryVT(); 1163 if (MemVT == MVT::f128) 1164 return lowerLoadF128(Op, DAG); 1165 1166 return Op; 1167 } 1168 1169 // Lower a f128 store into two f64 stores. 1170 static SDValue lowerStoreF128(SDValue Op, SelectionDAG &DAG) { 1171 SDLoc DL(Op); 1172 StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode()); 1173 assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type"); 1174 1175 SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32); 1176 SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32); 1177 1178 SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64, 1179 StNode->getValue(), SubRegEven); 1180 SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64, 1181 StNode->getValue(), SubRegOdd); 1182 1183 unsigned Alignment = StNode->getAlign().value(); 1184 if (Alignment > 8) 1185 Alignment = 8; 1186 1187 // VE stores Hi64 to 8(addr) and Lo64 to 0(addr) 1188 SDValue OutChains[2]; 1189 OutChains[0] = 1190 DAG.getStore(StNode->getChain(), DL, SDValue(Lo64, 0), 1191 StNode->getBasePtr(), MachinePointerInfo(), Alignment, 1192 StNode->isVolatile() ? MachineMemOperand::MOVolatile 1193 : MachineMemOperand::MONone); 1194 EVT AddrVT = StNode->getBasePtr().getValueType(); 1195 SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, StNode->getBasePtr(), 1196 DAG.getConstant(8, DL, AddrVT)); 1197 OutChains[1] = 1198 DAG.getStore(StNode->getChain(), DL, SDValue(Hi64, 0), HiPtr, 1199 MachinePointerInfo(), Alignment, 1200 StNode->isVolatile() ? MachineMemOperand::MOVolatile 1201 : MachineMemOperand::MONone); 1202 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 1203 } 1204 1205 SDValue VETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const { 1206 StoreSDNode *StNode = cast<StoreSDNode>(Op.getNode()); 1207 assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type"); 1208 1209 SDValue BasePtr = StNode->getBasePtr(); 1210 if (isa<FrameIndexSDNode>(BasePtr.getNode())) { 1211 // Do not expand store instruction with frame index here because of 1212 // dependency problems. We expand it later in eliminateFrameIndex(). 1213 return Op; 1214 } 1215 1216 EVT MemVT = StNode->getMemoryVT(); 1217 if (MemVT == MVT::f128) 1218 return lowerStoreF128(Op, DAG); 1219 1220 // Otherwise, ask llvm to expand it. 1221 return SDValue(); 1222 } 1223 1224 SDValue VETargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 1225 MachineFunction &MF = DAG.getMachineFunction(); 1226 VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>(); 1227 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1228 1229 // Need frame address to find the address of VarArgsFrameIndex. 1230 MF.getFrameInfo().setFrameAddressIsTaken(true); 1231 1232 // vastart just stores the address of the VarArgsFrameIndex slot into the 1233 // memory location argument. 1234 SDLoc DL(Op); 1235 SDValue Offset = 1236 DAG.getNode(ISD::ADD, DL, PtrVT, DAG.getRegister(VE::SX9, PtrVT), 1237 DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset(), DL)); 1238 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1239 return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1), 1240 MachinePointerInfo(SV)); 1241 } 1242 1243 SDValue VETargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const { 1244 SDNode *Node = Op.getNode(); 1245 EVT VT = Node->getValueType(0); 1246 SDValue InChain = Node->getOperand(0); 1247 SDValue VAListPtr = Node->getOperand(1); 1248 EVT PtrVT = VAListPtr.getValueType(); 1249 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1250 SDLoc DL(Node); 1251 SDValue VAList = 1252 DAG.getLoad(PtrVT, DL, InChain, VAListPtr, MachinePointerInfo(SV)); 1253 SDValue Chain = VAList.getValue(1); 1254 SDValue NextPtr; 1255 1256 if (VT == MVT::f128) { 1257 // VE f128 values must be stored with 16 bytes alignment. We doesn't 1258 // know the actual alignment of VAList, so we take alignment of it 1259 // dyanmically. 1260 int Align = 16; 1261 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 1262 DAG.getConstant(Align - 1, DL, PtrVT)); 1263 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 1264 DAG.getConstant(-Align, DL, PtrVT)); 1265 // Increment the pointer, VAList, by 16 to the next vaarg. 1266 NextPtr = 1267 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(16, DL)); 1268 } else if (VT == MVT::f32) { 1269 // float --> need special handling like below. 1270 // 0 4 1271 // +------+------+ 1272 // | empty| float| 1273 // +------+------+ 1274 // Increment the pointer, VAList, by 8 to the next vaarg. 1275 NextPtr = 1276 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL)); 1277 // Then, adjust VAList. 1278 unsigned InternalOffset = 4; 1279 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 1280 DAG.getConstant(InternalOffset, DL, PtrVT)); 1281 } else { 1282 // Increment the pointer, VAList, by 8 to the next vaarg. 1283 NextPtr = 1284 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL)); 1285 } 1286 1287 // Store the incremented VAList to the legalized pointer. 1288 InChain = DAG.getStore(Chain, DL, NextPtr, VAListPtr, MachinePointerInfo(SV)); 1289 1290 // Load the actual argument out of the pointer VAList. 1291 // We can't count on greater alignment than the word size. 1292 return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(), 1293 std::min(PtrVT.getSizeInBits(), VT.getSizeInBits()) / 8); 1294 } 1295 1296 SDValue VETargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op, 1297 SelectionDAG &DAG) const { 1298 // Generate following code. 1299 // (void)__llvm_grow_stack(size); 1300 // ret = GETSTACKTOP; // pseudo instruction 1301 SDLoc DL(Op); 1302 1303 // Get the inputs. 1304 SDNode *Node = Op.getNode(); 1305 SDValue Chain = Op.getOperand(0); 1306 SDValue Size = Op.getOperand(1); 1307 MaybeAlign Alignment(Op.getConstantOperandVal(2)); 1308 EVT VT = Node->getValueType(0); 1309 1310 // Chain the dynamic stack allocation so that it doesn't modify the stack 1311 // pointer when other instructions are using the stack. 1312 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 1313 1314 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering(); 1315 Align StackAlign = TFI.getStackAlign(); 1316 bool NeedsAlign = Alignment.valueOrOne() > StackAlign; 1317 1318 // Prepare arguments 1319 TargetLowering::ArgListTy Args; 1320 TargetLowering::ArgListEntry Entry; 1321 Entry.Node = Size; 1322 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 1323 Args.push_back(Entry); 1324 if (NeedsAlign) { 1325 Entry.Node = DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT); 1326 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 1327 Args.push_back(Entry); 1328 } 1329 Type *RetTy = Type::getVoidTy(*DAG.getContext()); 1330 1331 EVT PtrVT = Op.getValueType(); 1332 SDValue Callee; 1333 if (NeedsAlign) { 1334 Callee = DAG.getTargetExternalSymbol("__ve_grow_stack_align", PtrVT, 0); 1335 } else { 1336 Callee = DAG.getTargetExternalSymbol("__ve_grow_stack", PtrVT, 0); 1337 } 1338 1339 TargetLowering::CallLoweringInfo CLI(DAG); 1340 CLI.setDebugLoc(DL) 1341 .setChain(Chain) 1342 .setCallee(CallingConv::PreserveAll, RetTy, Callee, std::move(Args)) 1343 .setDiscardResult(true); 1344 std::pair<SDValue, SDValue> pair = LowerCallTo(CLI); 1345 Chain = pair.second; 1346 SDValue Result = DAG.getNode(VEISD::GETSTACKTOP, DL, VT, Chain); 1347 if (NeedsAlign) { 1348 Result = DAG.getNode(ISD::ADD, DL, VT, Result, 1349 DAG.getConstant((Alignment->value() - 1ULL), DL, VT)); 1350 Result = DAG.getNode(ISD::AND, DL, VT, Result, 1351 DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT)); 1352 } 1353 // Chain = Result.getValue(1); 1354 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true), 1355 DAG.getIntPtrConstant(0, DL, true), SDValue(), DL); 1356 1357 SDValue Ops[2] = {Result, Chain}; 1358 return DAG.getMergeValues(Ops, DL); 1359 } 1360 1361 SDValue VETargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1362 switch (Op.getOpcode()) { 1363 default: 1364 llvm_unreachable("Should not custom lower this!"); 1365 case ISD::ATOMIC_FENCE: 1366 return lowerATOMIC_FENCE(Op, DAG); 1367 case ISD::BlockAddress: 1368 return lowerBlockAddress(Op, DAG); 1369 case ISD::ConstantPool: 1370 return lowerConstantPool(Op, DAG); 1371 case ISD::DYNAMIC_STACKALLOC: 1372 return lowerDYNAMIC_STACKALLOC(Op, DAG); 1373 case ISD::GlobalAddress: 1374 return lowerGlobalAddress(Op, DAG); 1375 case ISD::GlobalTLSAddress: 1376 return lowerGlobalTLSAddress(Op, DAG); 1377 case ISD::LOAD: 1378 return lowerLOAD(Op, DAG); 1379 case ISD::STORE: 1380 return lowerSTORE(Op, DAG); 1381 case ISD::VASTART: 1382 return lowerVASTART(Op, DAG); 1383 case ISD::VAARG: 1384 return lowerVAARG(Op, DAG); 1385 } 1386 } 1387 /// } Custom Lower 1388 1389 static bool isI32Insn(const SDNode *User, const SDNode *N) { 1390 switch (User->getOpcode()) { 1391 default: 1392 return false; 1393 case ISD::ADD: 1394 case ISD::SUB: 1395 case ISD::MUL: 1396 case ISD::SDIV: 1397 case ISD::UDIV: 1398 case ISD::SETCC: 1399 case ISD::SMIN: 1400 case ISD::SMAX: 1401 case ISD::SHL: 1402 case ISD::SRA: 1403 case ISD::BSWAP: 1404 case ISD::SINT_TO_FP: 1405 case ISD::UINT_TO_FP: 1406 case ISD::BR_CC: 1407 case ISD::BITCAST: 1408 case ISD::ATOMIC_CMP_SWAP: 1409 case ISD::ATOMIC_SWAP: 1410 return true; 1411 case ISD::SRL: 1412 if (N->getOperand(0).getOpcode() != ISD::SRL) 1413 return true; 1414 // (srl (trunc (srl ...))) may be optimized by combining srl, so 1415 // doesn't optimize trunc now. 1416 return false; 1417 case ISD::SELECT_CC: 1418 if (User->getOperand(2).getNode() != N && 1419 User->getOperand(3).getNode() != N) 1420 return true; 1421 LLVM_FALLTHROUGH; 1422 case ISD::AND: 1423 case ISD::OR: 1424 case ISD::XOR: 1425 case ISD::SELECT: 1426 case ISD::CopyToReg: 1427 // Check all use of selections, bit operations, and copies. If all of them 1428 // are safe, optimize truncate to extract_subreg. 1429 for (SDNode::use_iterator UI = User->use_begin(), UE = User->use_end(); 1430 UI != UE; ++UI) { 1431 switch ((*UI)->getOpcode()) { 1432 default: 1433 // If the use is an instruction which treats the source operand as i32, 1434 // it is safe to avoid truncate here. 1435 if (isI32Insn(*UI, N)) 1436 continue; 1437 break; 1438 case ISD::ANY_EXTEND: 1439 case ISD::SIGN_EXTEND: 1440 case ISD::ZERO_EXTEND: { 1441 // Special optimizations to the combination of ext and trunc. 1442 // (ext ... (select ... (trunc ...))) is safe to avoid truncate here 1443 // since this truncate instruction clears higher 32 bits which is filled 1444 // by one of ext instructions later. 1445 assert(N->getValueType(0) == MVT::i32 && 1446 "find truncate to not i32 integer"); 1447 if (User->getOpcode() == ISD::SELECT_CC || 1448 User->getOpcode() == ISD::SELECT) 1449 continue; 1450 break; 1451 } 1452 } 1453 return false; 1454 } 1455 return true; 1456 } 1457 } 1458 1459 // Optimize TRUNCATE in DAG combining. Optimizing it in CUSTOM lower is 1460 // sometime too early. Optimizing it in DAG pattern matching in VEInstrInfo.td 1461 // is sometime too late. So, doing it at here. 1462 SDValue VETargetLowering::combineTRUNCATE(SDNode *N, 1463 DAGCombinerInfo &DCI) const { 1464 assert(N->getOpcode() == ISD::TRUNCATE && 1465 "Should be called with a TRUNCATE node"); 1466 1467 SelectionDAG &DAG = DCI.DAG; 1468 SDLoc DL(N); 1469 EVT VT = N->getValueType(0); 1470 1471 // We prefer to do this when all types are legal. 1472 if (!DCI.isAfterLegalizeDAG()) 1473 return SDValue(); 1474 1475 // Skip combine TRUNCATE atm if the operand of TRUNCATE might be a constant. 1476 if (N->getOperand(0)->getOpcode() == ISD::SELECT_CC && 1477 isa<ConstantSDNode>(N->getOperand(0)->getOperand(0)) && 1478 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 1479 return SDValue(); 1480 1481 // Check all use of this TRUNCATE. 1482 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE; 1483 ++UI) { 1484 SDNode *User = *UI; 1485 1486 // Make sure that we're not going to replace TRUNCATE for non i32 1487 // instructions. 1488 // 1489 // FIXME: Although we could sometimes handle this, and it does occur in 1490 // practice that one of the condition inputs to the select is also one of 1491 // the outputs, we currently can't deal with this. 1492 if (isI32Insn(User, N)) 1493 continue; 1494 1495 return SDValue(); 1496 } 1497 1498 SDValue SubI32 = DAG.getTargetConstant(VE::sub_i32, DL, MVT::i32); 1499 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, VT, 1500 N->getOperand(0), SubI32), 1501 0); 1502 } 1503 1504 SDValue VETargetLowering::PerformDAGCombine(SDNode *N, 1505 DAGCombinerInfo &DCI) const { 1506 switch (N->getOpcode()) { 1507 default: 1508 break; 1509 case ISD::TRUNCATE: 1510 return combineTRUNCATE(N, DCI); 1511 } 1512 1513 return SDValue(); 1514 } 1515