1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 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 implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 42 #include "llvm/CodeGen/MachineMemOperand.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachineOperand.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/CodeGen/RuntimeLibcalls.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsAMDGPU.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CommandLine.h" 94 #include "llvm/Support/Compiler.h" 95 #include "llvm/Support/Debug.h" 96 #include "llvm/Support/MathExtras.h" 97 #include "llvm/Support/raw_ostream.h" 98 #include "llvm/Target/TargetIntrinsicInfo.h" 99 #include "llvm/Target/TargetMachine.h" 100 #include "llvm/Target/TargetOptions.h" 101 #include "llvm/TargetParser/Triple.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <iterator> 105 #include <limits> 106 #include <optional> 107 #include <tuple> 108 109 using namespace llvm; 110 using namespace PatternMatch; 111 using namespace SwitchCG; 112 113 #define DEBUG_TYPE "isel" 114 115 /// LimitFloatPrecision - Generate low-precision inline sequences for 116 /// some float libcalls (6, 8 or 12 bits). 117 static unsigned LimitFloatPrecision; 118 119 static cl::opt<bool> 120 InsertAssertAlign("insert-assert-align", cl::init(true), 121 cl::desc("Insert the experimental `assertalign` node."), 122 cl::ReallyHidden); 123 124 static cl::opt<unsigned, true> 125 LimitFPPrecision("limit-float-precision", 126 cl::desc("Generate low-precision inline sequences " 127 "for some float libcalls"), 128 cl::location(LimitFloatPrecision), cl::Hidden, 129 cl::init(0)); 130 131 static cl::opt<unsigned> SwitchPeelThreshold( 132 "switch-peel-threshold", cl::Hidden, cl::init(66), 133 cl::desc("Set the case probability threshold for peeling the case from a " 134 "switch statement. A value greater than 100 will void this " 135 "optimization")); 136 137 // Limit the width of DAG chains. This is important in general to prevent 138 // DAG-based analysis from blowing up. For example, alias analysis and 139 // load clustering may not complete in reasonable time. It is difficult to 140 // recognize and avoid this situation within each individual analysis, and 141 // future analyses are likely to have the same behavior. Limiting DAG width is 142 // the safe approach and will be especially important with global DAGs. 143 // 144 // MaxParallelChains default is arbitrarily high to avoid affecting 145 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 146 // sequence over this should have been converted to llvm.memcpy by the 147 // frontend. It is easy to induce this behavior with .ll code such as: 148 // %buffer = alloca [4096 x i8] 149 // %data = load [4096 x i8]* %argPtr 150 // store [4096 x i8] %data, [4096 x i8]* %buffer 151 static const unsigned MaxParallelChains = 64; 152 153 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 154 const SDValue *Parts, unsigned NumParts, 155 MVT PartVT, EVT ValueVT, const Value *V, 156 SDValue InChain, 157 std::optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue 165 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 166 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 167 SDValue InChain, 168 std::optional<CallingConv::ID> CC = std::nullopt, 169 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 170 // Let the target assemble the parts if it wants to 171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 172 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 173 PartVT, ValueVT, CC)) 174 return Val; 175 176 if (ValueVT.isVector()) 177 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 178 InChain, CC); 179 180 assert(NumParts > 0 && "No parts to assemble!"); 181 SDValue Val = Parts[0]; 182 183 if (NumParts > 1) { 184 // Assemble the value from multiple parts. 185 if (ValueVT.isInteger()) { 186 unsigned PartBits = PartVT.getSizeInBits(); 187 unsigned ValueBits = ValueVT.getSizeInBits(); 188 189 // Assemble the power of 2 part. 190 unsigned RoundParts = llvm::bit_floor(NumParts); 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 200 InChain); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 202 PartVT, HalfVT, V, InChain); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, InChain, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 227 DAG.getConstant(Lo.getValueSizeInBits(), DL, 228 TLI.getShiftAmountTy( 229 TotalVT, DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 249 InChain, CC); 250 } 251 } 252 253 // There is now one part, held in Val. Correct it to match ValueVT. 254 // PartEVT is the type of the register class that holds the value. 255 // ValueVT is the type of the inline asm operation. 256 EVT PartEVT = Val.getValueType(); 257 258 if (PartEVT == ValueVT) 259 return Val; 260 261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 262 ValueVT.bitsLT(PartEVT)) { 263 // For an FP value in an integer part, we need to truncate to the right 264 // width first. 265 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 266 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 267 } 268 269 // Handle types that have the same size. 270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 271 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 272 273 // Handle types with different sizes. 274 if (PartEVT.isInteger() && ValueVT.isInteger()) { 275 if (ValueVT.bitsLT(PartEVT)) { 276 // For a truncate, see if we have any information to 277 // indicate whether the truncated bits will always be 278 // zero or sign-extension. 279 if (AssertOp) 280 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 281 DAG.getValueType(ValueVT)); 282 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 283 } 284 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 285 } 286 287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 288 // FP_ROUND's are always exact here. 289 if (ValueVT.bitsLT(Val.getValueType())) { 290 291 SDValue NoChange = 292 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 293 294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 295 llvm::Attribute::StrictFP)) { 296 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 297 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 298 NoChange); 299 } 300 301 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 302 } 303 304 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 305 } 306 307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 308 // then truncating. 309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 310 ValueVT.bitsLT(PartEVT)) { 311 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 313 } 314 315 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 316 } 317 318 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 319 const Twine &ErrMsg) { 320 const Instruction *I = dyn_cast_or_null<Instruction>(V); 321 if (!V) 322 return Ctx.emitError(ErrMsg); 323 324 const char *AsmError = ", possible invalid constraint for vector type"; 325 if (const CallInst *CI = dyn_cast<CallInst>(I)) 326 if (CI->isInlineAsm()) 327 return Ctx.emitError(I, ErrMsg + AsmError); 328 329 return Ctx.emitError(I, ErrMsg); 330 } 331 332 /// getCopyFromPartsVector - Create a value that contains the specified legal 333 /// parts combined into the value they represent. If the parts combine to a 334 /// type larger than ValueVT then AssertOp can be used to specify whether the 335 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 336 /// ValueVT (ISD::AssertSext). 337 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 338 const SDValue *Parts, unsigned NumParts, 339 MVT PartVT, EVT ValueVT, const Value *V, 340 SDValue InChain, 341 std::optional<CallingConv::ID> CallConv) { 342 assert(ValueVT.isVector() && "Not a vector value"); 343 assert(NumParts > 0 && "No parts to assemble!"); 344 const bool IsABIRegCopy = CallConv.has_value(); 345 346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 347 SDValue Val = Parts[0]; 348 349 // Handle a multi-element vector. 350 if (NumParts > 1) { 351 EVT IntermediateVT; 352 MVT RegisterVT; 353 unsigned NumIntermediates; 354 unsigned NumRegs; 355 356 if (IsABIRegCopy) { 357 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 358 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 359 NumIntermediates, RegisterVT); 360 } else { 361 NumRegs = 362 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 363 NumIntermediates, RegisterVT); 364 } 365 366 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 367 NumParts = NumRegs; // Silence a compiler warning. 368 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 369 assert(RegisterVT.getSizeInBits() == 370 Parts[0].getSimpleValueType().getSizeInBits() && 371 "Part type sizes don't match!"); 372 373 // Assemble the parts into intermediate operands. 374 SmallVector<SDValue, 8> Ops(NumIntermediates); 375 if (NumIntermediates == NumParts) { 376 // If the register was not expanded, truncate or copy the value, 377 // as appropriate. 378 for (unsigned i = 0; i != NumParts; ++i) 379 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 380 V, InChain, CallConv); 381 } else if (NumParts > 0) { 382 // If the intermediate type was expanded, build the intermediate 383 // operands from the parts. 384 assert(NumParts % NumIntermediates == 0 && 385 "Must expand into a divisible number of parts!"); 386 unsigned Factor = NumParts / NumIntermediates; 387 for (unsigned i = 0; i != NumIntermediates; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 389 IntermediateVT, V, InChain, CallConv); 390 } 391 392 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 393 // intermediate operands. 394 EVT BuiltVectorTy = 395 IntermediateVT.isVector() 396 ? EVT::getVectorVT( 397 *DAG.getContext(), IntermediateVT.getScalarType(), 398 IntermediateVT.getVectorElementCount() * NumParts) 399 : EVT::getVectorVT(*DAG.getContext(), 400 IntermediateVT.getScalarType(), 401 NumIntermediates); 402 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 403 : ISD::BUILD_VECTOR, 404 DL, BuiltVectorTy, Ops); 405 } 406 407 // There is now one part, held in Val. Correct it to match ValueVT. 408 EVT PartEVT = Val.getValueType(); 409 410 if (PartEVT == ValueVT) 411 return Val; 412 413 if (PartEVT.isVector()) { 414 // Vector/Vector bitcast. 415 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 416 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 417 418 // If the parts vector has more elements than the value vector, then we 419 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 420 // Extract the elements we want. 421 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 422 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 423 ValueVT.getVectorElementCount().getKnownMinValue()) && 424 (PartEVT.getVectorElementCount().isScalable() == 425 ValueVT.getVectorElementCount().isScalable()) && 426 "Cannot narrow, it would be a lossy transformation"); 427 PartEVT = 428 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 429 ValueVT.getVectorElementCount()); 430 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 431 DAG.getVectorIdxConstant(0, DL)); 432 if (PartEVT == ValueVT) 433 return Val; 434 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 437 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 438 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 } 441 442 // Promoted vector extract 443 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 444 } 445 446 // Trivial bitcast if the types are the same size and the destination 447 // vector type is legal. 448 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 449 TLI.isTypeLegal(ValueVT)) 450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 451 452 if (ValueVT.getVectorNumElements() != 1) { 453 // Certain ABIs require that vectors are passed as integers. For vectors 454 // are the same size, this is an obvious bitcast. 455 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 456 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 457 } else if (ValueVT.bitsLT(PartEVT)) { 458 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 459 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 460 // Drop the extra bits. 461 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 462 return DAG.getBitcast(ValueVT, Val); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 473 unsigned ValueSize = ValueSVT.getSizeInBits(); 474 if (ValueSize == PartEVT.getSizeInBits()) { 475 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 476 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 477 // It's possible a scalar floating point type gets softened to integer and 478 // then promoted to a larger integer. If PartEVT is the larger integer 479 // we need to truncate it and then bitcast to the FP type. 480 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 481 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 482 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 483 Val = DAG.getBitcast(ValueSVT, Val); 484 } else { 485 Val = ValueVT.isFloatingPoint() 486 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 487 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 488 } 489 } 490 491 return DAG.getBuildVector(ValueVT, DL, Val); 492 } 493 494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 495 SDValue Val, SDValue *Parts, unsigned NumParts, 496 MVT PartVT, const Value *V, 497 std::optional<CallingConv::ID> CallConv); 498 499 /// getCopyToParts - Create a series of nodes that contain the specified value 500 /// split into legal parts. If the parts contain more bits than Val, then, for 501 /// integers, ExtendKind can be used to specify how to generate the extra bits. 502 static void 503 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 504 unsigned NumParts, MVT PartVT, const Value *V, 505 std::optional<CallingConv::ID> CallConv = std::nullopt, 506 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 507 // Let the target split the parts if it wants to 508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 509 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 510 CallConv)) 511 return; 512 EVT ValueVT = Val.getValueType(); 513 514 // Handle the vector case separately. 515 if (ValueVT.isVector()) 516 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 517 CallConv); 518 519 unsigned OrigNumParts = NumParts; 520 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 521 "Copying to an illegal type!"); 522 523 if (NumParts == 0) 524 return; 525 526 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 527 EVT PartEVT = PartVT; 528 if (PartEVT == ValueVT) { 529 assert(NumParts == 1 && "No-op copy with multiple parts!"); 530 Parts[0] = Val; 531 return; 532 } 533 534 unsigned PartBits = PartVT.getSizeInBits(); 535 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 536 // If the parts cover more bits than the value has, promote the value. 537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 538 assert(NumParts == 1 && "Do not know what to promote to!"); 539 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 540 } else { 541 if (ValueVT.isFloatingPoint()) { 542 // FP values need to be bitcast, then extended if they are being put 543 // into a larger container. 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 545 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 546 } 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 } else if (PartBits == ValueVT.getSizeInBits()) { 556 // Different types of the same size. 557 assert(NumParts == 1 && PartEVT != ValueVT); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 560 // If the parts cover less bits than value has, truncate the value. 561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 562 ValueVT.isInteger() && 563 "Unknown mismatch!"); 564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 565 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 566 if (PartVT == MVT::x86mmx) 567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 568 } 569 570 // The value may have changed - recompute ValueVT. 571 ValueVT = Val.getValueType(); 572 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 573 "Failed to tile the value with PartVT!"); 574 575 if (NumParts == 1) { 576 if (PartEVT != ValueVT) { 577 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 578 "scalar-to-vector conversion failed"); 579 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 580 } 581 582 Parts[0] = Val; 583 return; 584 } 585 586 // Expand the value into multiple parts. 587 if (NumParts & (NumParts - 1)) { 588 // The number of parts is not a power of 2. Split off and copy the tail. 589 assert(PartVT.isInteger() && ValueVT.isInteger() && 590 "Do not know what to expand to!"); 591 unsigned RoundParts = llvm::bit_floor(NumParts); 592 unsigned RoundBits = RoundParts * PartBits; 593 unsigned OddParts = NumParts - RoundParts; 594 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 595 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 596 597 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 598 CallConv); 599 600 if (DAG.getDataLayout().isBigEndian()) 601 // The odd parts were reversed by getCopyToParts - unreverse them. 602 std::reverse(Parts + RoundParts, Parts + NumParts); 603 604 NumParts = RoundParts; 605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 606 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 607 } 608 609 // The number of parts is a power of 2. Repeatedly bisect the value using 610 // EXTRACT_ELEMENT. 611 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 612 EVT::getIntegerVT(*DAG.getContext(), 613 ValueVT.getSizeInBits()), 614 Val); 615 616 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 617 for (unsigned i = 0; i < NumParts; i += StepSize) { 618 unsigned ThisBits = StepSize * PartBits / 2; 619 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 620 SDValue &Part0 = Parts[i]; 621 SDValue &Part1 = Parts[i+StepSize/2]; 622 623 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 625 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 627 628 if (ThisBits == PartBits && ThisVT != PartVT) { 629 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 630 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 631 } 632 } 633 } 634 635 if (DAG.getDataLayout().isBigEndian()) 636 std::reverse(Parts, Parts + OrigNumParts); 637 } 638 639 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 640 const SDLoc &DL, EVT PartVT) { 641 if (!PartVT.isVector()) 642 return SDValue(); 643 644 EVT ValueVT = Val.getValueType(); 645 EVT PartEVT = PartVT.getVectorElementType(); 646 EVT ValueEVT = ValueVT.getVectorElementType(); 647 ElementCount PartNumElts = PartVT.getVectorElementCount(); 648 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 649 650 // We only support widening vectors with equivalent element types and 651 // fixed/scalable properties. If a target needs to widen a fixed-length type 652 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 653 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 654 PartNumElts.isScalable() != ValueNumElts.isScalable()) 655 return SDValue(); 656 657 // Have a try for bf16 because some targets share its ABI with fp16. 658 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 659 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 660 "Cannot widen to illegal type"); 661 Val = DAG.getNode(ISD::BITCAST, DL, 662 ValueVT.changeVectorElementType(MVT::f16), Val); 663 } else if (PartEVT != ValueEVT) { 664 return SDValue(); 665 } 666 667 // Widening a scalable vector to another scalable vector is done by inserting 668 // the vector into a larger undef one. 669 if (PartNumElts.isScalable()) 670 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 671 Val, DAG.getVectorIdxConstant(0, DL)); 672 673 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 674 // undef elements. 675 SmallVector<SDValue, 16> Ops; 676 DAG.ExtractVectorElements(Val, Ops); 677 SDValue EltUndef = DAG.getUNDEF(PartEVT); 678 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 679 680 // FIXME: Use CONCAT for 2x -> 4x. 681 return DAG.getBuildVector(PartVT, DL, Ops); 682 } 683 684 /// getCopyToPartsVector - Create a series of nodes that contain the specified 685 /// value split into legal parts. 686 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 687 SDValue Val, SDValue *Parts, unsigned NumParts, 688 MVT PartVT, const Value *V, 689 std::optional<CallingConv::ID> CallConv) { 690 EVT ValueVT = Val.getValueType(); 691 assert(ValueVT.isVector() && "Not a vector"); 692 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 693 const bool IsABIRegCopy = CallConv.has_value(); 694 695 if (NumParts == 1) { 696 EVT PartEVT = PartVT; 697 if (PartEVT == ValueVT) { 698 // Nothing to do. 699 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 700 // Bitconvert vector->vector case. 701 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 702 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 703 Val = Widened; 704 } else if (PartVT.isVector() && 705 PartEVT.getVectorElementType().bitsGE( 706 ValueVT.getVectorElementType()) && 707 PartEVT.getVectorElementCount() == 708 ValueVT.getVectorElementCount()) { 709 710 // Promoted vector extract 711 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 712 } else if (PartEVT.isVector() && 713 PartEVT.getVectorElementType() != 714 ValueVT.getVectorElementType() && 715 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 716 TargetLowering::TypeWidenVector) { 717 // Combination of widening and promotion. 718 EVT WidenVT = 719 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 720 PartVT.getVectorElementCount()); 721 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 722 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 723 } else { 724 // Don't extract an integer from a float vector. This can happen if the 725 // FP type gets softened to integer and then promoted. The promotion 726 // prevents it from being picked up by the earlier bitcast case. 727 if (ValueVT.getVectorElementCount().isScalar() && 728 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 729 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 730 DAG.getVectorIdxConstant(0, DL)); 731 } else { 732 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 733 assert(PartVT.getFixedSizeInBits() > ValueSize && 734 "lossy conversion of vector to scalar type"); 735 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 736 Val = DAG.getBitcast(IntermediateType, Val); 737 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 738 } 739 } 740 741 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 742 Parts[0] = Val; 743 return; 744 } 745 746 // Handle a multi-element vector. 747 EVT IntermediateVT; 748 MVT RegisterVT; 749 unsigned NumIntermediates; 750 unsigned NumRegs; 751 if (IsABIRegCopy) { 752 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 753 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 754 RegisterVT); 755 } else { 756 NumRegs = 757 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 758 NumIntermediates, RegisterVT); 759 } 760 761 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 762 NumParts = NumRegs; // Silence a compiler warning. 763 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 764 765 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 766 "Mixing scalable and fixed vectors when copying in parts"); 767 768 std::optional<ElementCount> DestEltCnt; 769 770 if (IntermediateVT.isVector()) 771 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 772 else 773 DestEltCnt = ElementCount::getFixed(NumIntermediates); 774 775 EVT BuiltVectorTy = EVT::getVectorVT( 776 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 777 778 if (ValueVT == BuiltVectorTy) { 779 // Nothing to do. 780 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 781 // Bitconvert vector->vector case. 782 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 783 } else { 784 if (BuiltVectorTy.getVectorElementType().bitsGT( 785 ValueVT.getVectorElementType())) { 786 // Integer promotion. 787 ValueVT = EVT::getVectorVT(*DAG.getContext(), 788 BuiltVectorTy.getVectorElementType(), 789 ValueVT.getVectorElementCount()); 790 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 791 } 792 793 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 794 Val = Widened; 795 } 796 } 797 798 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 799 800 // Split the vector into intermediate operands. 801 SmallVector<SDValue, 8> Ops(NumIntermediates); 802 for (unsigned i = 0; i != NumIntermediates; ++i) { 803 if (IntermediateVT.isVector()) { 804 // This does something sensible for scalable vectors - see the 805 // definition of EXTRACT_SUBVECTOR for further details. 806 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 807 Ops[i] = 808 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 809 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 810 } else { 811 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 812 DAG.getVectorIdxConstant(i, DL)); 813 } 814 } 815 816 // Split the intermediate operands into legal parts. 817 if (NumParts == NumIntermediates) { 818 // If the register was not expanded, promote or copy the value, 819 // as appropriate. 820 for (unsigned i = 0; i != NumParts; ++i) 821 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 822 } else if (NumParts > 0) { 823 // If the intermediate type was expanded, split each the value into 824 // legal parts. 825 assert(NumIntermediates != 0 && "division by zero"); 826 assert(NumParts % NumIntermediates == 0 && 827 "Must expand into a divisible number of parts!"); 828 unsigned Factor = NumParts / NumIntermediates; 829 for (unsigned i = 0; i != NumIntermediates; ++i) 830 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 831 CallConv); 832 } 833 } 834 835 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 836 EVT valuevt, std::optional<CallingConv::ID> CC) 837 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 838 RegCount(1, regs.size()), CallConv(CC) {} 839 840 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 841 const DataLayout &DL, unsigned Reg, Type *Ty, 842 std::optional<CallingConv::ID> CC) { 843 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 844 845 CallConv = CC; 846 847 for (EVT ValueVT : ValueVTs) { 848 unsigned NumRegs = 849 isABIMangled() 850 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 851 : TLI.getNumRegisters(Context, ValueVT); 852 MVT RegisterVT = 853 isABIMangled() 854 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 855 : TLI.getRegisterType(Context, ValueVT); 856 for (unsigned i = 0; i != NumRegs; ++i) 857 Regs.push_back(Reg + i); 858 RegVTs.push_back(RegisterVT); 859 RegCount.push_back(NumRegs); 860 Reg += NumRegs; 861 } 862 } 863 864 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 865 FunctionLoweringInfo &FuncInfo, 866 const SDLoc &dl, SDValue &Chain, 867 SDValue *Glue, const Value *V) const { 868 // A Value with type {} or [0 x %t] needs no registers. 869 if (ValueVTs.empty()) 870 return SDValue(); 871 872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 873 874 // Assemble the legal parts into the final values. 875 SmallVector<SDValue, 4> Values(ValueVTs.size()); 876 SmallVector<SDValue, 8> Parts; 877 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 878 // Copy the legal parts from the registers. 879 EVT ValueVT = ValueVTs[Value]; 880 unsigned NumRegs = RegCount[Value]; 881 MVT RegisterVT = isABIMangled() 882 ? TLI.getRegisterTypeForCallingConv( 883 *DAG.getContext(), *CallConv, RegVTs[Value]) 884 : RegVTs[Value]; 885 886 Parts.resize(NumRegs); 887 for (unsigned i = 0; i != NumRegs; ++i) { 888 SDValue P; 889 if (!Glue) { 890 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 891 } else { 892 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 893 *Glue = P.getValue(2); 894 } 895 896 Chain = P.getValue(1); 897 Parts[i] = P; 898 899 // If the source register was virtual and if we know something about it, 900 // add an assert node. 901 if (!Register::isVirtualRegister(Regs[Part + i]) || 902 !RegisterVT.isInteger()) 903 continue; 904 905 const FunctionLoweringInfo::LiveOutInfo *LOI = 906 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 907 if (!LOI) 908 continue; 909 910 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 911 unsigned NumSignBits = LOI->NumSignBits; 912 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 913 914 if (NumZeroBits == RegSize) { 915 // The current value is a zero. 916 // Explicitly express that as it would be easier for 917 // optimizations to kick in. 918 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 919 continue; 920 } 921 922 // FIXME: We capture more information than the dag can represent. For 923 // now, just use the tightest assertzext/assertsext possible. 924 bool isSExt; 925 EVT FromVT(MVT::Other); 926 if (NumZeroBits) { 927 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 928 isSExt = false; 929 } else if (NumSignBits > 1) { 930 FromVT = 931 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 932 isSExt = true; 933 } else { 934 continue; 935 } 936 // Add an assertion node. 937 assert(FromVT != MVT::Other); 938 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 939 RegisterVT, P, DAG.getValueType(FromVT)); 940 } 941 942 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 943 RegisterVT, ValueVT, V, Chain, CallConv); 944 Part += NumRegs; 945 Parts.clear(); 946 } 947 948 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 949 } 950 951 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 952 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 953 const Value *V, 954 ISD::NodeType PreferredExtendType) const { 955 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 956 ISD::NodeType ExtendKind = PreferredExtendType; 957 958 // Get the list of the values's legal parts. 959 unsigned NumRegs = Regs.size(); 960 SmallVector<SDValue, 8> Parts(NumRegs); 961 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 962 unsigned NumParts = RegCount[Value]; 963 964 MVT RegisterVT = isABIMangled() 965 ? TLI.getRegisterTypeForCallingConv( 966 *DAG.getContext(), *CallConv, RegVTs[Value]) 967 : RegVTs[Value]; 968 969 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 970 ExtendKind = ISD::ZERO_EXTEND; 971 972 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 973 NumParts, RegisterVT, V, CallConv, ExtendKind); 974 Part += NumParts; 975 } 976 977 // Copy the parts into the registers. 978 SmallVector<SDValue, 8> Chains(NumRegs); 979 for (unsigned i = 0; i != NumRegs; ++i) { 980 SDValue Part; 981 if (!Glue) { 982 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 983 } else { 984 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 985 *Glue = Part.getValue(1); 986 } 987 988 Chains[i] = Part.getValue(0); 989 } 990 991 if (NumRegs == 1 || Glue) 992 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 993 // flagged to it. That is the CopyToReg nodes and the user are considered 994 // a single scheduling unit. If we create a TokenFactor and return it as 995 // chain, then the TokenFactor is both a predecessor (operand) of the 996 // user as well as a successor (the TF operands are flagged to the user). 997 // c1, f1 = CopyToReg 998 // c2, f2 = CopyToReg 999 // c3 = TokenFactor c1, c2 1000 // ... 1001 // = op c3, ..., f2 1002 Chain = Chains[NumRegs-1]; 1003 else 1004 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1005 } 1006 1007 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1008 unsigned MatchingIdx, const SDLoc &dl, 1009 SelectionDAG &DAG, 1010 std::vector<SDValue> &Ops) const { 1011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1012 1013 InlineAsm::Flag Flag(Code, Regs.size()); 1014 if (HasMatching) 1015 Flag.setMatchingOp(MatchingIdx); 1016 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1017 // Put the register class of the virtual registers in the flag word. That 1018 // way, later passes can recompute register class constraints for inline 1019 // assembly as well as normal instructions. 1020 // Don't do this for tied operands that can use the regclass information 1021 // from the def. 1022 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1023 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1024 Flag.setRegClass(RC->getID()); 1025 } 1026 1027 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1028 Ops.push_back(Res); 1029 1030 if (Code == InlineAsm::Kind::Clobber) { 1031 // Clobbers should always have a 1:1 mapping with registers, and may 1032 // reference registers that have illegal (e.g. vector) types. Hence, we 1033 // shouldn't try to apply any sort of splitting logic to them. 1034 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1035 "No 1:1 mapping from clobbers to regs?"); 1036 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1037 (void)SP; 1038 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1039 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1040 assert( 1041 (Regs[I] != SP || 1042 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1043 "If we clobbered the stack pointer, MFI should know about it."); 1044 } 1045 return; 1046 } 1047 1048 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1049 MVT RegisterVT = RegVTs[Value]; 1050 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1051 RegisterVT); 1052 for (unsigned i = 0; i != NumRegs; ++i) { 1053 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1054 unsigned TheReg = Regs[Reg++]; 1055 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1056 } 1057 } 1058 } 1059 1060 SmallVector<std::pair<unsigned, TypeSize>, 4> 1061 RegsForValue::getRegsAndSizes() const { 1062 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1063 unsigned I = 0; 1064 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1065 unsigned RegCount = std::get<0>(CountAndVT); 1066 MVT RegisterVT = std::get<1>(CountAndVT); 1067 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1068 for (unsigned E = I + RegCount; I != E; ++I) 1069 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1070 } 1071 return OutVec; 1072 } 1073 1074 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1075 AssumptionCache *ac, 1076 const TargetLibraryInfo *li) { 1077 AA = aa; 1078 AC = ac; 1079 GFI = gfi; 1080 LibInfo = li; 1081 Context = DAG.getContext(); 1082 LPadToCallSiteMap.clear(); 1083 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1084 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1085 *DAG.getMachineFunction().getFunction().getParent()); 1086 } 1087 1088 void SelectionDAGBuilder::clear() { 1089 NodeMap.clear(); 1090 UnusedArgNodeMap.clear(); 1091 PendingLoads.clear(); 1092 PendingExports.clear(); 1093 PendingConstrainedFP.clear(); 1094 PendingConstrainedFPStrict.clear(); 1095 CurInst = nullptr; 1096 HasTailCall = false; 1097 SDNodeOrder = LowestSDNodeOrder; 1098 StatepointLowering.clear(); 1099 } 1100 1101 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1102 DanglingDebugInfoMap.clear(); 1103 } 1104 1105 // Update DAG root to include dependencies on Pending chains. 1106 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1107 SDValue Root = DAG.getRoot(); 1108 1109 if (Pending.empty()) 1110 return Root; 1111 1112 // Add current root to PendingChains, unless we already indirectly 1113 // depend on it. 1114 if (Root.getOpcode() != ISD::EntryToken) { 1115 unsigned i = 0, e = Pending.size(); 1116 for (; i != e; ++i) { 1117 assert(Pending[i].getNode()->getNumOperands() > 1); 1118 if (Pending[i].getNode()->getOperand(0) == Root) 1119 break; // Don't add the root if we already indirectly depend on it. 1120 } 1121 1122 if (i == e) 1123 Pending.push_back(Root); 1124 } 1125 1126 if (Pending.size() == 1) 1127 Root = Pending[0]; 1128 else 1129 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1130 1131 DAG.setRoot(Root); 1132 Pending.clear(); 1133 return Root; 1134 } 1135 1136 SDValue SelectionDAGBuilder::getMemoryRoot() { 1137 return updateRoot(PendingLoads); 1138 } 1139 1140 SDValue SelectionDAGBuilder::getRoot() { 1141 // Chain up all pending constrained intrinsics together with all 1142 // pending loads, by simply appending them to PendingLoads and 1143 // then calling getMemoryRoot(). 1144 PendingLoads.reserve(PendingLoads.size() + 1145 PendingConstrainedFP.size() + 1146 PendingConstrainedFPStrict.size()); 1147 PendingLoads.append(PendingConstrainedFP.begin(), 1148 PendingConstrainedFP.end()); 1149 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1150 PendingConstrainedFPStrict.end()); 1151 PendingConstrainedFP.clear(); 1152 PendingConstrainedFPStrict.clear(); 1153 return getMemoryRoot(); 1154 } 1155 1156 SDValue SelectionDAGBuilder::getControlRoot() { 1157 // We need to emit pending fpexcept.strict constrained intrinsics, 1158 // so append them to the PendingExports list. 1159 PendingExports.append(PendingConstrainedFPStrict.begin(), 1160 PendingConstrainedFPStrict.end()); 1161 PendingConstrainedFPStrict.clear(); 1162 return updateRoot(PendingExports); 1163 } 1164 1165 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1166 DILocalVariable *Variable, 1167 DIExpression *Expression, 1168 DebugLoc DL) { 1169 assert(Variable && "Missing variable"); 1170 1171 // Check if address has undef value. 1172 if (!Address || isa<UndefValue>(Address) || 1173 (Address->use_empty() && !isa<Argument>(Address))) { 1174 LLVM_DEBUG( 1175 dbgs() 1176 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1177 return; 1178 } 1179 1180 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1181 1182 SDValue &N = NodeMap[Address]; 1183 if (!N.getNode() && isa<Argument>(Address)) 1184 // Check unused arguments map. 1185 N = UnusedArgNodeMap[Address]; 1186 SDDbgValue *SDV; 1187 if (N.getNode()) { 1188 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1189 Address = BCI->getOperand(0); 1190 // Parameters are handled specially. 1191 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1192 if (IsParameter && FINode) { 1193 // Byval parameter. We have a frame index at this point. 1194 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1195 /*IsIndirect*/ true, DL, SDNodeOrder); 1196 } else if (isa<Argument>(Address)) { 1197 // Address is an argument, so try to emit its dbg value using 1198 // virtual register info from the FuncInfo.ValueMap. 1199 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1200 FuncArgumentDbgValueKind::Declare, N); 1201 return; 1202 } else { 1203 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1204 true, DL, SDNodeOrder); 1205 } 1206 DAG.AddDbgValue(SDV, IsParameter); 1207 } else { 1208 // If Address is an argument then try to emit its dbg value using 1209 // virtual register info from the FuncInfo.ValueMap. 1210 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1211 FuncArgumentDbgValueKind::Declare, N)) { 1212 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1213 << " (could not emit func-arg dbg_value)\n"); 1214 } 1215 } 1216 return; 1217 } 1218 1219 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1220 // Add SDDbgValue nodes for any var locs here. Do so before updating 1221 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1222 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1223 // Add SDDbgValue nodes for any var locs here. Do so before updating 1224 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1225 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1226 It != End; ++It) { 1227 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1228 dropDanglingDebugInfo(Var, It->Expr); 1229 if (It->Values.isKillLocation(It->Expr)) { 1230 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1231 continue; 1232 } 1233 SmallVector<Value *> Values(It->Values.location_ops()); 1234 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1235 It->Values.hasArgList())) { 1236 SmallVector<Value *, 4> Vals; 1237 for (Value *V : It->Values.location_ops()) 1238 Vals.push_back(V); 1239 addDanglingDebugInfo(Vals, 1240 FnVarLocs->getDILocalVariable(It->VariableID), 1241 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1242 } 1243 } 1244 // We must early-exit here to prevent any DPValues from being emitted below, 1245 // as we have just emitted the debug values resulting from assignment 1246 // tracking analysis, making any existing DPValues redundant (and probably 1247 // less correct). 1248 return; 1249 } 1250 1251 // Is there is any debug-info attached to this instruction, in the form of 1252 // DPValue non-instruction debug-info records. 1253 for (DbgRecord &DPR : I.getDbgValueRange()) { 1254 DPValue &DPV = cast<DPValue>(DPR); 1255 DILocalVariable *Variable = DPV.getVariable(); 1256 DIExpression *Expression = DPV.getExpression(); 1257 dropDanglingDebugInfo(Variable, Expression); 1258 1259 if (DPV.getType() == DPValue::LocationType::Declare) { 1260 if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV)) 1261 continue; 1262 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV 1263 << "\n"); 1264 handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression, 1265 DPV.getDebugLoc()); 1266 continue; 1267 } 1268 1269 // A DPValue with no locations is a kill location. 1270 SmallVector<Value *, 4> Values(DPV.location_ops()); 1271 if (Values.empty()) { 1272 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1273 SDNodeOrder); 1274 continue; 1275 } 1276 1277 // A DPValue with an undef or absent location is also a kill location. 1278 if (llvm::any_of(Values, 1279 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1280 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1281 SDNodeOrder); 1282 continue; 1283 } 1284 1285 bool IsVariadic = DPV.hasArgList(); 1286 if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(), 1287 SDNodeOrder, IsVariadic)) { 1288 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1289 DPV.getDebugLoc(), SDNodeOrder); 1290 } 1291 } 1292 } 1293 1294 void SelectionDAGBuilder::visit(const Instruction &I) { 1295 visitDbgInfo(I); 1296 1297 // Set up outgoing PHI node register values before emitting the terminator. 1298 if (I.isTerminator()) { 1299 HandlePHINodesInSuccessorBlocks(I.getParent()); 1300 } 1301 1302 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1303 if (!isa<DbgInfoIntrinsic>(I)) 1304 ++SDNodeOrder; 1305 1306 CurInst = &I; 1307 1308 // Set inserted listener only if required. 1309 bool NodeInserted = false; 1310 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1311 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1312 if (PCSectionsMD) { 1313 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1314 DAG, [&](SDNode *) { NodeInserted = true; }); 1315 } 1316 1317 visit(I.getOpcode(), I); 1318 1319 if (!I.isTerminator() && !HasTailCall && 1320 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1321 CopyToExportRegsIfNeeded(&I); 1322 1323 // Handle metadata. 1324 if (PCSectionsMD) { 1325 auto It = NodeMap.find(&I); 1326 if (It != NodeMap.end()) { 1327 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1328 } else if (NodeInserted) { 1329 // This should not happen; if it does, don't let it go unnoticed so we can 1330 // fix it. Relevant visit*() function is probably missing a setValue(). 1331 errs() << "warning: loosing !pcsections metadata [" 1332 << I.getModule()->getName() << "]\n"; 1333 LLVM_DEBUG(I.dump()); 1334 assert(false); 1335 } 1336 } 1337 1338 CurInst = nullptr; 1339 } 1340 1341 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1342 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1343 } 1344 1345 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1346 // Note: this doesn't use InstVisitor, because it has to work with 1347 // ConstantExpr's in addition to instructions. 1348 switch (Opcode) { 1349 default: llvm_unreachable("Unknown instruction type encountered!"); 1350 // Build the switch statement using the Instruction.def file. 1351 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1352 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1353 #include "llvm/IR/Instruction.def" 1354 } 1355 } 1356 1357 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1358 DILocalVariable *Variable, 1359 DebugLoc DL, unsigned Order, 1360 SmallVectorImpl<Value *> &Values, 1361 DIExpression *Expression) { 1362 // For variadic dbg_values we will now insert an undef. 1363 // FIXME: We can potentially recover these! 1364 SmallVector<SDDbgOperand, 2> Locs; 1365 for (const Value *V : Values) { 1366 auto *Undef = UndefValue::get(V->getType()); 1367 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1368 } 1369 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1370 /*IsIndirect=*/false, DL, Order, 1371 /*IsVariadic=*/true); 1372 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1373 return true; 1374 } 1375 1376 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1377 DILocalVariable *Var, 1378 DIExpression *Expr, 1379 bool IsVariadic, DebugLoc DL, 1380 unsigned Order) { 1381 if (IsVariadic) { 1382 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1383 return; 1384 } 1385 // TODO: Dangling debug info will eventually either be resolved or produce 1386 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1387 // between the original dbg.value location and its resolved DBG_VALUE, 1388 // which we should ideally fill with an extra Undef DBG_VALUE. 1389 assert(Values.size() == 1); 1390 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1391 } 1392 1393 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1394 const DIExpression *Expr) { 1395 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1396 DIVariable *DanglingVariable = DDI.getVariable(); 1397 DIExpression *DanglingExpr = DDI.getExpression(); 1398 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1399 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1400 << printDDI(nullptr, DDI) << "\n"); 1401 return true; 1402 } 1403 return false; 1404 }; 1405 1406 for (auto &DDIMI : DanglingDebugInfoMap) { 1407 DanglingDebugInfoVector &DDIV = DDIMI.second; 1408 1409 // If debug info is to be dropped, run it through final checks to see 1410 // whether it can be salvaged. 1411 for (auto &DDI : DDIV) 1412 if (isMatchingDbgValue(DDI)) 1413 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1414 1415 erase_if(DDIV, isMatchingDbgValue); 1416 } 1417 } 1418 1419 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1420 // generate the debug data structures now that we've seen its definition. 1421 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1422 SDValue Val) { 1423 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1424 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1425 return; 1426 1427 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1428 for (auto &DDI : DDIV) { 1429 DebugLoc DL = DDI.getDebugLoc(); 1430 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1431 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1432 DILocalVariable *Variable = DDI.getVariable(); 1433 DIExpression *Expr = DDI.getExpression(); 1434 assert(Variable->isValidLocationForIntrinsic(DL) && 1435 "Expected inlined-at fields to agree"); 1436 SDDbgValue *SDV; 1437 if (Val.getNode()) { 1438 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1439 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1440 // we couldn't resolve it directly when examining the DbgValue intrinsic 1441 // in the first place we should not be more successful here). Unless we 1442 // have some test case that prove this to be correct we should avoid 1443 // calling EmitFuncArgumentDbgValue here. 1444 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1445 FuncArgumentDbgValueKind::Value, Val)) { 1446 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1447 << printDDI(V, DDI) << "\n"); 1448 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1449 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1450 // inserted after the definition of Val when emitting the instructions 1451 // after ISel. An alternative could be to teach 1452 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1453 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1454 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1455 << ValSDNodeOrder << "\n"); 1456 SDV = getDbgValue(Val, Variable, Expr, DL, 1457 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1458 DAG.AddDbgValue(SDV, false); 1459 } else 1460 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1461 << printDDI(V, DDI) 1462 << " in EmitFuncArgumentDbgValue\n"); 1463 } else { 1464 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1465 << "\n"); 1466 auto Undef = UndefValue::get(V->getType()); 1467 auto SDV = 1468 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1469 DAG.AddDbgValue(SDV, false); 1470 } 1471 } 1472 DDIV.clear(); 1473 } 1474 1475 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1476 DanglingDebugInfo &DDI) { 1477 // TODO: For the variadic implementation, instead of only checking the fail 1478 // state of `handleDebugValue`, we need know specifically which values were 1479 // invalid, so that we attempt to salvage only those values when processing 1480 // a DIArgList. 1481 const Value *OrigV = V; 1482 DILocalVariable *Var = DDI.getVariable(); 1483 DIExpression *Expr = DDI.getExpression(); 1484 DebugLoc DL = DDI.getDebugLoc(); 1485 unsigned SDOrder = DDI.getSDNodeOrder(); 1486 1487 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1488 // that DW_OP_stack_value is desired. 1489 bool StackValue = true; 1490 1491 // Can this Value can be encoded without any further work? 1492 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1493 return; 1494 1495 // Attempt to salvage back through as many instructions as possible. Bail if 1496 // a non-instruction is seen, such as a constant expression or global 1497 // variable. FIXME: Further work could recover those too. 1498 while (isa<Instruction>(V)) { 1499 const Instruction &VAsInst = *cast<const Instruction>(V); 1500 // Temporary "0", awaiting real implementation. 1501 SmallVector<uint64_t, 16> Ops; 1502 SmallVector<Value *, 4> AdditionalValues; 1503 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1504 Expr->getNumLocationOperands(), Ops, 1505 AdditionalValues); 1506 // If we cannot salvage any further, and haven't yet found a suitable debug 1507 // expression, bail out. 1508 if (!V) 1509 break; 1510 1511 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1512 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1513 // here for variadic dbg_values, remove that condition. 1514 if (!AdditionalValues.empty()) 1515 break; 1516 1517 // New value and expr now represent this debuginfo. 1518 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1519 1520 // Some kind of simplification occurred: check whether the operand of the 1521 // salvaged debug expression can be encoded in this DAG. 1522 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1523 LLVM_DEBUG( 1524 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1525 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1526 return; 1527 } 1528 } 1529 1530 // This was the final opportunity to salvage this debug information, and it 1531 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1532 // any earlier variable location. 1533 assert(OrigV && "V shouldn't be null"); 1534 auto *Undef = UndefValue::get(OrigV->getType()); 1535 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1536 DAG.AddDbgValue(SDV, false); 1537 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1538 << printDDI(OrigV, DDI) << "\n"); 1539 } 1540 1541 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1542 DIExpression *Expr, 1543 DebugLoc DbgLoc, 1544 unsigned Order) { 1545 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1546 DIExpression *NewExpr = 1547 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1548 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1549 /*IsVariadic*/ false); 1550 } 1551 1552 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1553 DILocalVariable *Var, 1554 DIExpression *Expr, DebugLoc DbgLoc, 1555 unsigned Order, bool IsVariadic) { 1556 if (Values.empty()) 1557 return true; 1558 1559 // Filter EntryValue locations out early. 1560 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1561 return true; 1562 1563 SmallVector<SDDbgOperand> LocationOps; 1564 SmallVector<SDNode *> Dependencies; 1565 for (const Value *V : Values) { 1566 // Constant value. 1567 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1568 isa<ConstantPointerNull>(V)) { 1569 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1570 continue; 1571 } 1572 1573 // Look through IntToPtr constants. 1574 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1575 if (CE->getOpcode() == Instruction::IntToPtr) { 1576 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1577 continue; 1578 } 1579 1580 // If the Value is a frame index, we can create a FrameIndex debug value 1581 // without relying on the DAG at all. 1582 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1583 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1584 if (SI != FuncInfo.StaticAllocaMap.end()) { 1585 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1586 continue; 1587 } 1588 } 1589 1590 // Do not use getValue() in here; we don't want to generate code at 1591 // this point if it hasn't been done yet. 1592 SDValue N = NodeMap[V]; 1593 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1594 N = UnusedArgNodeMap[V]; 1595 if (N.getNode()) { 1596 // Only emit func arg dbg value for non-variadic dbg.values for now. 1597 if (!IsVariadic && 1598 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1599 FuncArgumentDbgValueKind::Value, N)) 1600 return true; 1601 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1602 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1603 // describe stack slot locations. 1604 // 1605 // Consider "int x = 0; int *px = &x;". There are two kinds of 1606 // interesting debug values here after optimization: 1607 // 1608 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1609 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1610 // 1611 // Both describe the direct values of their associated variables. 1612 Dependencies.push_back(N.getNode()); 1613 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1614 continue; 1615 } 1616 LocationOps.emplace_back( 1617 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1618 continue; 1619 } 1620 1621 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1622 // Special rules apply for the first dbg.values of parameter variables in a 1623 // function. Identify them by the fact they reference Argument Values, that 1624 // they're parameters, and they are parameters of the current function. We 1625 // need to let them dangle until they get an SDNode. 1626 bool IsParamOfFunc = 1627 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1628 if (IsParamOfFunc) 1629 return false; 1630 1631 // The value is not used in this block yet (or it would have an SDNode). 1632 // We still want the value to appear for the user if possible -- if it has 1633 // an associated VReg, we can refer to that instead. 1634 auto VMI = FuncInfo.ValueMap.find(V); 1635 if (VMI != FuncInfo.ValueMap.end()) { 1636 unsigned Reg = VMI->second; 1637 // If this is a PHI node, it may be split up into several MI PHI nodes 1638 // (in FunctionLoweringInfo::set). 1639 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1640 V->getType(), std::nullopt); 1641 if (RFV.occupiesMultipleRegs()) { 1642 // FIXME: We could potentially support variadic dbg_values here. 1643 if (IsVariadic) 1644 return false; 1645 unsigned Offset = 0; 1646 unsigned BitsToDescribe = 0; 1647 if (auto VarSize = Var->getSizeInBits()) 1648 BitsToDescribe = *VarSize; 1649 if (auto Fragment = Expr->getFragmentInfo()) 1650 BitsToDescribe = Fragment->SizeInBits; 1651 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1652 // Bail out if all bits are described already. 1653 if (Offset >= BitsToDescribe) 1654 break; 1655 // TODO: handle scalable vectors. 1656 unsigned RegisterSize = RegAndSize.second; 1657 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1658 ? BitsToDescribe - Offset 1659 : RegisterSize; 1660 auto FragmentExpr = DIExpression::createFragmentExpression( 1661 Expr, Offset, FragmentSize); 1662 if (!FragmentExpr) 1663 continue; 1664 SDDbgValue *SDV = DAG.getVRegDbgValue( 1665 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1666 DAG.AddDbgValue(SDV, false); 1667 Offset += RegisterSize; 1668 } 1669 return true; 1670 } 1671 // We can use simple vreg locations for variadic dbg_values as well. 1672 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1673 continue; 1674 } 1675 // We failed to create a SDDbgOperand for V. 1676 return false; 1677 } 1678 1679 // We have created a SDDbgOperand for each Value in Values. 1680 // Should use Order instead of SDNodeOrder? 1681 assert(!LocationOps.empty()); 1682 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1683 /*IsIndirect=*/false, DbgLoc, 1684 SDNodeOrder, IsVariadic); 1685 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1686 return true; 1687 } 1688 1689 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1690 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1691 for (auto &Pair : DanglingDebugInfoMap) 1692 for (auto &DDI : Pair.second) 1693 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1694 clearDanglingDebugInfo(); 1695 } 1696 1697 /// getCopyFromRegs - If there was virtual register allocated for the value V 1698 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1699 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1700 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1701 SDValue Result; 1702 1703 if (It != FuncInfo.ValueMap.end()) { 1704 Register InReg = It->second; 1705 1706 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1707 DAG.getDataLayout(), InReg, Ty, 1708 std::nullopt); // This is not an ABI copy. 1709 SDValue Chain = DAG.getEntryNode(); 1710 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1711 V); 1712 resolveDanglingDebugInfo(V, Result); 1713 } 1714 1715 return Result; 1716 } 1717 1718 /// getValue - Return an SDValue for the given Value. 1719 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1720 // If we already have an SDValue for this value, use it. It's important 1721 // to do this first, so that we don't create a CopyFromReg if we already 1722 // have a regular SDValue. 1723 SDValue &N = NodeMap[V]; 1724 if (N.getNode()) return N; 1725 1726 // If there's a virtual register allocated and initialized for this 1727 // value, use it. 1728 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1729 return copyFromReg; 1730 1731 // Otherwise create a new SDValue and remember it. 1732 SDValue Val = getValueImpl(V); 1733 NodeMap[V] = Val; 1734 resolveDanglingDebugInfo(V, Val); 1735 return Val; 1736 } 1737 1738 /// getNonRegisterValue - Return an SDValue for the given Value, but 1739 /// don't look in FuncInfo.ValueMap for a virtual register. 1740 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1741 // If we already have an SDValue for this value, use it. 1742 SDValue &N = NodeMap[V]; 1743 if (N.getNode()) { 1744 if (isIntOrFPConstant(N)) { 1745 // Remove the debug location from the node as the node is about to be used 1746 // in a location which may differ from the original debug location. This 1747 // is relevant to Constant and ConstantFP nodes because they can appear 1748 // as constant expressions inside PHI nodes. 1749 N->setDebugLoc(DebugLoc()); 1750 } 1751 return N; 1752 } 1753 1754 // Otherwise create a new SDValue and remember it. 1755 SDValue Val = getValueImpl(V); 1756 NodeMap[V] = Val; 1757 resolveDanglingDebugInfo(V, Val); 1758 return Val; 1759 } 1760 1761 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1762 /// Create an SDValue for the given value. 1763 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1765 1766 if (const Constant *C = dyn_cast<Constant>(V)) { 1767 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1768 1769 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1770 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1771 1772 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1773 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1774 1775 if (isa<ConstantPointerNull>(C)) { 1776 unsigned AS = V->getType()->getPointerAddressSpace(); 1777 return DAG.getConstant(0, getCurSDLoc(), 1778 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1779 } 1780 1781 if (match(C, m_VScale())) 1782 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1783 1784 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1785 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1786 1787 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1788 return DAG.getUNDEF(VT); 1789 1790 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1791 visit(CE->getOpcode(), *CE); 1792 SDValue N1 = NodeMap[V]; 1793 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1794 return N1; 1795 } 1796 1797 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1798 SmallVector<SDValue, 4> Constants; 1799 for (const Use &U : C->operands()) { 1800 SDNode *Val = getValue(U).getNode(); 1801 // If the operand is an empty aggregate, there are no values. 1802 if (!Val) continue; 1803 // Add each leaf value from the operand to the Constants list 1804 // to form a flattened list of all the values. 1805 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1806 Constants.push_back(SDValue(Val, i)); 1807 } 1808 1809 return DAG.getMergeValues(Constants, getCurSDLoc()); 1810 } 1811 1812 if (const ConstantDataSequential *CDS = 1813 dyn_cast<ConstantDataSequential>(C)) { 1814 SmallVector<SDValue, 4> Ops; 1815 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1816 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1817 // Add each leaf value from the operand to the Constants list 1818 // to form a flattened list of all the values. 1819 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1820 Ops.push_back(SDValue(Val, i)); 1821 } 1822 1823 if (isa<ArrayType>(CDS->getType())) 1824 return DAG.getMergeValues(Ops, getCurSDLoc()); 1825 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1826 } 1827 1828 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1829 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1830 "Unknown struct or array constant!"); 1831 1832 SmallVector<EVT, 4> ValueVTs; 1833 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1834 unsigned NumElts = ValueVTs.size(); 1835 if (NumElts == 0) 1836 return SDValue(); // empty struct 1837 SmallVector<SDValue, 4> Constants(NumElts); 1838 for (unsigned i = 0; i != NumElts; ++i) { 1839 EVT EltVT = ValueVTs[i]; 1840 if (isa<UndefValue>(C)) 1841 Constants[i] = DAG.getUNDEF(EltVT); 1842 else if (EltVT.isFloatingPoint()) 1843 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1844 else 1845 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1846 } 1847 1848 return DAG.getMergeValues(Constants, getCurSDLoc()); 1849 } 1850 1851 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1852 return DAG.getBlockAddress(BA, VT); 1853 1854 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1855 return getValue(Equiv->getGlobalValue()); 1856 1857 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1858 return getValue(NC->getGlobalValue()); 1859 1860 if (VT == MVT::aarch64svcount) { 1861 assert(C->isNullValue() && "Can only zero this target type!"); 1862 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1863 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1864 } 1865 1866 VectorType *VecTy = cast<VectorType>(V->getType()); 1867 1868 // Now that we know the number and type of the elements, get that number of 1869 // elements into the Ops array based on what kind of constant it is. 1870 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1871 SmallVector<SDValue, 16> Ops; 1872 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1873 for (unsigned i = 0; i != NumElements; ++i) 1874 Ops.push_back(getValue(CV->getOperand(i))); 1875 1876 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1877 } 1878 1879 if (isa<ConstantAggregateZero>(C)) { 1880 EVT EltVT = 1881 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1882 1883 SDValue Op; 1884 if (EltVT.isFloatingPoint()) 1885 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1886 else 1887 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1888 1889 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1890 } 1891 1892 llvm_unreachable("Unknown vector constant"); 1893 } 1894 1895 // If this is a static alloca, generate it as the frameindex instead of 1896 // computation. 1897 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1898 DenseMap<const AllocaInst*, int>::iterator SI = 1899 FuncInfo.StaticAllocaMap.find(AI); 1900 if (SI != FuncInfo.StaticAllocaMap.end()) 1901 return DAG.getFrameIndex( 1902 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1903 } 1904 1905 // If this is an instruction which fast-isel has deferred, select it now. 1906 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1907 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1908 1909 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1910 Inst->getType(), std::nullopt); 1911 SDValue Chain = DAG.getEntryNode(); 1912 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1913 } 1914 1915 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1916 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1917 1918 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1919 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1920 1921 llvm_unreachable("Can't get register for value!"); 1922 } 1923 1924 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1925 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1926 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1927 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1928 bool IsSEH = isAsynchronousEHPersonality(Pers); 1929 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1930 if (!IsSEH) 1931 CatchPadMBB->setIsEHScopeEntry(); 1932 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1933 if (IsMSVCCXX || IsCoreCLR) 1934 CatchPadMBB->setIsEHFuncletEntry(); 1935 } 1936 1937 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1938 // Update machine-CFG edge. 1939 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1940 FuncInfo.MBB->addSuccessor(TargetMBB); 1941 TargetMBB->setIsEHCatchretTarget(true); 1942 DAG.getMachineFunction().setHasEHCatchret(true); 1943 1944 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1945 bool IsSEH = isAsynchronousEHPersonality(Pers); 1946 if (IsSEH) { 1947 // If this is not a fall-through branch or optimizations are switched off, 1948 // emit the branch. 1949 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1950 TM.getOptLevel() == CodeGenOptLevel::None) 1951 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1952 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1953 return; 1954 } 1955 1956 // Figure out the funclet membership for the catchret's successor. 1957 // This will be used by the FuncletLayout pass to determine how to order the 1958 // BB's. 1959 // A 'catchret' returns to the outer scope's color. 1960 Value *ParentPad = I.getCatchSwitchParentPad(); 1961 const BasicBlock *SuccessorColor; 1962 if (isa<ConstantTokenNone>(ParentPad)) 1963 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1964 else 1965 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1966 assert(SuccessorColor && "No parent funclet for catchret!"); 1967 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1968 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1969 1970 // Create the terminator node. 1971 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1972 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1973 DAG.getBasicBlock(SuccessorColorMBB)); 1974 DAG.setRoot(Ret); 1975 } 1976 1977 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1978 // Don't emit any special code for the cleanuppad instruction. It just marks 1979 // the start of an EH scope/funclet. 1980 FuncInfo.MBB->setIsEHScopeEntry(); 1981 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1982 if (Pers != EHPersonality::Wasm_CXX) { 1983 FuncInfo.MBB->setIsEHFuncletEntry(); 1984 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1985 } 1986 } 1987 1988 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1989 // not match, it is OK to add only the first unwind destination catchpad to the 1990 // successors, because there will be at least one invoke instruction within the 1991 // catch scope that points to the next unwind destination, if one exists, so 1992 // CFGSort cannot mess up with BB sorting order. 1993 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1994 // call within them, and catchpads only consisting of 'catch (...)' have a 1995 // '__cxa_end_catch' call within them, both of which generate invokes in case 1996 // the next unwind destination exists, i.e., the next unwind destination is not 1997 // the caller.) 1998 // 1999 // Having at most one EH pad successor is also simpler and helps later 2000 // transformations. 2001 // 2002 // For example, 2003 // current: 2004 // invoke void @foo to ... unwind label %catch.dispatch 2005 // catch.dispatch: 2006 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2007 // catch.start: 2008 // ... 2009 // ... in this BB or some other child BB dominated by this BB there will be an 2010 // invoke that points to 'next' BB as an unwind destination 2011 // 2012 // next: ; We don't need to add this to 'current' BB's successor 2013 // ... 2014 static void findWasmUnwindDestinations( 2015 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2016 BranchProbability Prob, 2017 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2018 &UnwindDests) { 2019 while (EHPadBB) { 2020 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2021 if (isa<CleanupPadInst>(Pad)) { 2022 // Stop on cleanup pads. 2023 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2024 UnwindDests.back().first->setIsEHScopeEntry(); 2025 break; 2026 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2027 // Add the catchpad handlers to the possible destinations. We don't 2028 // continue to the unwind destination of the catchswitch for wasm. 2029 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2030 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2031 UnwindDests.back().first->setIsEHScopeEntry(); 2032 } 2033 break; 2034 } else { 2035 continue; 2036 } 2037 } 2038 } 2039 2040 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2041 /// many places it could ultimately go. In the IR, we have a single unwind 2042 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2043 /// This function skips over imaginary basic blocks that hold catchswitch 2044 /// instructions, and finds all the "real" machine 2045 /// basic block destinations. As those destinations may not be successors of 2046 /// EHPadBB, here we also calculate the edge probability to those destinations. 2047 /// The passed-in Prob is the edge probability to EHPadBB. 2048 static void findUnwindDestinations( 2049 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2050 BranchProbability Prob, 2051 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2052 &UnwindDests) { 2053 EHPersonality Personality = 2054 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2055 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2056 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2057 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2058 bool IsSEH = isAsynchronousEHPersonality(Personality); 2059 2060 if (IsWasmCXX) { 2061 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2062 assert(UnwindDests.size() <= 1 && 2063 "There should be at most one unwind destination for wasm"); 2064 return; 2065 } 2066 2067 while (EHPadBB) { 2068 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2069 BasicBlock *NewEHPadBB = nullptr; 2070 if (isa<LandingPadInst>(Pad)) { 2071 // Stop on landingpads. They are not funclets. 2072 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2073 break; 2074 } else if (isa<CleanupPadInst>(Pad)) { 2075 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2076 // personalities. 2077 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2078 UnwindDests.back().first->setIsEHScopeEntry(); 2079 UnwindDests.back().first->setIsEHFuncletEntry(); 2080 break; 2081 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2082 // Add the catchpad handlers to the possible destinations. 2083 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2084 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2085 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2086 if (IsMSVCCXX || IsCoreCLR) 2087 UnwindDests.back().first->setIsEHFuncletEntry(); 2088 if (!IsSEH) 2089 UnwindDests.back().first->setIsEHScopeEntry(); 2090 } 2091 NewEHPadBB = CatchSwitch->getUnwindDest(); 2092 } else { 2093 continue; 2094 } 2095 2096 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2097 if (BPI && NewEHPadBB) 2098 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2099 EHPadBB = NewEHPadBB; 2100 } 2101 } 2102 2103 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2104 // Update successor info. 2105 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2106 auto UnwindDest = I.getUnwindDest(); 2107 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2108 BranchProbability UnwindDestProb = 2109 (BPI && UnwindDest) 2110 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2111 : BranchProbability::getZero(); 2112 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2113 for (auto &UnwindDest : UnwindDests) { 2114 UnwindDest.first->setIsEHPad(); 2115 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2116 } 2117 FuncInfo.MBB->normalizeSuccProbs(); 2118 2119 // Create the terminator node. 2120 SDValue Ret = 2121 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2122 DAG.setRoot(Ret); 2123 } 2124 2125 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2126 report_fatal_error("visitCatchSwitch not yet implemented!"); 2127 } 2128 2129 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2130 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2131 auto &DL = DAG.getDataLayout(); 2132 SDValue Chain = getControlRoot(); 2133 SmallVector<ISD::OutputArg, 8> Outs; 2134 SmallVector<SDValue, 8> OutVals; 2135 2136 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2137 // lower 2138 // 2139 // %val = call <ty> @llvm.experimental.deoptimize() 2140 // ret <ty> %val 2141 // 2142 // differently. 2143 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2144 LowerDeoptimizingReturn(); 2145 return; 2146 } 2147 2148 if (!FuncInfo.CanLowerReturn) { 2149 unsigned DemoteReg = FuncInfo.DemoteRegister; 2150 const Function *F = I.getParent()->getParent(); 2151 2152 // Emit a store of the return value through the virtual register. 2153 // Leave Outs empty so that LowerReturn won't try to load return 2154 // registers the usual way. 2155 SmallVector<EVT, 1> PtrValueVTs; 2156 ComputeValueVTs(TLI, DL, 2157 PointerType::get(F->getContext(), 2158 DAG.getDataLayout().getAllocaAddrSpace()), 2159 PtrValueVTs); 2160 2161 SDValue RetPtr = 2162 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2163 SDValue RetOp = getValue(I.getOperand(0)); 2164 2165 SmallVector<EVT, 4> ValueVTs, MemVTs; 2166 SmallVector<uint64_t, 4> Offsets; 2167 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2168 &Offsets, 0); 2169 unsigned NumValues = ValueVTs.size(); 2170 2171 SmallVector<SDValue, 4> Chains(NumValues); 2172 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2173 for (unsigned i = 0; i != NumValues; ++i) { 2174 // An aggregate return value cannot wrap around the address space, so 2175 // offsets to its parts don't wrap either. 2176 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2177 TypeSize::getFixed(Offsets[i])); 2178 2179 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2180 if (MemVTs[i] != ValueVTs[i]) 2181 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2182 Chains[i] = DAG.getStore( 2183 Chain, getCurSDLoc(), Val, 2184 // FIXME: better loc info would be nice. 2185 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2186 commonAlignment(BaseAlign, Offsets[i])); 2187 } 2188 2189 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2190 MVT::Other, Chains); 2191 } else if (I.getNumOperands() != 0) { 2192 SmallVector<EVT, 4> ValueVTs; 2193 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2194 unsigned NumValues = ValueVTs.size(); 2195 if (NumValues) { 2196 SDValue RetOp = getValue(I.getOperand(0)); 2197 2198 const Function *F = I.getParent()->getParent(); 2199 2200 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2201 I.getOperand(0)->getType(), F->getCallingConv(), 2202 /*IsVarArg*/ false, DL); 2203 2204 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2205 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2206 ExtendKind = ISD::SIGN_EXTEND; 2207 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2208 ExtendKind = ISD::ZERO_EXTEND; 2209 2210 LLVMContext &Context = F->getContext(); 2211 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2212 2213 for (unsigned j = 0; j != NumValues; ++j) { 2214 EVT VT = ValueVTs[j]; 2215 2216 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2217 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2218 2219 CallingConv::ID CC = F->getCallingConv(); 2220 2221 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2222 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2223 SmallVector<SDValue, 4> Parts(NumParts); 2224 getCopyToParts(DAG, getCurSDLoc(), 2225 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2226 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2227 2228 // 'inreg' on function refers to return value 2229 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2230 if (RetInReg) 2231 Flags.setInReg(); 2232 2233 if (I.getOperand(0)->getType()->isPointerTy()) { 2234 Flags.setPointer(); 2235 Flags.setPointerAddrSpace( 2236 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2237 } 2238 2239 if (NeedsRegBlock) { 2240 Flags.setInConsecutiveRegs(); 2241 if (j == NumValues - 1) 2242 Flags.setInConsecutiveRegsLast(); 2243 } 2244 2245 // Propagate extension type if any 2246 if (ExtendKind == ISD::SIGN_EXTEND) 2247 Flags.setSExt(); 2248 else if (ExtendKind == ISD::ZERO_EXTEND) 2249 Flags.setZExt(); 2250 2251 for (unsigned i = 0; i < NumParts; ++i) { 2252 Outs.push_back(ISD::OutputArg(Flags, 2253 Parts[i].getValueType().getSimpleVT(), 2254 VT, /*isfixed=*/true, 0, 0)); 2255 OutVals.push_back(Parts[i]); 2256 } 2257 } 2258 } 2259 } 2260 2261 // Push in swifterror virtual register as the last element of Outs. This makes 2262 // sure swifterror virtual register will be returned in the swifterror 2263 // physical register. 2264 const Function *F = I.getParent()->getParent(); 2265 if (TLI.supportSwiftError() && 2266 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2267 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2268 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2269 Flags.setSwiftError(); 2270 Outs.push_back(ISD::OutputArg( 2271 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2272 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2273 // Create SDNode for the swifterror virtual register. 2274 OutVals.push_back( 2275 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2276 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2277 EVT(TLI.getPointerTy(DL)))); 2278 } 2279 2280 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2281 CallingConv::ID CallConv = 2282 DAG.getMachineFunction().getFunction().getCallingConv(); 2283 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2284 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2285 2286 // Verify that the target's LowerReturn behaved as expected. 2287 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2288 "LowerReturn didn't return a valid chain!"); 2289 2290 // Update the DAG with the new chain value resulting from return lowering. 2291 DAG.setRoot(Chain); 2292 } 2293 2294 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2295 /// created for it, emit nodes to copy the value into the virtual 2296 /// registers. 2297 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2298 // Skip empty types 2299 if (V->getType()->isEmptyTy()) 2300 return; 2301 2302 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2303 if (VMI != FuncInfo.ValueMap.end()) { 2304 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2305 "Unused value assigned virtual registers!"); 2306 CopyValueToVirtualRegister(V, VMI->second); 2307 } 2308 } 2309 2310 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2311 /// the current basic block, add it to ValueMap now so that we'll get a 2312 /// CopyTo/FromReg. 2313 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2314 // No need to export constants. 2315 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2316 2317 // Already exported? 2318 if (FuncInfo.isExportedInst(V)) return; 2319 2320 Register Reg = FuncInfo.InitializeRegForValue(V); 2321 CopyValueToVirtualRegister(V, Reg); 2322 } 2323 2324 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2325 const BasicBlock *FromBB) { 2326 // The operands of the setcc have to be in this block. We don't know 2327 // how to export them from some other block. 2328 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2329 // Can export from current BB. 2330 if (VI->getParent() == FromBB) 2331 return true; 2332 2333 // Is already exported, noop. 2334 return FuncInfo.isExportedInst(V); 2335 } 2336 2337 // If this is an argument, we can export it if the BB is the entry block or 2338 // if it is already exported. 2339 if (isa<Argument>(V)) { 2340 if (FromBB->isEntryBlock()) 2341 return true; 2342 2343 // Otherwise, can only export this if it is already exported. 2344 return FuncInfo.isExportedInst(V); 2345 } 2346 2347 // Otherwise, constants can always be exported. 2348 return true; 2349 } 2350 2351 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2352 BranchProbability 2353 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2354 const MachineBasicBlock *Dst) const { 2355 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2356 const BasicBlock *SrcBB = Src->getBasicBlock(); 2357 const BasicBlock *DstBB = Dst->getBasicBlock(); 2358 if (!BPI) { 2359 // If BPI is not available, set the default probability as 1 / N, where N is 2360 // the number of successors. 2361 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2362 return BranchProbability(1, SuccSize); 2363 } 2364 return BPI->getEdgeProbability(SrcBB, DstBB); 2365 } 2366 2367 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2368 MachineBasicBlock *Dst, 2369 BranchProbability Prob) { 2370 if (!FuncInfo.BPI) 2371 Src->addSuccessorWithoutProb(Dst); 2372 else { 2373 if (Prob.isUnknown()) 2374 Prob = getEdgeProbability(Src, Dst); 2375 Src->addSuccessor(Dst, Prob); 2376 } 2377 } 2378 2379 static bool InBlock(const Value *V, const BasicBlock *BB) { 2380 if (const Instruction *I = dyn_cast<Instruction>(V)) 2381 return I->getParent() == BB; 2382 return true; 2383 } 2384 2385 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2386 /// This function emits a branch and is used at the leaves of an OR or an 2387 /// AND operator tree. 2388 void 2389 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2390 MachineBasicBlock *TBB, 2391 MachineBasicBlock *FBB, 2392 MachineBasicBlock *CurBB, 2393 MachineBasicBlock *SwitchBB, 2394 BranchProbability TProb, 2395 BranchProbability FProb, 2396 bool InvertCond) { 2397 const BasicBlock *BB = CurBB->getBasicBlock(); 2398 2399 // If the leaf of the tree is a comparison, merge the condition into 2400 // the caseblock. 2401 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2402 // The operands of the cmp have to be in this block. We don't know 2403 // how to export them from some other block. If this is the first block 2404 // of the sequence, no exporting is needed. 2405 if (CurBB == SwitchBB || 2406 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2407 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2408 ISD::CondCode Condition; 2409 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2410 ICmpInst::Predicate Pred = 2411 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2412 Condition = getICmpCondCode(Pred); 2413 } else { 2414 const FCmpInst *FC = cast<FCmpInst>(Cond); 2415 FCmpInst::Predicate Pred = 2416 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2417 Condition = getFCmpCondCode(Pred); 2418 if (TM.Options.NoNaNsFPMath) 2419 Condition = getFCmpCodeWithoutNaN(Condition); 2420 } 2421 2422 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2423 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2424 SL->SwitchCases.push_back(CB); 2425 return; 2426 } 2427 } 2428 2429 // Create a CaseBlock record representing this branch. 2430 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2431 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2432 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2433 SL->SwitchCases.push_back(CB); 2434 } 2435 2436 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2437 MachineBasicBlock *TBB, 2438 MachineBasicBlock *FBB, 2439 MachineBasicBlock *CurBB, 2440 MachineBasicBlock *SwitchBB, 2441 Instruction::BinaryOps Opc, 2442 BranchProbability TProb, 2443 BranchProbability FProb, 2444 bool InvertCond) { 2445 // Skip over not part of the tree and remember to invert op and operands at 2446 // next level. 2447 Value *NotCond; 2448 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2449 InBlock(NotCond, CurBB->getBasicBlock())) { 2450 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2451 !InvertCond); 2452 return; 2453 } 2454 2455 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2456 const Value *BOpOp0, *BOpOp1; 2457 // Compute the effective opcode for Cond, taking into account whether it needs 2458 // to be inverted, e.g. 2459 // and (not (or A, B)), C 2460 // gets lowered as 2461 // and (and (not A, not B), C) 2462 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2463 if (BOp) { 2464 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2465 ? Instruction::And 2466 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2467 ? Instruction::Or 2468 : (Instruction::BinaryOps)0); 2469 if (InvertCond) { 2470 if (BOpc == Instruction::And) 2471 BOpc = Instruction::Or; 2472 else if (BOpc == Instruction::Or) 2473 BOpc = Instruction::And; 2474 } 2475 } 2476 2477 // If this node is not part of the or/and tree, emit it as a branch. 2478 // Note that all nodes in the tree should have same opcode. 2479 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2480 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2481 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2482 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2483 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2484 TProb, FProb, InvertCond); 2485 return; 2486 } 2487 2488 // Create TmpBB after CurBB. 2489 MachineFunction::iterator BBI(CurBB); 2490 MachineFunction &MF = DAG.getMachineFunction(); 2491 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2492 CurBB->getParent()->insert(++BBI, TmpBB); 2493 2494 if (Opc == Instruction::Or) { 2495 // Codegen X | Y as: 2496 // BB1: 2497 // jmp_if_X TBB 2498 // jmp TmpBB 2499 // TmpBB: 2500 // jmp_if_Y TBB 2501 // jmp FBB 2502 // 2503 2504 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2505 // The requirement is that 2506 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2507 // = TrueProb for original BB. 2508 // Assuming the original probabilities are A and B, one choice is to set 2509 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2510 // A/(1+B) and 2B/(1+B). This choice assumes that 2511 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2512 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2513 // TmpBB, but the math is more complicated. 2514 2515 auto NewTrueProb = TProb / 2; 2516 auto NewFalseProb = TProb / 2 + FProb; 2517 // Emit the LHS condition. 2518 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2519 NewFalseProb, InvertCond); 2520 2521 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2522 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2523 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2524 // Emit the RHS condition into TmpBB. 2525 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2526 Probs[1], InvertCond); 2527 } else { 2528 assert(Opc == Instruction::And && "Unknown merge op!"); 2529 // Codegen X & Y as: 2530 // BB1: 2531 // jmp_if_X TmpBB 2532 // jmp FBB 2533 // TmpBB: 2534 // jmp_if_Y TBB 2535 // jmp FBB 2536 // 2537 // This requires creation of TmpBB after CurBB. 2538 2539 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2540 // The requirement is that 2541 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2542 // = FalseProb for original BB. 2543 // Assuming the original probabilities are A and B, one choice is to set 2544 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2545 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2546 // TrueProb for BB1 * FalseProb for TmpBB. 2547 2548 auto NewTrueProb = TProb + FProb / 2; 2549 auto NewFalseProb = FProb / 2; 2550 // Emit the LHS condition. 2551 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2552 NewFalseProb, InvertCond); 2553 2554 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2555 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2556 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2557 // Emit the RHS condition into TmpBB. 2558 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2559 Probs[1], InvertCond); 2560 } 2561 } 2562 2563 /// If the set of cases should be emitted as a series of branches, return true. 2564 /// If we should emit this as a bunch of and/or'd together conditions, return 2565 /// false. 2566 bool 2567 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2568 if (Cases.size() != 2) return true; 2569 2570 // If this is two comparisons of the same values or'd or and'd together, they 2571 // will get folded into a single comparison, so don't emit two blocks. 2572 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2573 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2574 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2575 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2576 return false; 2577 } 2578 2579 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2580 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2581 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2582 Cases[0].CC == Cases[1].CC && 2583 isa<Constant>(Cases[0].CmpRHS) && 2584 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2585 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2586 return false; 2587 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2588 return false; 2589 } 2590 2591 return true; 2592 } 2593 2594 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2595 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2596 2597 // Update machine-CFG edges. 2598 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2599 2600 if (I.isUnconditional()) { 2601 // Update machine-CFG edges. 2602 BrMBB->addSuccessor(Succ0MBB); 2603 2604 // If this is not a fall-through branch or optimizations are switched off, 2605 // emit the branch. 2606 if (Succ0MBB != NextBlock(BrMBB) || 2607 TM.getOptLevel() == CodeGenOptLevel::None) { 2608 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2609 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2610 setValue(&I, Br); 2611 DAG.setRoot(Br); 2612 } 2613 2614 return; 2615 } 2616 2617 // If this condition is one of the special cases we handle, do special stuff 2618 // now. 2619 const Value *CondVal = I.getCondition(); 2620 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2621 2622 // If this is a series of conditions that are or'd or and'd together, emit 2623 // this as a sequence of branches instead of setcc's with and/or operations. 2624 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2625 // unpredictable branches, and vector extracts because those jumps are likely 2626 // expensive for any target), this should improve performance. 2627 // For example, instead of something like: 2628 // cmp A, B 2629 // C = seteq 2630 // cmp D, E 2631 // F = setle 2632 // or C, F 2633 // jnz foo 2634 // Emit: 2635 // cmp A, B 2636 // je foo 2637 // cmp D, E 2638 // jle foo 2639 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2640 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2641 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2642 Value *Vec; 2643 const Value *BOp0, *BOp1; 2644 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2645 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2646 Opcode = Instruction::And; 2647 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2648 Opcode = Instruction::Or; 2649 2650 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2651 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2652 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2653 getEdgeProbability(BrMBB, Succ0MBB), 2654 getEdgeProbability(BrMBB, Succ1MBB), 2655 /*InvertCond=*/false); 2656 // If the compares in later blocks need to use values not currently 2657 // exported from this block, export them now. This block should always 2658 // be the first entry. 2659 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2660 2661 // Allow some cases to be rejected. 2662 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2663 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2664 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2665 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2666 } 2667 2668 // Emit the branch for this block. 2669 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2670 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2671 return; 2672 } 2673 2674 // Okay, we decided not to do this, remove any inserted MBB's and clear 2675 // SwitchCases. 2676 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2677 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2678 2679 SL->SwitchCases.clear(); 2680 } 2681 } 2682 2683 // Create a CaseBlock record representing this branch. 2684 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2685 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2686 2687 // Use visitSwitchCase to actually insert the fast branch sequence for this 2688 // cond branch. 2689 visitSwitchCase(CB, BrMBB); 2690 } 2691 2692 /// visitSwitchCase - Emits the necessary code to represent a single node in 2693 /// the binary search tree resulting from lowering a switch instruction. 2694 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2695 MachineBasicBlock *SwitchBB) { 2696 SDValue Cond; 2697 SDValue CondLHS = getValue(CB.CmpLHS); 2698 SDLoc dl = CB.DL; 2699 2700 if (CB.CC == ISD::SETTRUE) { 2701 // Branch or fall through to TrueBB. 2702 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2703 SwitchBB->normalizeSuccProbs(); 2704 if (CB.TrueBB != NextBlock(SwitchBB)) { 2705 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2706 DAG.getBasicBlock(CB.TrueBB))); 2707 } 2708 return; 2709 } 2710 2711 auto &TLI = DAG.getTargetLoweringInfo(); 2712 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2713 2714 // Build the setcc now. 2715 if (!CB.CmpMHS) { 2716 // Fold "(X == true)" to X and "(X == false)" to !X to 2717 // handle common cases produced by branch lowering. 2718 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2719 CB.CC == ISD::SETEQ) 2720 Cond = CondLHS; 2721 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2722 CB.CC == ISD::SETEQ) { 2723 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2724 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2725 } else { 2726 SDValue CondRHS = getValue(CB.CmpRHS); 2727 2728 // If a pointer's DAG type is larger than its memory type then the DAG 2729 // values are zero-extended. This breaks signed comparisons so truncate 2730 // back to the underlying type before doing the compare. 2731 if (CondLHS.getValueType() != MemVT) { 2732 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2733 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2734 } 2735 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2736 } 2737 } else { 2738 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2739 2740 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2741 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2742 2743 SDValue CmpOp = getValue(CB.CmpMHS); 2744 EVT VT = CmpOp.getValueType(); 2745 2746 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2747 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2748 ISD::SETLE); 2749 } else { 2750 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2751 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2752 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2753 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2754 } 2755 } 2756 2757 // Update successor info 2758 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2759 // TrueBB and FalseBB are always different unless the incoming IR is 2760 // degenerate. This only happens when running llc on weird IR. 2761 if (CB.TrueBB != CB.FalseBB) 2762 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2763 SwitchBB->normalizeSuccProbs(); 2764 2765 // If the lhs block is the next block, invert the condition so that we can 2766 // fall through to the lhs instead of the rhs block. 2767 if (CB.TrueBB == NextBlock(SwitchBB)) { 2768 std::swap(CB.TrueBB, CB.FalseBB); 2769 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2770 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2771 } 2772 2773 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2774 MVT::Other, getControlRoot(), Cond, 2775 DAG.getBasicBlock(CB.TrueBB)); 2776 2777 setValue(CurInst, BrCond); 2778 2779 // Insert the false branch. Do this even if it's a fall through branch, 2780 // this makes it easier to do DAG optimizations which require inverting 2781 // the branch condition. 2782 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2783 DAG.getBasicBlock(CB.FalseBB)); 2784 2785 DAG.setRoot(BrCond); 2786 } 2787 2788 /// visitJumpTable - Emit JumpTable node in the current MBB 2789 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2790 // Emit the code for the jump table 2791 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2792 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2793 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2794 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2795 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2796 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2797 Index.getValue(1), Table, Index); 2798 DAG.setRoot(BrJumpTable); 2799 } 2800 2801 /// visitJumpTableHeader - This function emits necessary code to produce index 2802 /// in the JumpTable from switch case. 2803 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2804 JumpTableHeader &JTH, 2805 MachineBasicBlock *SwitchBB) { 2806 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2807 const SDLoc &dl = *JT.SL; 2808 2809 // Subtract the lowest switch case value from the value being switched on. 2810 SDValue SwitchOp = getValue(JTH.SValue); 2811 EVT VT = SwitchOp.getValueType(); 2812 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2813 DAG.getConstant(JTH.First, dl, VT)); 2814 2815 // The SDNode we just created, which holds the value being switched on minus 2816 // the smallest case value, needs to be copied to a virtual register so it 2817 // can be used as an index into the jump table in a subsequent basic block. 2818 // This value may be smaller or larger than the target's pointer type, and 2819 // therefore require extension or truncating. 2820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2821 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2822 2823 unsigned JumpTableReg = 2824 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2825 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2826 JumpTableReg, SwitchOp); 2827 JT.Reg = JumpTableReg; 2828 2829 if (!JTH.FallthroughUnreachable) { 2830 // Emit the range check for the jump table, and branch to the default block 2831 // for the switch statement if the value being switched on exceeds the 2832 // largest case in the switch. 2833 SDValue CMP = DAG.getSetCC( 2834 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2835 Sub.getValueType()), 2836 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2837 2838 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2839 MVT::Other, CopyTo, CMP, 2840 DAG.getBasicBlock(JT.Default)); 2841 2842 // Avoid emitting unnecessary branches to the next block. 2843 if (JT.MBB != NextBlock(SwitchBB)) 2844 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2845 DAG.getBasicBlock(JT.MBB)); 2846 2847 DAG.setRoot(BrCond); 2848 } else { 2849 // Avoid emitting unnecessary branches to the next block. 2850 if (JT.MBB != NextBlock(SwitchBB)) 2851 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2852 DAG.getBasicBlock(JT.MBB))); 2853 else 2854 DAG.setRoot(CopyTo); 2855 } 2856 } 2857 2858 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2859 /// variable if there exists one. 2860 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2861 SDValue &Chain) { 2862 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2863 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2864 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2865 MachineFunction &MF = DAG.getMachineFunction(); 2866 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2867 MachineSDNode *Node = 2868 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2869 if (Global) { 2870 MachinePointerInfo MPInfo(Global); 2871 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2872 MachineMemOperand::MODereferenceable; 2873 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2874 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2875 DAG.setNodeMemRefs(Node, {MemRef}); 2876 } 2877 if (PtrTy != PtrMemTy) 2878 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2879 return SDValue(Node, 0); 2880 } 2881 2882 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2883 /// tail spliced into a stack protector check success bb. 2884 /// 2885 /// For a high level explanation of how this fits into the stack protector 2886 /// generation see the comment on the declaration of class 2887 /// StackProtectorDescriptor. 2888 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2889 MachineBasicBlock *ParentBB) { 2890 2891 // First create the loads to the guard/stack slot for the comparison. 2892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2893 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2894 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2895 2896 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2897 int FI = MFI.getStackProtectorIndex(); 2898 2899 SDValue Guard; 2900 SDLoc dl = getCurSDLoc(); 2901 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2902 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2903 Align Align = 2904 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 2905 2906 // Generate code to load the content of the guard slot. 2907 SDValue GuardVal = DAG.getLoad( 2908 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2909 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2910 MachineMemOperand::MOVolatile); 2911 2912 if (TLI.useStackGuardXorFP()) 2913 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2914 2915 // Retrieve guard check function, nullptr if instrumentation is inlined. 2916 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2917 // The target provides a guard check function to validate the guard value. 2918 // Generate a call to that function with the content of the guard slot as 2919 // argument. 2920 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2921 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2922 2923 TargetLowering::ArgListTy Args; 2924 TargetLowering::ArgListEntry Entry; 2925 Entry.Node = GuardVal; 2926 Entry.Ty = FnTy->getParamType(0); 2927 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2928 Entry.IsInReg = true; 2929 Args.push_back(Entry); 2930 2931 TargetLowering::CallLoweringInfo CLI(DAG); 2932 CLI.setDebugLoc(getCurSDLoc()) 2933 .setChain(DAG.getEntryNode()) 2934 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2935 getValue(GuardCheckFn), std::move(Args)); 2936 2937 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2938 DAG.setRoot(Result.second); 2939 return; 2940 } 2941 2942 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2943 // Otherwise, emit a volatile load to retrieve the stack guard value. 2944 SDValue Chain = DAG.getEntryNode(); 2945 if (TLI.useLoadStackGuardNode()) { 2946 Guard = getLoadStackGuard(DAG, dl, Chain); 2947 } else { 2948 const Value *IRGuard = TLI.getSDagStackGuard(M); 2949 SDValue GuardPtr = getValue(IRGuard); 2950 2951 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2952 MachinePointerInfo(IRGuard, 0), Align, 2953 MachineMemOperand::MOVolatile); 2954 } 2955 2956 // Perform the comparison via a getsetcc. 2957 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2958 *DAG.getContext(), 2959 Guard.getValueType()), 2960 Guard, GuardVal, ISD::SETNE); 2961 2962 // If the guard/stackslot do not equal, branch to failure MBB. 2963 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2964 MVT::Other, GuardVal.getOperand(0), 2965 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2966 // Otherwise branch to success MBB. 2967 SDValue Br = DAG.getNode(ISD::BR, dl, 2968 MVT::Other, BrCond, 2969 DAG.getBasicBlock(SPD.getSuccessMBB())); 2970 2971 DAG.setRoot(Br); 2972 } 2973 2974 /// Codegen the failure basic block for a stack protector check. 2975 /// 2976 /// A failure stack protector machine basic block consists simply of a call to 2977 /// __stack_chk_fail(). 2978 /// 2979 /// For a high level explanation of how this fits into the stack protector 2980 /// generation see the comment on the declaration of class 2981 /// StackProtectorDescriptor. 2982 void 2983 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2984 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2985 TargetLowering::MakeLibCallOptions CallOptions; 2986 CallOptions.setDiscardResult(true); 2987 SDValue Chain = 2988 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2989 std::nullopt, CallOptions, getCurSDLoc()) 2990 .second; 2991 // On PS4/PS5, the "return address" must still be within the calling 2992 // function, even if it's at the very end, so emit an explicit TRAP here. 2993 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2994 if (TM.getTargetTriple().isPS()) 2995 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2996 // WebAssembly needs an unreachable instruction after a non-returning call, 2997 // because the function return type can be different from __stack_chk_fail's 2998 // return type (void). 2999 if (TM.getTargetTriple().isWasm()) 3000 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3001 3002 DAG.setRoot(Chain); 3003 } 3004 3005 /// visitBitTestHeader - This function emits necessary code to produce value 3006 /// suitable for "bit tests" 3007 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3008 MachineBasicBlock *SwitchBB) { 3009 SDLoc dl = getCurSDLoc(); 3010 3011 // Subtract the minimum value. 3012 SDValue SwitchOp = getValue(B.SValue); 3013 EVT VT = SwitchOp.getValueType(); 3014 SDValue RangeSub = 3015 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3016 3017 // Determine the type of the test operands. 3018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3019 bool UsePtrType = false; 3020 if (!TLI.isTypeLegal(VT)) { 3021 UsePtrType = true; 3022 } else { 3023 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3024 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3025 // Switch table case range are encoded into series of masks. 3026 // Just use pointer type, it's guaranteed to fit. 3027 UsePtrType = true; 3028 break; 3029 } 3030 } 3031 SDValue Sub = RangeSub; 3032 if (UsePtrType) { 3033 VT = TLI.getPointerTy(DAG.getDataLayout()); 3034 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3035 } 3036 3037 B.RegVT = VT.getSimpleVT(); 3038 B.Reg = FuncInfo.CreateReg(B.RegVT); 3039 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3040 3041 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3042 3043 if (!B.FallthroughUnreachable) 3044 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3045 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3046 SwitchBB->normalizeSuccProbs(); 3047 3048 SDValue Root = CopyTo; 3049 if (!B.FallthroughUnreachable) { 3050 // Conditional branch to the default block. 3051 SDValue RangeCmp = DAG.getSetCC(dl, 3052 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3053 RangeSub.getValueType()), 3054 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3055 ISD::SETUGT); 3056 3057 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3058 DAG.getBasicBlock(B.Default)); 3059 } 3060 3061 // Avoid emitting unnecessary branches to the next block. 3062 if (MBB != NextBlock(SwitchBB)) 3063 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3064 3065 DAG.setRoot(Root); 3066 } 3067 3068 /// visitBitTestCase - this function produces one "bit test" 3069 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3070 MachineBasicBlock* NextMBB, 3071 BranchProbability BranchProbToNext, 3072 unsigned Reg, 3073 BitTestCase &B, 3074 MachineBasicBlock *SwitchBB) { 3075 SDLoc dl = getCurSDLoc(); 3076 MVT VT = BB.RegVT; 3077 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3078 SDValue Cmp; 3079 unsigned PopCount = llvm::popcount(B.Mask); 3080 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3081 if (PopCount == 1) { 3082 // Testing for a single bit; just compare the shift count with what it 3083 // would need to be to shift a 1 bit in that position. 3084 Cmp = DAG.getSetCC( 3085 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3086 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3087 ISD::SETEQ); 3088 } else if (PopCount == BB.Range) { 3089 // There is only one zero bit in the range, test for it directly. 3090 Cmp = DAG.getSetCC( 3091 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3092 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3093 } else { 3094 // Make desired shift 3095 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3096 DAG.getConstant(1, dl, VT), ShiftOp); 3097 3098 // Emit bit tests and jumps 3099 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3100 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3101 Cmp = DAG.getSetCC( 3102 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3103 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3104 } 3105 3106 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3107 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3108 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3109 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3110 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3111 // one as they are relative probabilities (and thus work more like weights), 3112 // and hence we need to normalize them to let the sum of them become one. 3113 SwitchBB->normalizeSuccProbs(); 3114 3115 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3116 MVT::Other, getControlRoot(), 3117 Cmp, DAG.getBasicBlock(B.TargetBB)); 3118 3119 // Avoid emitting unnecessary branches to the next block. 3120 if (NextMBB != NextBlock(SwitchBB)) 3121 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3122 DAG.getBasicBlock(NextMBB)); 3123 3124 DAG.setRoot(BrAnd); 3125 } 3126 3127 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3128 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3129 3130 // Retrieve successors. Look through artificial IR level blocks like 3131 // catchswitch for successors. 3132 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3133 const BasicBlock *EHPadBB = I.getSuccessor(1); 3134 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3135 3136 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3137 // have to do anything here to lower funclet bundles. 3138 assert(!I.hasOperandBundlesOtherThan( 3139 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3140 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3141 LLVMContext::OB_cfguardtarget, 3142 LLVMContext::OB_clang_arc_attachedcall}) && 3143 "Cannot lower invokes with arbitrary operand bundles yet!"); 3144 3145 const Value *Callee(I.getCalledOperand()); 3146 const Function *Fn = dyn_cast<Function>(Callee); 3147 if (isa<InlineAsm>(Callee)) 3148 visitInlineAsm(I, EHPadBB); 3149 else if (Fn && Fn->isIntrinsic()) { 3150 switch (Fn->getIntrinsicID()) { 3151 default: 3152 llvm_unreachable("Cannot invoke this intrinsic"); 3153 case Intrinsic::donothing: 3154 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3155 case Intrinsic::seh_try_begin: 3156 case Intrinsic::seh_scope_begin: 3157 case Intrinsic::seh_try_end: 3158 case Intrinsic::seh_scope_end: 3159 if (EHPadMBB) 3160 // a block referenced by EH table 3161 // so dtor-funclet not removed by opts 3162 EHPadMBB->setMachineBlockAddressTaken(); 3163 break; 3164 case Intrinsic::experimental_patchpoint_void: 3165 case Intrinsic::experimental_patchpoint_i64: 3166 visitPatchpoint(I, EHPadBB); 3167 break; 3168 case Intrinsic::experimental_gc_statepoint: 3169 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3170 break; 3171 case Intrinsic::wasm_rethrow: { 3172 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3173 // special because it can be invoked, so we manually lower it to a DAG 3174 // node here. 3175 SmallVector<SDValue, 8> Ops; 3176 Ops.push_back(getRoot()); // inchain 3177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3178 Ops.push_back( 3179 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3180 TLI.getPointerTy(DAG.getDataLayout()))); 3181 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3182 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3183 break; 3184 } 3185 } 3186 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3187 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3188 // Eventually we will support lowering the @llvm.experimental.deoptimize 3189 // intrinsic, and right now there are no plans to support other intrinsics 3190 // with deopt state. 3191 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3192 } else { 3193 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3194 } 3195 3196 // If the value of the invoke is used outside of its defining block, make it 3197 // available as a virtual register. 3198 // We already took care of the exported value for the statepoint instruction 3199 // during call to the LowerStatepoint. 3200 if (!isa<GCStatepointInst>(I)) { 3201 CopyToExportRegsIfNeeded(&I); 3202 } 3203 3204 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3205 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3206 BranchProbability EHPadBBProb = 3207 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3208 : BranchProbability::getZero(); 3209 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3210 3211 // Update successor info. 3212 addSuccessorWithProb(InvokeMBB, Return); 3213 for (auto &UnwindDest : UnwindDests) { 3214 UnwindDest.first->setIsEHPad(); 3215 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3216 } 3217 InvokeMBB->normalizeSuccProbs(); 3218 3219 // Drop into normal successor. 3220 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3221 DAG.getBasicBlock(Return))); 3222 } 3223 3224 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3225 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3226 3227 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3228 // have to do anything here to lower funclet bundles. 3229 assert(!I.hasOperandBundlesOtherThan( 3230 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3231 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3232 3233 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3234 visitInlineAsm(I); 3235 CopyToExportRegsIfNeeded(&I); 3236 3237 // Retrieve successors. 3238 SmallPtrSet<BasicBlock *, 8> Dests; 3239 Dests.insert(I.getDefaultDest()); 3240 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3241 3242 // Update successor info. 3243 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3244 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3245 BasicBlock *Dest = I.getIndirectDest(i); 3246 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3247 Target->setIsInlineAsmBrIndirectTarget(); 3248 Target->setMachineBlockAddressTaken(); 3249 Target->setLabelMustBeEmitted(); 3250 // Don't add duplicate machine successors. 3251 if (Dests.insert(Dest).second) 3252 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3253 } 3254 CallBrMBB->normalizeSuccProbs(); 3255 3256 // Drop into default successor. 3257 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3258 MVT::Other, getControlRoot(), 3259 DAG.getBasicBlock(Return))); 3260 } 3261 3262 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3263 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3264 } 3265 3266 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3267 assert(FuncInfo.MBB->isEHPad() && 3268 "Call to landingpad not in landing pad!"); 3269 3270 // If there aren't registers to copy the values into (e.g., during SjLj 3271 // exceptions), then don't bother to create these DAG nodes. 3272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3273 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3274 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3275 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3276 return; 3277 3278 // If landingpad's return type is token type, we don't create DAG nodes 3279 // for its exception pointer and selector value. The extraction of exception 3280 // pointer or selector value from token type landingpads is not currently 3281 // supported. 3282 if (LP.getType()->isTokenTy()) 3283 return; 3284 3285 SmallVector<EVT, 2> ValueVTs; 3286 SDLoc dl = getCurSDLoc(); 3287 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3288 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3289 3290 // Get the two live-in registers as SDValues. The physregs have already been 3291 // copied into virtual registers. 3292 SDValue Ops[2]; 3293 if (FuncInfo.ExceptionPointerVirtReg) { 3294 Ops[0] = DAG.getZExtOrTrunc( 3295 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3296 FuncInfo.ExceptionPointerVirtReg, 3297 TLI.getPointerTy(DAG.getDataLayout())), 3298 dl, ValueVTs[0]); 3299 } else { 3300 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3301 } 3302 Ops[1] = DAG.getZExtOrTrunc( 3303 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3304 FuncInfo.ExceptionSelectorVirtReg, 3305 TLI.getPointerTy(DAG.getDataLayout())), 3306 dl, ValueVTs[1]); 3307 3308 // Merge into one. 3309 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3310 DAG.getVTList(ValueVTs), Ops); 3311 setValue(&LP, Res); 3312 } 3313 3314 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3315 MachineBasicBlock *Last) { 3316 // Update JTCases. 3317 for (JumpTableBlock &JTB : SL->JTCases) 3318 if (JTB.first.HeaderBB == First) 3319 JTB.first.HeaderBB = Last; 3320 3321 // Update BitTestCases. 3322 for (BitTestBlock &BTB : SL->BitTestCases) 3323 if (BTB.Parent == First) 3324 BTB.Parent = Last; 3325 } 3326 3327 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3328 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3329 3330 // Update machine-CFG edges with unique successors. 3331 SmallSet<BasicBlock*, 32> Done; 3332 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3333 BasicBlock *BB = I.getSuccessor(i); 3334 bool Inserted = Done.insert(BB).second; 3335 if (!Inserted) 3336 continue; 3337 3338 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3339 addSuccessorWithProb(IndirectBrMBB, Succ); 3340 } 3341 IndirectBrMBB->normalizeSuccProbs(); 3342 3343 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3344 MVT::Other, getControlRoot(), 3345 getValue(I.getAddress()))); 3346 } 3347 3348 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3349 if (!DAG.getTarget().Options.TrapUnreachable) 3350 return; 3351 3352 // We may be able to ignore unreachable behind a noreturn call. 3353 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3354 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3355 if (Call->doesNotReturn()) 3356 return; 3357 } 3358 } 3359 3360 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3361 } 3362 3363 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3364 SDNodeFlags Flags; 3365 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3366 Flags.copyFMF(*FPOp); 3367 3368 SDValue Op = getValue(I.getOperand(0)); 3369 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3370 Op, Flags); 3371 setValue(&I, UnNodeValue); 3372 } 3373 3374 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3375 SDNodeFlags Flags; 3376 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3377 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3378 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3379 } 3380 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3381 Flags.setExact(ExactOp->isExact()); 3382 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3383 Flags.setDisjoint(DisjointOp->isDisjoint()); 3384 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3385 Flags.copyFMF(*FPOp); 3386 3387 SDValue Op1 = getValue(I.getOperand(0)); 3388 SDValue Op2 = getValue(I.getOperand(1)); 3389 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3390 Op1, Op2, Flags); 3391 setValue(&I, BinNodeValue); 3392 } 3393 3394 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3395 SDValue Op1 = getValue(I.getOperand(0)); 3396 SDValue Op2 = getValue(I.getOperand(1)); 3397 3398 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3399 Op1.getValueType(), DAG.getDataLayout()); 3400 3401 // Coerce the shift amount to the right type if we can. This exposes the 3402 // truncate or zext to optimization early. 3403 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3404 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3405 "Unexpected shift type"); 3406 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3407 } 3408 3409 bool nuw = false; 3410 bool nsw = false; 3411 bool exact = false; 3412 3413 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3414 3415 if (const OverflowingBinaryOperator *OFBinOp = 3416 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3417 nuw = OFBinOp->hasNoUnsignedWrap(); 3418 nsw = OFBinOp->hasNoSignedWrap(); 3419 } 3420 if (const PossiblyExactOperator *ExactOp = 3421 dyn_cast<const PossiblyExactOperator>(&I)) 3422 exact = ExactOp->isExact(); 3423 } 3424 SDNodeFlags Flags; 3425 Flags.setExact(exact); 3426 Flags.setNoSignedWrap(nsw); 3427 Flags.setNoUnsignedWrap(nuw); 3428 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3429 Flags); 3430 setValue(&I, Res); 3431 } 3432 3433 void SelectionDAGBuilder::visitSDiv(const User &I) { 3434 SDValue Op1 = getValue(I.getOperand(0)); 3435 SDValue Op2 = getValue(I.getOperand(1)); 3436 3437 SDNodeFlags Flags; 3438 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3439 cast<PossiblyExactOperator>(&I)->isExact()); 3440 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3441 Op2, Flags)); 3442 } 3443 3444 void SelectionDAGBuilder::visitICmp(const User &I) { 3445 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3446 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3447 predicate = IC->getPredicate(); 3448 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3449 predicate = ICmpInst::Predicate(IC->getPredicate()); 3450 SDValue Op1 = getValue(I.getOperand(0)); 3451 SDValue Op2 = getValue(I.getOperand(1)); 3452 ISD::CondCode Opcode = getICmpCondCode(predicate); 3453 3454 auto &TLI = DAG.getTargetLoweringInfo(); 3455 EVT MemVT = 3456 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3457 3458 // If a pointer's DAG type is larger than its memory type then the DAG values 3459 // are zero-extended. This breaks signed comparisons so truncate back to the 3460 // underlying type before doing the compare. 3461 if (Op1.getValueType() != MemVT) { 3462 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3463 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3464 } 3465 3466 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3467 I.getType()); 3468 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3469 } 3470 3471 void SelectionDAGBuilder::visitFCmp(const User &I) { 3472 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3473 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3474 predicate = FC->getPredicate(); 3475 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3476 predicate = FCmpInst::Predicate(FC->getPredicate()); 3477 SDValue Op1 = getValue(I.getOperand(0)); 3478 SDValue Op2 = getValue(I.getOperand(1)); 3479 3480 ISD::CondCode Condition = getFCmpCondCode(predicate); 3481 auto *FPMO = cast<FPMathOperator>(&I); 3482 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3483 Condition = getFCmpCodeWithoutNaN(Condition); 3484 3485 SDNodeFlags Flags; 3486 Flags.copyFMF(*FPMO); 3487 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3488 3489 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3490 I.getType()); 3491 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3492 } 3493 3494 // Check if the condition of the select has one use or two users that are both 3495 // selects with the same condition. 3496 static bool hasOnlySelectUsers(const Value *Cond) { 3497 return llvm::all_of(Cond->users(), [](const Value *V) { 3498 return isa<SelectInst>(V); 3499 }); 3500 } 3501 3502 void SelectionDAGBuilder::visitSelect(const User &I) { 3503 SmallVector<EVT, 4> ValueVTs; 3504 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3505 ValueVTs); 3506 unsigned NumValues = ValueVTs.size(); 3507 if (NumValues == 0) return; 3508 3509 SmallVector<SDValue, 4> Values(NumValues); 3510 SDValue Cond = getValue(I.getOperand(0)); 3511 SDValue LHSVal = getValue(I.getOperand(1)); 3512 SDValue RHSVal = getValue(I.getOperand(2)); 3513 SmallVector<SDValue, 1> BaseOps(1, Cond); 3514 ISD::NodeType OpCode = 3515 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3516 3517 bool IsUnaryAbs = false; 3518 bool Negate = false; 3519 3520 SDNodeFlags Flags; 3521 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3522 Flags.copyFMF(*FPOp); 3523 3524 Flags.setUnpredictable( 3525 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3526 3527 // Min/max matching is only viable if all output VTs are the same. 3528 if (all_equal(ValueVTs)) { 3529 EVT VT = ValueVTs[0]; 3530 LLVMContext &Ctx = *DAG.getContext(); 3531 auto &TLI = DAG.getTargetLoweringInfo(); 3532 3533 // We care about the legality of the operation after it has been type 3534 // legalized. 3535 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3536 VT = TLI.getTypeToTransformTo(Ctx, VT); 3537 3538 // If the vselect is legal, assume we want to leave this as a vector setcc + 3539 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3540 // min/max is legal on the scalar type. 3541 bool UseScalarMinMax = VT.isVector() && 3542 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3543 3544 // ValueTracking's select pattern matching does not account for -0.0, 3545 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3546 // -0.0 is less than +0.0. 3547 Value *LHS, *RHS; 3548 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3549 ISD::NodeType Opc = ISD::DELETED_NODE; 3550 switch (SPR.Flavor) { 3551 case SPF_UMAX: Opc = ISD::UMAX; break; 3552 case SPF_UMIN: Opc = ISD::UMIN; break; 3553 case SPF_SMAX: Opc = ISD::SMAX; break; 3554 case SPF_SMIN: Opc = ISD::SMIN; break; 3555 case SPF_FMINNUM: 3556 switch (SPR.NaNBehavior) { 3557 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3558 case SPNB_RETURNS_NAN: break; 3559 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3560 case SPNB_RETURNS_ANY: 3561 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3562 (UseScalarMinMax && 3563 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3564 Opc = ISD::FMINNUM; 3565 break; 3566 } 3567 break; 3568 case SPF_FMAXNUM: 3569 switch (SPR.NaNBehavior) { 3570 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3571 case SPNB_RETURNS_NAN: break; 3572 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3573 case SPNB_RETURNS_ANY: 3574 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3575 (UseScalarMinMax && 3576 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3577 Opc = ISD::FMAXNUM; 3578 break; 3579 } 3580 break; 3581 case SPF_NABS: 3582 Negate = true; 3583 [[fallthrough]]; 3584 case SPF_ABS: 3585 IsUnaryAbs = true; 3586 Opc = ISD::ABS; 3587 break; 3588 default: break; 3589 } 3590 3591 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3592 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3593 (UseScalarMinMax && 3594 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3595 // If the underlying comparison instruction is used by any other 3596 // instruction, the consumed instructions won't be destroyed, so it is 3597 // not profitable to convert to a min/max. 3598 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3599 OpCode = Opc; 3600 LHSVal = getValue(LHS); 3601 RHSVal = getValue(RHS); 3602 BaseOps.clear(); 3603 } 3604 3605 if (IsUnaryAbs) { 3606 OpCode = Opc; 3607 LHSVal = getValue(LHS); 3608 BaseOps.clear(); 3609 } 3610 } 3611 3612 if (IsUnaryAbs) { 3613 for (unsigned i = 0; i != NumValues; ++i) { 3614 SDLoc dl = getCurSDLoc(); 3615 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3616 Values[i] = 3617 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3618 if (Negate) 3619 Values[i] = DAG.getNegative(Values[i], dl, VT); 3620 } 3621 } else { 3622 for (unsigned i = 0; i != NumValues; ++i) { 3623 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3624 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3625 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3626 Values[i] = DAG.getNode( 3627 OpCode, getCurSDLoc(), 3628 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3629 } 3630 } 3631 3632 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3633 DAG.getVTList(ValueVTs), Values)); 3634 } 3635 3636 void SelectionDAGBuilder::visitTrunc(const User &I) { 3637 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3638 SDValue N = getValue(I.getOperand(0)); 3639 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3640 I.getType()); 3641 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3642 } 3643 3644 void SelectionDAGBuilder::visitZExt(const User &I) { 3645 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3646 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3647 SDValue N = getValue(I.getOperand(0)); 3648 auto &TLI = DAG.getTargetLoweringInfo(); 3649 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3650 3651 SDNodeFlags Flags; 3652 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3653 Flags.setNonNeg(PNI->hasNonNeg()); 3654 3655 // Eagerly use nonneg information to canonicalize towards sign_extend if 3656 // that is the target's preference. 3657 // TODO: Let the target do this later. 3658 if (Flags.hasNonNeg() && 3659 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3660 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3661 return; 3662 } 3663 3664 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3665 } 3666 3667 void SelectionDAGBuilder::visitSExt(const User &I) { 3668 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3669 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3670 SDValue N = getValue(I.getOperand(0)); 3671 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3672 I.getType()); 3673 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3674 } 3675 3676 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3677 // FPTrunc is never a no-op cast, no need to check 3678 SDValue N = getValue(I.getOperand(0)); 3679 SDLoc dl = getCurSDLoc(); 3680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3681 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3682 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3683 DAG.getTargetConstant( 3684 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3685 } 3686 3687 void SelectionDAGBuilder::visitFPExt(const User &I) { 3688 // FPExt is never a no-op cast, no need to check 3689 SDValue N = getValue(I.getOperand(0)); 3690 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3691 I.getType()); 3692 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3693 } 3694 3695 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3696 // FPToUI is never a no-op cast, no need to check 3697 SDValue N = getValue(I.getOperand(0)); 3698 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3699 I.getType()); 3700 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3701 } 3702 3703 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3704 // FPToSI is never a no-op cast, no need to check 3705 SDValue N = getValue(I.getOperand(0)); 3706 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3707 I.getType()); 3708 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3709 } 3710 3711 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3712 // UIToFP is never a no-op cast, no need to check 3713 SDValue N = getValue(I.getOperand(0)); 3714 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3715 I.getType()); 3716 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3717 } 3718 3719 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3720 // SIToFP is never a no-op cast, no need to check 3721 SDValue N = getValue(I.getOperand(0)); 3722 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3723 I.getType()); 3724 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3725 } 3726 3727 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3728 // What to do depends on the size of the integer and the size of the pointer. 3729 // We can either truncate, zero extend, or no-op, accordingly. 3730 SDValue N = getValue(I.getOperand(0)); 3731 auto &TLI = DAG.getTargetLoweringInfo(); 3732 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3733 I.getType()); 3734 EVT PtrMemVT = 3735 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3736 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3737 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3738 setValue(&I, N); 3739 } 3740 3741 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3742 // What to do depends on the size of the integer and the size of the pointer. 3743 // We can either truncate, zero extend, or no-op, accordingly. 3744 SDValue N = getValue(I.getOperand(0)); 3745 auto &TLI = DAG.getTargetLoweringInfo(); 3746 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3747 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3748 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3749 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3750 setValue(&I, N); 3751 } 3752 3753 void SelectionDAGBuilder::visitBitCast(const User &I) { 3754 SDValue N = getValue(I.getOperand(0)); 3755 SDLoc dl = getCurSDLoc(); 3756 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3757 I.getType()); 3758 3759 // BitCast assures us that source and destination are the same size so this is 3760 // either a BITCAST or a no-op. 3761 if (DestVT != N.getValueType()) 3762 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3763 DestVT, N)); // convert types. 3764 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3765 // might fold any kind of constant expression to an integer constant and that 3766 // is not what we are looking for. Only recognize a bitcast of a genuine 3767 // constant integer as an opaque constant. 3768 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3769 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3770 /*isOpaque*/true)); 3771 else 3772 setValue(&I, N); // noop cast. 3773 } 3774 3775 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3777 const Value *SV = I.getOperand(0); 3778 SDValue N = getValue(SV); 3779 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3780 3781 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3782 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3783 3784 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3785 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3786 3787 setValue(&I, N); 3788 } 3789 3790 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3792 SDValue InVec = getValue(I.getOperand(0)); 3793 SDValue InVal = getValue(I.getOperand(1)); 3794 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3795 TLI.getVectorIdxTy(DAG.getDataLayout())); 3796 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3797 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3798 InVec, InVal, InIdx)); 3799 } 3800 3801 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3803 SDValue InVec = getValue(I.getOperand(0)); 3804 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3805 TLI.getVectorIdxTy(DAG.getDataLayout())); 3806 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3807 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3808 InVec, InIdx)); 3809 } 3810 3811 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3812 SDValue Src1 = getValue(I.getOperand(0)); 3813 SDValue Src2 = getValue(I.getOperand(1)); 3814 ArrayRef<int> Mask; 3815 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3816 Mask = SVI->getShuffleMask(); 3817 else 3818 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3819 SDLoc DL = getCurSDLoc(); 3820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3821 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3822 EVT SrcVT = Src1.getValueType(); 3823 3824 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3825 VT.isScalableVector()) { 3826 // Canonical splat form of first element of first input vector. 3827 SDValue FirstElt = 3828 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3829 DAG.getVectorIdxConstant(0, DL)); 3830 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3831 return; 3832 } 3833 3834 // For now, we only handle splats for scalable vectors. 3835 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3836 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3837 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3838 3839 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3840 unsigned MaskNumElts = Mask.size(); 3841 3842 if (SrcNumElts == MaskNumElts) { 3843 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3844 return; 3845 } 3846 3847 // Normalize the shuffle vector since mask and vector length don't match. 3848 if (SrcNumElts < MaskNumElts) { 3849 // Mask is longer than the source vectors. We can use concatenate vector to 3850 // make the mask and vectors lengths match. 3851 3852 if (MaskNumElts % SrcNumElts == 0) { 3853 // Mask length is a multiple of the source vector length. 3854 // Check if the shuffle is some kind of concatenation of the input 3855 // vectors. 3856 unsigned NumConcat = MaskNumElts / SrcNumElts; 3857 bool IsConcat = true; 3858 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3859 for (unsigned i = 0; i != MaskNumElts; ++i) { 3860 int Idx = Mask[i]; 3861 if (Idx < 0) 3862 continue; 3863 // Ensure the indices in each SrcVT sized piece are sequential and that 3864 // the same source is used for the whole piece. 3865 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3866 (ConcatSrcs[i / SrcNumElts] >= 0 && 3867 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3868 IsConcat = false; 3869 break; 3870 } 3871 // Remember which source this index came from. 3872 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3873 } 3874 3875 // The shuffle is concatenating multiple vectors together. Just emit 3876 // a CONCAT_VECTORS operation. 3877 if (IsConcat) { 3878 SmallVector<SDValue, 8> ConcatOps; 3879 for (auto Src : ConcatSrcs) { 3880 if (Src < 0) 3881 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3882 else if (Src == 0) 3883 ConcatOps.push_back(Src1); 3884 else 3885 ConcatOps.push_back(Src2); 3886 } 3887 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3888 return; 3889 } 3890 } 3891 3892 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3893 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3894 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3895 PaddedMaskNumElts); 3896 3897 // Pad both vectors with undefs to make them the same length as the mask. 3898 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3899 3900 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3901 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3902 MOps1[0] = Src1; 3903 MOps2[0] = Src2; 3904 3905 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3906 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3907 3908 // Readjust mask for new input vector length. 3909 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3910 for (unsigned i = 0; i != MaskNumElts; ++i) { 3911 int Idx = Mask[i]; 3912 if (Idx >= (int)SrcNumElts) 3913 Idx -= SrcNumElts - PaddedMaskNumElts; 3914 MappedOps[i] = Idx; 3915 } 3916 3917 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3918 3919 // If the concatenated vector was padded, extract a subvector with the 3920 // correct number of elements. 3921 if (MaskNumElts != PaddedMaskNumElts) 3922 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3923 DAG.getVectorIdxConstant(0, DL)); 3924 3925 setValue(&I, Result); 3926 return; 3927 } 3928 3929 if (SrcNumElts > MaskNumElts) { 3930 // Analyze the access pattern of the vector to see if we can extract 3931 // two subvectors and do the shuffle. 3932 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3933 bool CanExtract = true; 3934 for (int Idx : Mask) { 3935 unsigned Input = 0; 3936 if (Idx < 0) 3937 continue; 3938 3939 if (Idx >= (int)SrcNumElts) { 3940 Input = 1; 3941 Idx -= SrcNumElts; 3942 } 3943 3944 // If all the indices come from the same MaskNumElts sized portion of 3945 // the sources we can use extract. Also make sure the extract wouldn't 3946 // extract past the end of the source. 3947 int NewStartIdx = alignDown(Idx, MaskNumElts); 3948 if (NewStartIdx + MaskNumElts > SrcNumElts || 3949 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3950 CanExtract = false; 3951 // Make sure we always update StartIdx as we use it to track if all 3952 // elements are undef. 3953 StartIdx[Input] = NewStartIdx; 3954 } 3955 3956 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3957 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3958 return; 3959 } 3960 if (CanExtract) { 3961 // Extract appropriate subvector and generate a vector shuffle 3962 for (unsigned Input = 0; Input < 2; ++Input) { 3963 SDValue &Src = Input == 0 ? Src1 : Src2; 3964 if (StartIdx[Input] < 0) 3965 Src = DAG.getUNDEF(VT); 3966 else { 3967 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3968 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3969 } 3970 } 3971 3972 // Calculate new mask. 3973 SmallVector<int, 8> MappedOps(Mask); 3974 for (int &Idx : MappedOps) { 3975 if (Idx >= (int)SrcNumElts) 3976 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3977 else if (Idx >= 0) 3978 Idx -= StartIdx[0]; 3979 } 3980 3981 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3982 return; 3983 } 3984 } 3985 3986 // We can't use either concat vectors or extract subvectors so fall back to 3987 // replacing the shuffle with extract and build vector. 3988 // to insert and build vector. 3989 EVT EltVT = VT.getVectorElementType(); 3990 SmallVector<SDValue,8> Ops; 3991 for (int Idx : Mask) { 3992 SDValue Res; 3993 3994 if (Idx < 0) { 3995 Res = DAG.getUNDEF(EltVT); 3996 } else { 3997 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3998 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3999 4000 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4001 DAG.getVectorIdxConstant(Idx, DL)); 4002 } 4003 4004 Ops.push_back(Res); 4005 } 4006 4007 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4008 } 4009 4010 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4011 ArrayRef<unsigned> Indices = I.getIndices(); 4012 const Value *Op0 = I.getOperand(0); 4013 const Value *Op1 = I.getOperand(1); 4014 Type *AggTy = I.getType(); 4015 Type *ValTy = Op1->getType(); 4016 bool IntoUndef = isa<UndefValue>(Op0); 4017 bool FromUndef = isa<UndefValue>(Op1); 4018 4019 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4020 4021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4022 SmallVector<EVT, 4> AggValueVTs; 4023 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4024 SmallVector<EVT, 4> ValValueVTs; 4025 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4026 4027 unsigned NumAggValues = AggValueVTs.size(); 4028 unsigned NumValValues = ValValueVTs.size(); 4029 SmallVector<SDValue, 4> Values(NumAggValues); 4030 4031 // Ignore an insertvalue that produces an empty object 4032 if (!NumAggValues) { 4033 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4034 return; 4035 } 4036 4037 SDValue Agg = getValue(Op0); 4038 unsigned i = 0; 4039 // Copy the beginning value(s) from the original aggregate. 4040 for (; i != LinearIndex; ++i) 4041 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4042 SDValue(Agg.getNode(), Agg.getResNo() + i); 4043 // Copy values from the inserted value(s). 4044 if (NumValValues) { 4045 SDValue Val = getValue(Op1); 4046 for (; i != LinearIndex + NumValValues; ++i) 4047 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4048 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4049 } 4050 // Copy remaining value(s) from the original aggregate. 4051 for (; i != NumAggValues; ++i) 4052 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4053 SDValue(Agg.getNode(), Agg.getResNo() + i); 4054 4055 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4056 DAG.getVTList(AggValueVTs), Values)); 4057 } 4058 4059 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4060 ArrayRef<unsigned> Indices = I.getIndices(); 4061 const Value *Op0 = I.getOperand(0); 4062 Type *AggTy = Op0->getType(); 4063 Type *ValTy = I.getType(); 4064 bool OutOfUndef = isa<UndefValue>(Op0); 4065 4066 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4067 4068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4069 SmallVector<EVT, 4> ValValueVTs; 4070 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4071 4072 unsigned NumValValues = ValValueVTs.size(); 4073 4074 // Ignore a extractvalue that produces an empty object 4075 if (!NumValValues) { 4076 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4077 return; 4078 } 4079 4080 SmallVector<SDValue, 4> Values(NumValValues); 4081 4082 SDValue Agg = getValue(Op0); 4083 // Copy out the selected value(s). 4084 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4085 Values[i - LinearIndex] = 4086 OutOfUndef ? 4087 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4088 SDValue(Agg.getNode(), Agg.getResNo() + i); 4089 4090 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4091 DAG.getVTList(ValValueVTs), Values)); 4092 } 4093 4094 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4095 Value *Op0 = I.getOperand(0); 4096 // Note that the pointer operand may be a vector of pointers. Take the scalar 4097 // element which holds a pointer. 4098 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4099 SDValue N = getValue(Op0); 4100 SDLoc dl = getCurSDLoc(); 4101 auto &TLI = DAG.getTargetLoweringInfo(); 4102 4103 // Normalize Vector GEP - all scalar operands should be converted to the 4104 // splat vector. 4105 bool IsVectorGEP = I.getType()->isVectorTy(); 4106 ElementCount VectorElementCount = 4107 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4108 : ElementCount::getFixed(0); 4109 4110 if (IsVectorGEP && !N.getValueType().isVector()) { 4111 LLVMContext &Context = *DAG.getContext(); 4112 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4113 N = DAG.getSplat(VT, dl, N); 4114 } 4115 4116 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4117 GTI != E; ++GTI) { 4118 const Value *Idx = GTI.getOperand(); 4119 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4120 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4121 if (Field) { 4122 // N = N + Offset 4123 uint64_t Offset = 4124 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4125 4126 // In an inbounds GEP with an offset that is nonnegative even when 4127 // interpreted as signed, assume there is no unsigned overflow. 4128 SDNodeFlags Flags; 4129 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4130 Flags.setNoUnsignedWrap(true); 4131 4132 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4133 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4134 } 4135 } else { 4136 // IdxSize is the width of the arithmetic according to IR semantics. 4137 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4138 // (and fix up the result later). 4139 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4140 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4141 TypeSize ElementSize = 4142 GTI.getSequentialElementStride(DAG.getDataLayout()); 4143 // We intentionally mask away the high bits here; ElementSize may not 4144 // fit in IdxTy. 4145 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4146 bool ElementScalable = ElementSize.isScalable(); 4147 4148 // If this is a scalar constant or a splat vector of constants, 4149 // handle it quickly. 4150 const auto *C = dyn_cast<Constant>(Idx); 4151 if (C && isa<VectorType>(C->getType())) 4152 C = C->getSplatValue(); 4153 4154 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4155 if (CI && CI->isZero()) 4156 continue; 4157 if (CI && !ElementScalable) { 4158 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4159 LLVMContext &Context = *DAG.getContext(); 4160 SDValue OffsVal; 4161 if (IsVectorGEP) 4162 OffsVal = DAG.getConstant( 4163 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4164 else 4165 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4166 4167 // In an inbounds GEP with an offset that is nonnegative even when 4168 // interpreted as signed, assume there is no unsigned overflow. 4169 SDNodeFlags Flags; 4170 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4171 Flags.setNoUnsignedWrap(true); 4172 4173 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4174 4175 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4176 continue; 4177 } 4178 4179 // N = N + Idx * ElementMul; 4180 SDValue IdxN = getValue(Idx); 4181 4182 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4183 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4184 VectorElementCount); 4185 IdxN = DAG.getSplat(VT, dl, IdxN); 4186 } 4187 4188 // If the index is smaller or larger than intptr_t, truncate or extend 4189 // it. 4190 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4191 4192 if (ElementScalable) { 4193 EVT VScaleTy = N.getValueType().getScalarType(); 4194 SDValue VScale = DAG.getNode( 4195 ISD::VSCALE, dl, VScaleTy, 4196 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4197 if (IsVectorGEP) 4198 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4199 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4200 } else { 4201 // If this is a multiply by a power of two, turn it into a shl 4202 // immediately. This is a very common case. 4203 if (ElementMul != 1) { 4204 if (ElementMul.isPowerOf2()) { 4205 unsigned Amt = ElementMul.logBase2(); 4206 IdxN = DAG.getNode(ISD::SHL, dl, 4207 N.getValueType(), IdxN, 4208 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4209 } else { 4210 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4211 IdxN.getValueType()); 4212 IdxN = DAG.getNode(ISD::MUL, dl, 4213 N.getValueType(), IdxN, Scale); 4214 } 4215 } 4216 } 4217 4218 N = DAG.getNode(ISD::ADD, dl, 4219 N.getValueType(), N, IdxN); 4220 } 4221 } 4222 4223 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4224 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4225 if (IsVectorGEP) { 4226 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4227 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4228 } 4229 4230 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4231 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4232 4233 setValue(&I, N); 4234 } 4235 4236 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4237 // If this is a fixed sized alloca in the entry block of the function, 4238 // allocate it statically on the stack. 4239 if (FuncInfo.StaticAllocaMap.count(&I)) 4240 return; // getValue will auto-populate this. 4241 4242 SDLoc dl = getCurSDLoc(); 4243 Type *Ty = I.getAllocatedType(); 4244 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4245 auto &DL = DAG.getDataLayout(); 4246 TypeSize TySize = DL.getTypeAllocSize(Ty); 4247 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4248 4249 SDValue AllocSize = getValue(I.getArraySize()); 4250 4251 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4252 if (AllocSize.getValueType() != IntPtr) 4253 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4254 4255 if (TySize.isScalable()) 4256 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4257 DAG.getVScale(dl, IntPtr, 4258 APInt(IntPtr.getScalarSizeInBits(), 4259 TySize.getKnownMinValue()))); 4260 else { 4261 SDValue TySizeValue = 4262 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4263 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4264 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4265 } 4266 4267 // Handle alignment. If the requested alignment is less than or equal to 4268 // the stack alignment, ignore it. If the size is greater than or equal to 4269 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4270 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4271 if (*Alignment <= StackAlign) 4272 Alignment = std::nullopt; 4273 4274 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4275 // Round the size of the allocation up to the stack alignment size 4276 // by add SA-1 to the size. This doesn't overflow because we're computing 4277 // an address inside an alloca. 4278 SDNodeFlags Flags; 4279 Flags.setNoUnsignedWrap(true); 4280 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4281 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4282 4283 // Mask out the low bits for alignment purposes. 4284 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4285 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4286 4287 SDValue Ops[] = { 4288 getRoot(), AllocSize, 4289 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4290 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4291 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4292 setValue(&I, DSA); 4293 DAG.setRoot(DSA.getValue(1)); 4294 4295 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4296 } 4297 4298 static const MDNode *getRangeMetadata(const Instruction &I) { 4299 // If !noundef is not present, then !range violation results in a poison 4300 // value rather than immediate undefined behavior. In theory, transferring 4301 // these annotations to SDAG is fine, but in practice there are key SDAG 4302 // transforms that are known not to be poison-safe, such as folding logical 4303 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4304 // also present. 4305 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4306 return nullptr; 4307 return I.getMetadata(LLVMContext::MD_range); 4308 } 4309 4310 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4311 if (I.isAtomic()) 4312 return visitAtomicLoad(I); 4313 4314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4315 const Value *SV = I.getOperand(0); 4316 if (TLI.supportSwiftError()) { 4317 // Swifterror values can come from either a function parameter with 4318 // swifterror attribute or an alloca with swifterror attribute. 4319 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4320 if (Arg->hasSwiftErrorAttr()) 4321 return visitLoadFromSwiftError(I); 4322 } 4323 4324 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4325 if (Alloca->isSwiftError()) 4326 return visitLoadFromSwiftError(I); 4327 } 4328 } 4329 4330 SDValue Ptr = getValue(SV); 4331 4332 Type *Ty = I.getType(); 4333 SmallVector<EVT, 4> ValueVTs, MemVTs; 4334 SmallVector<TypeSize, 4> Offsets; 4335 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4336 unsigned NumValues = ValueVTs.size(); 4337 if (NumValues == 0) 4338 return; 4339 4340 Align Alignment = I.getAlign(); 4341 AAMDNodes AAInfo = I.getAAMetadata(); 4342 const MDNode *Ranges = getRangeMetadata(I); 4343 bool isVolatile = I.isVolatile(); 4344 MachineMemOperand::Flags MMOFlags = 4345 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4346 4347 SDValue Root; 4348 bool ConstantMemory = false; 4349 if (isVolatile) 4350 // Serialize volatile loads with other side effects. 4351 Root = getRoot(); 4352 else if (NumValues > MaxParallelChains) 4353 Root = getMemoryRoot(); 4354 else if (AA && 4355 AA->pointsToConstantMemory(MemoryLocation( 4356 SV, 4357 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4358 AAInfo))) { 4359 // Do not serialize (non-volatile) loads of constant memory with anything. 4360 Root = DAG.getEntryNode(); 4361 ConstantMemory = true; 4362 MMOFlags |= MachineMemOperand::MOInvariant; 4363 } else { 4364 // Do not serialize non-volatile loads against each other. 4365 Root = DAG.getRoot(); 4366 } 4367 4368 SDLoc dl = getCurSDLoc(); 4369 4370 if (isVolatile) 4371 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4372 4373 SmallVector<SDValue, 4> Values(NumValues); 4374 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4375 4376 unsigned ChainI = 0; 4377 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4378 // Serializing loads here may result in excessive register pressure, and 4379 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4380 // could recover a bit by hoisting nodes upward in the chain by recognizing 4381 // they are side-effect free or do not alias. The optimizer should really 4382 // avoid this case by converting large object/array copies to llvm.memcpy 4383 // (MaxParallelChains should always remain as failsafe). 4384 if (ChainI == MaxParallelChains) { 4385 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4386 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4387 ArrayRef(Chains.data(), ChainI)); 4388 Root = Chain; 4389 ChainI = 0; 4390 } 4391 4392 // TODO: MachinePointerInfo only supports a fixed length offset. 4393 MachinePointerInfo PtrInfo = 4394 !Offsets[i].isScalable() || Offsets[i].isZero() 4395 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4396 : MachinePointerInfo(); 4397 4398 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4399 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4400 MMOFlags, AAInfo, Ranges); 4401 Chains[ChainI] = L.getValue(1); 4402 4403 if (MemVTs[i] != ValueVTs[i]) 4404 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4405 4406 Values[i] = L; 4407 } 4408 4409 if (!ConstantMemory) { 4410 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4411 ArrayRef(Chains.data(), ChainI)); 4412 if (isVolatile) 4413 DAG.setRoot(Chain); 4414 else 4415 PendingLoads.push_back(Chain); 4416 } 4417 4418 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4419 DAG.getVTList(ValueVTs), Values)); 4420 } 4421 4422 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4423 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4424 "call visitStoreToSwiftError when backend supports swifterror"); 4425 4426 SmallVector<EVT, 4> ValueVTs; 4427 SmallVector<uint64_t, 4> Offsets; 4428 const Value *SrcV = I.getOperand(0); 4429 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4430 SrcV->getType(), ValueVTs, &Offsets, 0); 4431 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4432 "expect a single EVT for swifterror"); 4433 4434 SDValue Src = getValue(SrcV); 4435 // Create a virtual register, then update the virtual register. 4436 Register VReg = 4437 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4438 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4439 // Chain can be getRoot or getControlRoot. 4440 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4441 SDValue(Src.getNode(), Src.getResNo())); 4442 DAG.setRoot(CopyNode); 4443 } 4444 4445 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4446 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4447 "call visitLoadFromSwiftError when backend supports swifterror"); 4448 4449 assert(!I.isVolatile() && 4450 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4451 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4452 "Support volatile, non temporal, invariant for load_from_swift_error"); 4453 4454 const Value *SV = I.getOperand(0); 4455 Type *Ty = I.getType(); 4456 assert( 4457 (!AA || 4458 !AA->pointsToConstantMemory(MemoryLocation( 4459 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4460 I.getAAMetadata()))) && 4461 "load_from_swift_error should not be constant memory"); 4462 4463 SmallVector<EVT, 4> ValueVTs; 4464 SmallVector<uint64_t, 4> Offsets; 4465 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4466 ValueVTs, &Offsets, 0); 4467 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4468 "expect a single EVT for swifterror"); 4469 4470 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4471 SDValue L = DAG.getCopyFromReg( 4472 getRoot(), getCurSDLoc(), 4473 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4474 4475 setValue(&I, L); 4476 } 4477 4478 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4479 if (I.isAtomic()) 4480 return visitAtomicStore(I); 4481 4482 const Value *SrcV = I.getOperand(0); 4483 const Value *PtrV = I.getOperand(1); 4484 4485 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4486 if (TLI.supportSwiftError()) { 4487 // Swifterror values can come from either a function parameter with 4488 // swifterror attribute or an alloca with swifterror attribute. 4489 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4490 if (Arg->hasSwiftErrorAttr()) 4491 return visitStoreToSwiftError(I); 4492 } 4493 4494 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4495 if (Alloca->isSwiftError()) 4496 return visitStoreToSwiftError(I); 4497 } 4498 } 4499 4500 SmallVector<EVT, 4> ValueVTs, MemVTs; 4501 SmallVector<TypeSize, 4> Offsets; 4502 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4503 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4504 unsigned NumValues = ValueVTs.size(); 4505 if (NumValues == 0) 4506 return; 4507 4508 // Get the lowered operands. Note that we do this after 4509 // checking if NumResults is zero, because with zero results 4510 // the operands won't have values in the map. 4511 SDValue Src = getValue(SrcV); 4512 SDValue Ptr = getValue(PtrV); 4513 4514 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4515 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4516 SDLoc dl = getCurSDLoc(); 4517 Align Alignment = I.getAlign(); 4518 AAMDNodes AAInfo = I.getAAMetadata(); 4519 4520 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4521 4522 unsigned ChainI = 0; 4523 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4524 // See visitLoad comments. 4525 if (ChainI == MaxParallelChains) { 4526 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4527 ArrayRef(Chains.data(), ChainI)); 4528 Root = Chain; 4529 ChainI = 0; 4530 } 4531 4532 // TODO: MachinePointerInfo only supports a fixed length offset. 4533 MachinePointerInfo PtrInfo = 4534 !Offsets[i].isScalable() || Offsets[i].isZero() 4535 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4536 : MachinePointerInfo(); 4537 4538 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4539 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4540 if (MemVTs[i] != ValueVTs[i]) 4541 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4542 SDValue St = 4543 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4544 Chains[ChainI] = St; 4545 } 4546 4547 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4548 ArrayRef(Chains.data(), ChainI)); 4549 setValue(&I, StoreNode); 4550 DAG.setRoot(StoreNode); 4551 } 4552 4553 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4554 bool IsCompressing) { 4555 SDLoc sdl = getCurSDLoc(); 4556 4557 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4558 MaybeAlign &Alignment) { 4559 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4560 Src0 = I.getArgOperand(0); 4561 Ptr = I.getArgOperand(1); 4562 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4563 Mask = I.getArgOperand(3); 4564 }; 4565 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4566 MaybeAlign &Alignment) { 4567 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4568 Src0 = I.getArgOperand(0); 4569 Ptr = I.getArgOperand(1); 4570 Mask = I.getArgOperand(2); 4571 Alignment = std::nullopt; 4572 }; 4573 4574 Value *PtrOperand, *MaskOperand, *Src0Operand; 4575 MaybeAlign Alignment; 4576 if (IsCompressing) 4577 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4578 else 4579 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4580 4581 SDValue Ptr = getValue(PtrOperand); 4582 SDValue Src0 = getValue(Src0Operand); 4583 SDValue Mask = getValue(MaskOperand); 4584 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4585 4586 EVT VT = Src0.getValueType(); 4587 if (!Alignment) 4588 Alignment = DAG.getEVTAlign(VT); 4589 4590 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4591 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4592 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4593 SDValue StoreNode = 4594 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4595 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4596 DAG.setRoot(StoreNode); 4597 setValue(&I, StoreNode); 4598 } 4599 4600 // Get a uniform base for the Gather/Scatter intrinsic. 4601 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4602 // We try to represent it as a base pointer + vector of indices. 4603 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4604 // The first operand of the GEP may be a single pointer or a vector of pointers 4605 // Example: 4606 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4607 // or 4608 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4609 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4610 // 4611 // When the first GEP operand is a single pointer - it is the uniform base we 4612 // are looking for. If first operand of the GEP is a splat vector - we 4613 // extract the splat value and use it as a uniform base. 4614 // In all other cases the function returns 'false'. 4615 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4616 ISD::MemIndexType &IndexType, SDValue &Scale, 4617 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4618 uint64_t ElemSize) { 4619 SelectionDAG& DAG = SDB->DAG; 4620 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4621 const DataLayout &DL = DAG.getDataLayout(); 4622 4623 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4624 4625 // Handle splat constant pointer. 4626 if (auto *C = dyn_cast<Constant>(Ptr)) { 4627 C = C->getSplatValue(); 4628 if (!C) 4629 return false; 4630 4631 Base = SDB->getValue(C); 4632 4633 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4634 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4635 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4636 IndexType = ISD::SIGNED_SCALED; 4637 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4638 return true; 4639 } 4640 4641 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4642 if (!GEP || GEP->getParent() != CurBB) 4643 return false; 4644 4645 if (GEP->getNumOperands() != 2) 4646 return false; 4647 4648 const Value *BasePtr = GEP->getPointerOperand(); 4649 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4650 4651 // Make sure the base is scalar and the index is a vector. 4652 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4653 return false; 4654 4655 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4656 if (ScaleVal.isScalable()) 4657 return false; 4658 4659 // Target may not support the required addressing mode. 4660 if (ScaleVal != 1 && 4661 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4662 return false; 4663 4664 Base = SDB->getValue(BasePtr); 4665 Index = SDB->getValue(IndexVal); 4666 IndexType = ISD::SIGNED_SCALED; 4667 4668 Scale = 4669 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4670 return true; 4671 } 4672 4673 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4674 SDLoc sdl = getCurSDLoc(); 4675 4676 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4677 const Value *Ptr = I.getArgOperand(1); 4678 SDValue Src0 = getValue(I.getArgOperand(0)); 4679 SDValue Mask = getValue(I.getArgOperand(3)); 4680 EVT VT = Src0.getValueType(); 4681 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4682 ->getMaybeAlignValue() 4683 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4684 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4685 4686 SDValue Base; 4687 SDValue Index; 4688 ISD::MemIndexType IndexType; 4689 SDValue Scale; 4690 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4691 I.getParent(), VT.getScalarStoreSize()); 4692 4693 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4694 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4695 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4696 // TODO: Make MachineMemOperands aware of scalable 4697 // vectors. 4698 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4699 if (!UniformBase) { 4700 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4701 Index = getValue(Ptr); 4702 IndexType = ISD::SIGNED_SCALED; 4703 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4704 } 4705 4706 EVT IdxVT = Index.getValueType(); 4707 EVT EltTy = IdxVT.getVectorElementType(); 4708 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4709 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4710 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4711 } 4712 4713 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4714 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4715 Ops, MMO, IndexType, false); 4716 DAG.setRoot(Scatter); 4717 setValue(&I, Scatter); 4718 } 4719 4720 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4721 SDLoc sdl = getCurSDLoc(); 4722 4723 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4724 MaybeAlign &Alignment) { 4725 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4726 Ptr = I.getArgOperand(0); 4727 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4728 Mask = I.getArgOperand(2); 4729 Src0 = I.getArgOperand(3); 4730 }; 4731 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4732 MaybeAlign &Alignment) { 4733 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4734 Ptr = I.getArgOperand(0); 4735 Alignment = std::nullopt; 4736 Mask = I.getArgOperand(1); 4737 Src0 = I.getArgOperand(2); 4738 }; 4739 4740 Value *PtrOperand, *MaskOperand, *Src0Operand; 4741 MaybeAlign Alignment; 4742 if (IsExpanding) 4743 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4744 else 4745 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4746 4747 SDValue Ptr = getValue(PtrOperand); 4748 SDValue Src0 = getValue(Src0Operand); 4749 SDValue Mask = getValue(MaskOperand); 4750 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4751 4752 EVT VT = Src0.getValueType(); 4753 if (!Alignment) 4754 Alignment = DAG.getEVTAlign(VT); 4755 4756 AAMDNodes AAInfo = I.getAAMetadata(); 4757 const MDNode *Ranges = getRangeMetadata(I); 4758 4759 // Do not serialize masked loads of constant memory with anything. 4760 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4761 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4762 4763 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4764 4765 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4766 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4767 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4768 4769 SDValue Load = 4770 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4771 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4772 if (AddToChain) 4773 PendingLoads.push_back(Load.getValue(1)); 4774 setValue(&I, Load); 4775 } 4776 4777 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4778 SDLoc sdl = getCurSDLoc(); 4779 4780 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4781 const Value *Ptr = I.getArgOperand(0); 4782 SDValue Src0 = getValue(I.getArgOperand(3)); 4783 SDValue Mask = getValue(I.getArgOperand(2)); 4784 4785 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4786 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4787 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4788 ->getMaybeAlignValue() 4789 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4790 4791 const MDNode *Ranges = getRangeMetadata(I); 4792 4793 SDValue Root = DAG.getRoot(); 4794 SDValue Base; 4795 SDValue Index; 4796 ISD::MemIndexType IndexType; 4797 SDValue Scale; 4798 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4799 I.getParent(), VT.getScalarStoreSize()); 4800 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4801 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4802 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4803 // TODO: Make MachineMemOperands aware of scalable 4804 // vectors. 4805 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4806 4807 if (!UniformBase) { 4808 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4809 Index = getValue(Ptr); 4810 IndexType = ISD::SIGNED_SCALED; 4811 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4812 } 4813 4814 EVT IdxVT = Index.getValueType(); 4815 EVT EltTy = IdxVT.getVectorElementType(); 4816 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4817 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4818 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4819 } 4820 4821 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4822 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4823 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4824 4825 PendingLoads.push_back(Gather.getValue(1)); 4826 setValue(&I, Gather); 4827 } 4828 4829 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4830 SDLoc dl = getCurSDLoc(); 4831 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4832 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4833 SyncScope::ID SSID = I.getSyncScopeID(); 4834 4835 SDValue InChain = getRoot(); 4836 4837 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4838 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4839 4840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4841 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4842 4843 MachineFunction &MF = DAG.getMachineFunction(); 4844 MachineMemOperand *MMO = MF.getMachineMemOperand( 4845 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4846 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4847 FailureOrdering); 4848 4849 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4850 dl, MemVT, VTs, InChain, 4851 getValue(I.getPointerOperand()), 4852 getValue(I.getCompareOperand()), 4853 getValue(I.getNewValOperand()), MMO); 4854 4855 SDValue OutChain = L.getValue(2); 4856 4857 setValue(&I, L); 4858 DAG.setRoot(OutChain); 4859 } 4860 4861 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4862 SDLoc dl = getCurSDLoc(); 4863 ISD::NodeType NT; 4864 switch (I.getOperation()) { 4865 default: llvm_unreachable("Unknown atomicrmw operation"); 4866 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4867 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4868 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4869 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4870 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4871 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4872 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4873 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4874 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4875 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4876 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4877 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4878 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4879 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4880 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4881 case AtomicRMWInst::UIncWrap: 4882 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4883 break; 4884 case AtomicRMWInst::UDecWrap: 4885 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4886 break; 4887 } 4888 AtomicOrdering Ordering = I.getOrdering(); 4889 SyncScope::ID SSID = I.getSyncScopeID(); 4890 4891 SDValue InChain = getRoot(); 4892 4893 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4894 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4895 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4896 4897 MachineFunction &MF = DAG.getMachineFunction(); 4898 MachineMemOperand *MMO = MF.getMachineMemOperand( 4899 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4900 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4901 4902 SDValue L = 4903 DAG.getAtomic(NT, dl, MemVT, InChain, 4904 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4905 MMO); 4906 4907 SDValue OutChain = L.getValue(1); 4908 4909 setValue(&I, L); 4910 DAG.setRoot(OutChain); 4911 } 4912 4913 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4914 SDLoc dl = getCurSDLoc(); 4915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4916 SDValue Ops[3]; 4917 Ops[0] = getRoot(); 4918 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4919 TLI.getFenceOperandTy(DAG.getDataLayout())); 4920 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4921 TLI.getFenceOperandTy(DAG.getDataLayout())); 4922 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4923 setValue(&I, N); 4924 DAG.setRoot(N); 4925 } 4926 4927 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4928 SDLoc dl = getCurSDLoc(); 4929 AtomicOrdering Order = I.getOrdering(); 4930 SyncScope::ID SSID = I.getSyncScopeID(); 4931 4932 SDValue InChain = getRoot(); 4933 4934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4935 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4936 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4937 4938 if (!TLI.supportsUnalignedAtomics() && 4939 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4940 report_fatal_error("Cannot generate unaligned atomic load"); 4941 4942 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4943 4944 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4945 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4946 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4947 4948 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4949 4950 SDValue Ptr = getValue(I.getPointerOperand()); 4951 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4952 Ptr, MMO); 4953 4954 SDValue OutChain = L.getValue(1); 4955 if (MemVT != VT) 4956 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4957 4958 setValue(&I, L); 4959 DAG.setRoot(OutChain); 4960 } 4961 4962 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4963 SDLoc dl = getCurSDLoc(); 4964 4965 AtomicOrdering Ordering = I.getOrdering(); 4966 SyncScope::ID SSID = I.getSyncScopeID(); 4967 4968 SDValue InChain = getRoot(); 4969 4970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4971 EVT MemVT = 4972 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4973 4974 if (!TLI.supportsUnalignedAtomics() && 4975 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4976 report_fatal_error("Cannot generate unaligned atomic store"); 4977 4978 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4979 4980 MachineFunction &MF = DAG.getMachineFunction(); 4981 MachineMemOperand *MMO = MF.getMachineMemOperand( 4982 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4983 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4984 4985 SDValue Val = getValue(I.getValueOperand()); 4986 if (Val.getValueType() != MemVT) 4987 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4988 SDValue Ptr = getValue(I.getPointerOperand()); 4989 4990 SDValue OutChain = 4991 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 4992 4993 setValue(&I, OutChain); 4994 DAG.setRoot(OutChain); 4995 } 4996 4997 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4998 /// node. 4999 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5000 unsigned Intrinsic) { 5001 // Ignore the callsite's attributes. A specific call site may be marked with 5002 // readnone, but the lowering code will expect the chain based on the 5003 // definition. 5004 const Function *F = I.getCalledFunction(); 5005 bool HasChain = !F->doesNotAccessMemory(); 5006 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5007 5008 // Build the operand list. 5009 SmallVector<SDValue, 8> Ops; 5010 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5011 if (OnlyLoad) { 5012 // We don't need to serialize loads against other loads. 5013 Ops.push_back(DAG.getRoot()); 5014 } else { 5015 Ops.push_back(getRoot()); 5016 } 5017 } 5018 5019 // Info is set by getTgtMemIntrinsic 5020 TargetLowering::IntrinsicInfo Info; 5021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5022 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5023 DAG.getMachineFunction(), 5024 Intrinsic); 5025 5026 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5027 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5028 Info.opc == ISD::INTRINSIC_W_CHAIN) 5029 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5030 TLI.getPointerTy(DAG.getDataLayout()))); 5031 5032 // Add all operands of the call to the operand list. 5033 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5034 const Value *Arg = I.getArgOperand(i); 5035 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5036 Ops.push_back(getValue(Arg)); 5037 continue; 5038 } 5039 5040 // Use TargetConstant instead of a regular constant for immarg. 5041 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5042 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5043 assert(CI->getBitWidth() <= 64 && 5044 "large intrinsic immediates not handled"); 5045 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5046 } else { 5047 Ops.push_back( 5048 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5049 } 5050 } 5051 5052 SmallVector<EVT, 4> ValueVTs; 5053 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5054 5055 if (HasChain) 5056 ValueVTs.push_back(MVT::Other); 5057 5058 SDVTList VTs = DAG.getVTList(ValueVTs); 5059 5060 // Propagate fast-math-flags from IR to node(s). 5061 SDNodeFlags Flags; 5062 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5063 Flags.copyFMF(*FPMO); 5064 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5065 5066 // Create the node. 5067 SDValue Result; 5068 // In some cases, custom collection of operands from CallInst I may be needed. 5069 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5070 if (IsTgtIntrinsic) { 5071 // This is target intrinsic that touches memory 5072 // 5073 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5074 // didn't yield anything useful. 5075 MachinePointerInfo MPI; 5076 if (Info.ptrVal) 5077 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5078 else if (Info.fallbackAddressSpace) 5079 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5080 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5081 Info.memVT, MPI, Info.align, Info.flags, 5082 Info.size, I.getAAMetadata()); 5083 } else if (!HasChain) { 5084 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5085 } else if (!I.getType()->isVoidTy()) { 5086 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5087 } else { 5088 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5089 } 5090 5091 if (HasChain) { 5092 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5093 if (OnlyLoad) 5094 PendingLoads.push_back(Chain); 5095 else 5096 DAG.setRoot(Chain); 5097 } 5098 5099 if (!I.getType()->isVoidTy()) { 5100 if (!isa<VectorType>(I.getType())) 5101 Result = lowerRangeToAssertZExt(DAG, I, Result); 5102 5103 MaybeAlign Alignment = I.getRetAlign(); 5104 5105 // Insert `assertalign` node if there's an alignment. 5106 if (InsertAssertAlign && Alignment) { 5107 Result = 5108 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5109 } 5110 5111 setValue(&I, Result); 5112 } 5113 } 5114 5115 /// GetSignificand - Get the significand and build it into a floating-point 5116 /// number with exponent of 1: 5117 /// 5118 /// Op = (Op & 0x007fffff) | 0x3f800000; 5119 /// 5120 /// where Op is the hexadecimal representation of floating point value. 5121 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5122 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5123 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5124 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5125 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5126 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5127 } 5128 5129 /// GetExponent - Get the exponent: 5130 /// 5131 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5132 /// 5133 /// where Op is the hexadecimal representation of floating point value. 5134 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5135 const TargetLowering &TLI, const SDLoc &dl) { 5136 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5137 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5138 SDValue t1 = DAG.getNode( 5139 ISD::SRL, dl, MVT::i32, t0, 5140 DAG.getConstant(23, dl, 5141 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5142 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5143 DAG.getConstant(127, dl, MVT::i32)); 5144 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5145 } 5146 5147 /// getF32Constant - Get 32-bit floating point constant. 5148 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5149 const SDLoc &dl) { 5150 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5151 MVT::f32); 5152 } 5153 5154 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5155 SelectionDAG &DAG) { 5156 // TODO: What fast-math-flags should be set on the floating-point nodes? 5157 5158 // IntegerPartOfX = ((int32_t)(t0); 5159 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5160 5161 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5162 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5163 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5164 5165 // IntegerPartOfX <<= 23; 5166 IntegerPartOfX = 5167 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5168 DAG.getConstant(23, dl, 5169 DAG.getTargetLoweringInfo().getShiftAmountTy( 5170 MVT::i32, DAG.getDataLayout()))); 5171 5172 SDValue TwoToFractionalPartOfX; 5173 if (LimitFloatPrecision <= 6) { 5174 // For floating-point precision of 6: 5175 // 5176 // TwoToFractionalPartOfX = 5177 // 0.997535578f + 5178 // (0.735607626f + 0.252464424f * x) * x; 5179 // 5180 // error 0.0144103317, which is 6 bits 5181 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5182 getF32Constant(DAG, 0x3e814304, dl)); 5183 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5184 getF32Constant(DAG, 0x3f3c50c8, dl)); 5185 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5186 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5187 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5188 } else if (LimitFloatPrecision <= 12) { 5189 // For floating-point precision of 12: 5190 // 5191 // TwoToFractionalPartOfX = 5192 // 0.999892986f + 5193 // (0.696457318f + 5194 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5195 // 5196 // error 0.000107046256, which is 13 to 14 bits 5197 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5198 getF32Constant(DAG, 0x3da235e3, dl)); 5199 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5200 getF32Constant(DAG, 0x3e65b8f3, dl)); 5201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5203 getF32Constant(DAG, 0x3f324b07, dl)); 5204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5205 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5206 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5207 } else { // LimitFloatPrecision <= 18 5208 // For floating-point precision of 18: 5209 // 5210 // TwoToFractionalPartOfX = 5211 // 0.999999982f + 5212 // (0.693148872f + 5213 // (0.240227044f + 5214 // (0.554906021e-1f + 5215 // (0.961591928e-2f + 5216 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5217 // error 2.47208000*10^(-7), which is better than 18 bits 5218 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5219 getF32Constant(DAG, 0x3924b03e, dl)); 5220 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5221 getF32Constant(DAG, 0x3ab24b87, dl)); 5222 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5223 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5224 getF32Constant(DAG, 0x3c1d8c17, dl)); 5225 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5226 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5227 getF32Constant(DAG, 0x3d634a1d, dl)); 5228 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5229 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5230 getF32Constant(DAG, 0x3e75fe14, dl)); 5231 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5232 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5233 getF32Constant(DAG, 0x3f317234, dl)); 5234 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5235 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5236 getF32Constant(DAG, 0x3f800000, dl)); 5237 } 5238 5239 // Add the exponent into the result in integer domain. 5240 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5241 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5242 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5243 } 5244 5245 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5246 /// limited-precision mode. 5247 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5248 const TargetLowering &TLI, SDNodeFlags Flags) { 5249 if (Op.getValueType() == MVT::f32 && 5250 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5251 5252 // Put the exponent in the right bit position for later addition to the 5253 // final result: 5254 // 5255 // t0 = Op * log2(e) 5256 5257 // TODO: What fast-math-flags should be set here? 5258 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5259 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5260 return getLimitedPrecisionExp2(t0, dl, DAG); 5261 } 5262 5263 // No special expansion. 5264 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5265 } 5266 5267 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5268 /// limited-precision mode. 5269 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5270 const TargetLowering &TLI, SDNodeFlags Flags) { 5271 // TODO: What fast-math-flags should be set on the floating-point nodes? 5272 5273 if (Op.getValueType() == MVT::f32 && 5274 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5275 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5276 5277 // Scale the exponent by log(2). 5278 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5279 SDValue LogOfExponent = 5280 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5281 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5282 5283 // Get the significand and build it into a floating-point number with 5284 // exponent of 1. 5285 SDValue X = GetSignificand(DAG, Op1, dl); 5286 5287 SDValue LogOfMantissa; 5288 if (LimitFloatPrecision <= 6) { 5289 // For floating-point precision of 6: 5290 // 5291 // LogofMantissa = 5292 // -1.1609546f + 5293 // (1.4034025f - 0.23903021f * x) * x; 5294 // 5295 // error 0.0034276066, which is better than 8 bits 5296 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5297 getF32Constant(DAG, 0xbe74c456, dl)); 5298 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5299 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5300 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5301 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5302 getF32Constant(DAG, 0x3f949a29, dl)); 5303 } else if (LimitFloatPrecision <= 12) { 5304 // For floating-point precision of 12: 5305 // 5306 // LogOfMantissa = 5307 // -1.7417939f + 5308 // (2.8212026f + 5309 // (-1.4699568f + 5310 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5311 // 5312 // error 0.000061011436, which is 14 bits 5313 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5314 getF32Constant(DAG, 0xbd67b6d6, dl)); 5315 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5316 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5317 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5318 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5319 getF32Constant(DAG, 0x3fbc278b, dl)); 5320 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5321 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5322 getF32Constant(DAG, 0x40348e95, dl)); 5323 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5324 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5325 getF32Constant(DAG, 0x3fdef31a, dl)); 5326 } else { // LimitFloatPrecision <= 18 5327 // For floating-point precision of 18: 5328 // 5329 // LogOfMantissa = 5330 // -2.1072184f + 5331 // (4.2372794f + 5332 // (-3.7029485f + 5333 // (2.2781945f + 5334 // (-0.87823314f + 5335 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5336 // 5337 // error 0.0000023660568, which is better than 18 bits 5338 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5339 getF32Constant(DAG, 0xbc91e5ac, dl)); 5340 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5341 getF32Constant(DAG, 0x3e4350aa, dl)); 5342 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5343 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5344 getF32Constant(DAG, 0x3f60d3e3, dl)); 5345 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5346 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5347 getF32Constant(DAG, 0x4011cdf0, dl)); 5348 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5349 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5350 getF32Constant(DAG, 0x406cfd1c, dl)); 5351 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5352 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5353 getF32Constant(DAG, 0x408797cb, dl)); 5354 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5355 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5356 getF32Constant(DAG, 0x4006dcab, dl)); 5357 } 5358 5359 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5360 } 5361 5362 // No special expansion. 5363 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5364 } 5365 5366 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5367 /// limited-precision mode. 5368 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5369 const TargetLowering &TLI, SDNodeFlags Flags) { 5370 // TODO: What fast-math-flags should be set on the floating-point nodes? 5371 5372 if (Op.getValueType() == MVT::f32 && 5373 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5374 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5375 5376 // Get the exponent. 5377 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5378 5379 // Get the significand and build it into a floating-point number with 5380 // exponent of 1. 5381 SDValue X = GetSignificand(DAG, Op1, dl); 5382 5383 // Different possible minimax approximations of significand in 5384 // floating-point for various degrees of accuracy over [1,2]. 5385 SDValue Log2ofMantissa; 5386 if (LimitFloatPrecision <= 6) { 5387 // For floating-point precision of 6: 5388 // 5389 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5390 // 5391 // error 0.0049451742, which is more than 7 bits 5392 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5393 getF32Constant(DAG, 0xbeb08fe0, dl)); 5394 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5395 getF32Constant(DAG, 0x40019463, dl)); 5396 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5397 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5398 getF32Constant(DAG, 0x3fd6633d, dl)); 5399 } else if (LimitFloatPrecision <= 12) { 5400 // For floating-point precision of 12: 5401 // 5402 // Log2ofMantissa = 5403 // -2.51285454f + 5404 // (4.07009056f + 5405 // (-2.12067489f + 5406 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5407 // 5408 // error 0.0000876136000, which is better than 13 bits 5409 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5410 getF32Constant(DAG, 0xbda7262e, dl)); 5411 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5412 getF32Constant(DAG, 0x3f25280b, dl)); 5413 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5414 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5415 getF32Constant(DAG, 0x4007b923, dl)); 5416 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5417 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5418 getF32Constant(DAG, 0x40823e2f, dl)); 5419 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5420 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5421 getF32Constant(DAG, 0x4020d29c, dl)); 5422 } else { // LimitFloatPrecision <= 18 5423 // For floating-point precision of 18: 5424 // 5425 // Log2ofMantissa = 5426 // -3.0400495f + 5427 // (6.1129976f + 5428 // (-5.3420409f + 5429 // (3.2865683f + 5430 // (-1.2669343f + 5431 // (0.27515199f - 5432 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5433 // 5434 // error 0.0000018516, which is better than 18 bits 5435 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5436 getF32Constant(DAG, 0xbcd2769e, dl)); 5437 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5438 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5439 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5440 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5441 getF32Constant(DAG, 0x3fa22ae7, dl)); 5442 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5443 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5444 getF32Constant(DAG, 0x40525723, dl)); 5445 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5446 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5447 getF32Constant(DAG, 0x40aaf200, dl)); 5448 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5449 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5450 getF32Constant(DAG, 0x40c39dad, dl)); 5451 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5452 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5453 getF32Constant(DAG, 0x4042902c, dl)); 5454 } 5455 5456 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5457 } 5458 5459 // No special expansion. 5460 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5461 } 5462 5463 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5464 /// limited-precision mode. 5465 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5466 const TargetLowering &TLI, SDNodeFlags Flags) { 5467 // TODO: What fast-math-flags should be set on the floating-point nodes? 5468 5469 if (Op.getValueType() == MVT::f32 && 5470 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5471 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5472 5473 // Scale the exponent by log10(2) [0.30102999f]. 5474 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5475 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5476 getF32Constant(DAG, 0x3e9a209a, dl)); 5477 5478 // Get the significand and build it into a floating-point number with 5479 // exponent of 1. 5480 SDValue X = GetSignificand(DAG, Op1, dl); 5481 5482 SDValue Log10ofMantissa; 5483 if (LimitFloatPrecision <= 6) { 5484 // For floating-point precision of 6: 5485 // 5486 // Log10ofMantissa = 5487 // -0.50419619f + 5488 // (0.60948995f - 0.10380950f * x) * x; 5489 // 5490 // error 0.0014886165, which is 6 bits 5491 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5492 getF32Constant(DAG, 0xbdd49a13, dl)); 5493 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5494 getF32Constant(DAG, 0x3f1c0789, dl)); 5495 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5496 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5497 getF32Constant(DAG, 0x3f011300, dl)); 5498 } else if (LimitFloatPrecision <= 12) { 5499 // For floating-point precision of 12: 5500 // 5501 // Log10ofMantissa = 5502 // -0.64831180f + 5503 // (0.91751397f + 5504 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5505 // 5506 // error 0.00019228036, which is better than 12 bits 5507 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5508 getF32Constant(DAG, 0x3d431f31, dl)); 5509 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5510 getF32Constant(DAG, 0x3ea21fb2, dl)); 5511 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5512 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5513 getF32Constant(DAG, 0x3f6ae232, dl)); 5514 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5515 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5516 getF32Constant(DAG, 0x3f25f7c3, dl)); 5517 } else { // LimitFloatPrecision <= 18 5518 // For floating-point precision of 18: 5519 // 5520 // Log10ofMantissa = 5521 // -0.84299375f + 5522 // (1.5327582f + 5523 // (-1.0688956f + 5524 // (0.49102474f + 5525 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5526 // 5527 // error 0.0000037995730, which is better than 18 bits 5528 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5529 getF32Constant(DAG, 0x3c5d51ce, dl)); 5530 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5531 getF32Constant(DAG, 0x3e00685a, dl)); 5532 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5533 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5534 getF32Constant(DAG, 0x3efb6798, dl)); 5535 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5536 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5537 getF32Constant(DAG, 0x3f88d192, dl)); 5538 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5539 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5540 getF32Constant(DAG, 0x3fc4316c, dl)); 5541 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5542 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5543 getF32Constant(DAG, 0x3f57ce70, dl)); 5544 } 5545 5546 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5547 } 5548 5549 // No special expansion. 5550 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5551 } 5552 5553 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5554 /// limited-precision mode. 5555 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5556 const TargetLowering &TLI, SDNodeFlags Flags) { 5557 if (Op.getValueType() == MVT::f32 && 5558 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5559 return getLimitedPrecisionExp2(Op, dl, DAG); 5560 5561 // No special expansion. 5562 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5563 } 5564 5565 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5566 /// limited-precision mode with x == 10.0f. 5567 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5568 SelectionDAG &DAG, const TargetLowering &TLI, 5569 SDNodeFlags Flags) { 5570 bool IsExp10 = false; 5571 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5572 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5573 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5574 APFloat Ten(10.0f); 5575 IsExp10 = LHSC->isExactlyValue(Ten); 5576 } 5577 } 5578 5579 // TODO: What fast-math-flags should be set on the FMUL node? 5580 if (IsExp10) { 5581 // Put the exponent in the right bit position for later addition to the 5582 // final result: 5583 // 5584 // #define LOG2OF10 3.3219281f 5585 // t0 = Op * LOG2OF10; 5586 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5587 getF32Constant(DAG, 0x40549a78, dl)); 5588 return getLimitedPrecisionExp2(t0, dl, DAG); 5589 } 5590 5591 // No special expansion. 5592 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5593 } 5594 5595 /// ExpandPowI - Expand a llvm.powi intrinsic. 5596 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5597 SelectionDAG &DAG) { 5598 // If RHS is a constant, we can expand this out to a multiplication tree if 5599 // it's beneficial on the target, otherwise we end up lowering to a call to 5600 // __powidf2 (for example). 5601 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5602 unsigned Val = RHSC->getSExtValue(); 5603 5604 // powi(x, 0) -> 1.0 5605 if (Val == 0) 5606 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5607 5608 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5609 Val, DAG.shouldOptForSize())) { 5610 // Get the exponent as a positive value. 5611 if ((int)Val < 0) 5612 Val = -Val; 5613 // We use the simple binary decomposition method to generate the multiply 5614 // sequence. There are more optimal ways to do this (for example, 5615 // powi(x,15) generates one more multiply than it should), but this has 5616 // the benefit of being both really simple and much better than a libcall. 5617 SDValue Res; // Logically starts equal to 1.0 5618 SDValue CurSquare = LHS; 5619 // TODO: Intrinsics should have fast-math-flags that propagate to these 5620 // nodes. 5621 while (Val) { 5622 if (Val & 1) { 5623 if (Res.getNode()) 5624 Res = 5625 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5626 else 5627 Res = CurSquare; // 1.0*CurSquare. 5628 } 5629 5630 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5631 CurSquare, CurSquare); 5632 Val >>= 1; 5633 } 5634 5635 // If the original was negative, invert the result, producing 1/(x*x*x). 5636 if (RHSC->getSExtValue() < 0) 5637 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5638 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5639 return Res; 5640 } 5641 } 5642 5643 // Otherwise, expand to a libcall. 5644 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5645 } 5646 5647 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5648 SDValue LHS, SDValue RHS, SDValue Scale, 5649 SelectionDAG &DAG, const TargetLowering &TLI) { 5650 EVT VT = LHS.getValueType(); 5651 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5652 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5653 LLVMContext &Ctx = *DAG.getContext(); 5654 5655 // If the type is legal but the operation isn't, this node might survive all 5656 // the way to operation legalization. If we end up there and we do not have 5657 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5658 // node. 5659 5660 // Coax the legalizer into expanding the node during type legalization instead 5661 // by bumping the size by one bit. This will force it to Promote, enabling the 5662 // early expansion and avoiding the need to expand later. 5663 5664 // We don't have to do this if Scale is 0; that can always be expanded, unless 5665 // it's a saturating signed operation. Those can experience true integer 5666 // division overflow, a case which we must avoid. 5667 5668 // FIXME: We wouldn't have to do this (or any of the early 5669 // expansion/promotion) if it was possible to expand a libcall of an 5670 // illegal type during operation legalization. But it's not, so things 5671 // get a bit hacky. 5672 unsigned ScaleInt = Scale->getAsZExtVal(); 5673 if ((ScaleInt > 0 || (Saturating && Signed)) && 5674 (TLI.isTypeLegal(VT) || 5675 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5676 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5677 Opcode, VT, ScaleInt); 5678 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5679 EVT PromVT; 5680 if (VT.isScalarInteger()) 5681 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5682 else if (VT.isVector()) { 5683 PromVT = VT.getVectorElementType(); 5684 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5685 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5686 } else 5687 llvm_unreachable("Wrong VT for DIVFIX?"); 5688 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5689 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5690 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5691 // For saturating operations, we need to shift up the LHS to get the 5692 // proper saturation width, and then shift down again afterwards. 5693 if (Saturating) 5694 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5695 DAG.getConstant(1, DL, ShiftTy)); 5696 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5697 if (Saturating) 5698 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5699 DAG.getConstant(1, DL, ShiftTy)); 5700 return DAG.getZExtOrTrunc(Res, DL, VT); 5701 } 5702 } 5703 5704 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5705 } 5706 5707 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5708 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5709 static void 5710 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5711 const SDValue &N) { 5712 switch (N.getOpcode()) { 5713 case ISD::CopyFromReg: { 5714 SDValue Op = N.getOperand(1); 5715 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5716 Op.getValueType().getSizeInBits()); 5717 return; 5718 } 5719 case ISD::BITCAST: 5720 case ISD::AssertZext: 5721 case ISD::AssertSext: 5722 case ISD::TRUNCATE: 5723 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5724 return; 5725 case ISD::BUILD_PAIR: 5726 case ISD::BUILD_VECTOR: 5727 case ISD::CONCAT_VECTORS: 5728 for (SDValue Op : N->op_values()) 5729 getUnderlyingArgRegs(Regs, Op); 5730 return; 5731 default: 5732 return; 5733 } 5734 } 5735 5736 /// If the DbgValueInst is a dbg_value of a function argument, create the 5737 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5738 /// instruction selection, they will be inserted to the entry BB. 5739 /// We don't currently support this for variadic dbg_values, as they shouldn't 5740 /// appear for function arguments or in the prologue. 5741 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5742 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5743 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5744 const Argument *Arg = dyn_cast<Argument>(V); 5745 if (!Arg) 5746 return false; 5747 5748 MachineFunction &MF = DAG.getMachineFunction(); 5749 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5750 5751 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5752 // we've been asked to pursue. 5753 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5754 bool Indirect) { 5755 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5756 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5757 // pointing at the VReg, which will be patched up later. 5758 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5759 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5760 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5761 /* isKill */ false, /* isDead */ false, 5762 /* isUndef */ false, /* isEarlyClobber */ false, 5763 /* SubReg */ 0, /* isDebug */ true)}); 5764 5765 auto *NewDIExpr = FragExpr; 5766 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5767 // the DIExpression. 5768 if (Indirect) 5769 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5770 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5771 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5772 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5773 } else { 5774 // Create a completely standard DBG_VALUE. 5775 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5776 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5777 } 5778 }; 5779 5780 if (Kind == FuncArgumentDbgValueKind::Value) { 5781 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5782 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5783 // the entry block. 5784 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5785 if (!IsInEntryBlock) 5786 return false; 5787 5788 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5789 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5790 // variable that also is a param. 5791 // 5792 // Although, if we are at the top of the entry block already, we can still 5793 // emit using ArgDbgValue. This might catch some situations when the 5794 // dbg.value refers to an argument that isn't used in the entry block, so 5795 // any CopyToReg node would be optimized out and the only way to express 5796 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5797 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5798 // we should only emit as ArgDbgValue if the Variable is an argument to the 5799 // current function, and the dbg.value intrinsic is found in the entry 5800 // block. 5801 bool VariableIsFunctionInputArg = Variable->isParameter() && 5802 !DL->getInlinedAt(); 5803 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5804 if (!IsInPrologue && !VariableIsFunctionInputArg) 5805 return false; 5806 5807 // Here we assume that a function argument on IR level only can be used to 5808 // describe one input parameter on source level. If we for example have 5809 // source code like this 5810 // 5811 // struct A { long x, y; }; 5812 // void foo(struct A a, long b) { 5813 // ... 5814 // b = a.x; 5815 // ... 5816 // } 5817 // 5818 // and IR like this 5819 // 5820 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5821 // entry: 5822 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5823 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5824 // call void @llvm.dbg.value(metadata i32 %b, "b", 5825 // ... 5826 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5827 // ... 5828 // 5829 // then the last dbg.value is describing a parameter "b" using a value that 5830 // is an argument. But since we already has used %a1 to describe a parameter 5831 // we should not handle that last dbg.value here (that would result in an 5832 // incorrect hoisting of the DBG_VALUE to the function entry). 5833 // Notice that we allow one dbg.value per IR level argument, to accommodate 5834 // for the situation with fragments above. 5835 if (VariableIsFunctionInputArg) { 5836 unsigned ArgNo = Arg->getArgNo(); 5837 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5838 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5839 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5840 return false; 5841 FuncInfo.DescribedArgs.set(ArgNo); 5842 } 5843 } 5844 5845 bool IsIndirect = false; 5846 std::optional<MachineOperand> Op; 5847 // Some arguments' frame index is recorded during argument lowering. 5848 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5849 if (FI != std::numeric_limits<int>::max()) 5850 Op = MachineOperand::CreateFI(FI); 5851 5852 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5853 if (!Op && N.getNode()) { 5854 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5855 Register Reg; 5856 if (ArgRegsAndSizes.size() == 1) 5857 Reg = ArgRegsAndSizes.front().first; 5858 5859 if (Reg && Reg.isVirtual()) { 5860 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5861 Register PR = RegInfo.getLiveInPhysReg(Reg); 5862 if (PR) 5863 Reg = PR; 5864 } 5865 if (Reg) { 5866 Op = MachineOperand::CreateReg(Reg, false); 5867 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5868 } 5869 } 5870 5871 if (!Op && N.getNode()) { 5872 // Check if frame index is available. 5873 SDValue LCandidate = peekThroughBitcasts(N); 5874 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5875 if (FrameIndexSDNode *FINode = 5876 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5877 Op = MachineOperand::CreateFI(FINode->getIndex()); 5878 } 5879 5880 if (!Op) { 5881 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5882 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5883 SplitRegs) { 5884 unsigned Offset = 0; 5885 for (const auto &RegAndSize : SplitRegs) { 5886 // If the expression is already a fragment, the current register 5887 // offset+size might extend beyond the fragment. In this case, only 5888 // the register bits that are inside the fragment are relevant. 5889 int RegFragmentSizeInBits = RegAndSize.second; 5890 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5891 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5892 // The register is entirely outside the expression fragment, 5893 // so is irrelevant for debug info. 5894 if (Offset >= ExprFragmentSizeInBits) 5895 break; 5896 // The register is partially outside the expression fragment, only 5897 // the low bits within the fragment are relevant for debug info. 5898 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5899 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5900 } 5901 } 5902 5903 auto FragmentExpr = DIExpression::createFragmentExpression( 5904 Expr, Offset, RegFragmentSizeInBits); 5905 Offset += RegAndSize.second; 5906 // If a valid fragment expression cannot be created, the variable's 5907 // correct value cannot be determined and so it is set as Undef. 5908 if (!FragmentExpr) { 5909 SDDbgValue *SDV = DAG.getConstantDbgValue( 5910 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5911 DAG.AddDbgValue(SDV, false); 5912 continue; 5913 } 5914 MachineInstr *NewMI = 5915 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5916 Kind != FuncArgumentDbgValueKind::Value); 5917 FuncInfo.ArgDbgValues.push_back(NewMI); 5918 } 5919 }; 5920 5921 // Check if ValueMap has reg number. 5922 DenseMap<const Value *, Register>::const_iterator 5923 VMI = FuncInfo.ValueMap.find(V); 5924 if (VMI != FuncInfo.ValueMap.end()) { 5925 const auto &TLI = DAG.getTargetLoweringInfo(); 5926 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5927 V->getType(), std::nullopt); 5928 if (RFV.occupiesMultipleRegs()) { 5929 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5930 return true; 5931 } 5932 5933 Op = MachineOperand::CreateReg(VMI->second, false); 5934 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5935 } else if (ArgRegsAndSizes.size() > 1) { 5936 // This was split due to the calling convention, and no virtual register 5937 // mapping exists for the value. 5938 splitMultiRegDbgValue(ArgRegsAndSizes); 5939 return true; 5940 } 5941 } 5942 5943 if (!Op) 5944 return false; 5945 5946 assert(Variable->isValidLocationForIntrinsic(DL) && 5947 "Expected inlined-at fields to agree"); 5948 MachineInstr *NewMI = nullptr; 5949 5950 if (Op->isReg()) 5951 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5952 else 5953 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5954 Variable, Expr); 5955 5956 // Otherwise, use ArgDbgValues. 5957 FuncInfo.ArgDbgValues.push_back(NewMI); 5958 return true; 5959 } 5960 5961 /// Return the appropriate SDDbgValue based on N. 5962 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5963 DILocalVariable *Variable, 5964 DIExpression *Expr, 5965 const DebugLoc &dl, 5966 unsigned DbgSDNodeOrder) { 5967 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5968 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5969 // stack slot locations. 5970 // 5971 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5972 // debug values here after optimization: 5973 // 5974 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5975 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5976 // 5977 // Both describe the direct values of their associated variables. 5978 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5979 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5980 } 5981 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5982 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5983 } 5984 5985 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5986 switch (Intrinsic) { 5987 case Intrinsic::smul_fix: 5988 return ISD::SMULFIX; 5989 case Intrinsic::umul_fix: 5990 return ISD::UMULFIX; 5991 case Intrinsic::smul_fix_sat: 5992 return ISD::SMULFIXSAT; 5993 case Intrinsic::umul_fix_sat: 5994 return ISD::UMULFIXSAT; 5995 case Intrinsic::sdiv_fix: 5996 return ISD::SDIVFIX; 5997 case Intrinsic::udiv_fix: 5998 return ISD::UDIVFIX; 5999 case Intrinsic::sdiv_fix_sat: 6000 return ISD::SDIVFIXSAT; 6001 case Intrinsic::udiv_fix_sat: 6002 return ISD::UDIVFIXSAT; 6003 default: 6004 llvm_unreachable("Unhandled fixed point intrinsic"); 6005 } 6006 } 6007 6008 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6009 const char *FunctionName) { 6010 assert(FunctionName && "FunctionName must not be nullptr"); 6011 SDValue Callee = DAG.getExternalSymbol( 6012 FunctionName, 6013 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6014 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6015 } 6016 6017 /// Given a @llvm.call.preallocated.setup, return the corresponding 6018 /// preallocated call. 6019 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6020 assert(cast<CallBase>(PreallocatedSetup) 6021 ->getCalledFunction() 6022 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6023 "expected call_preallocated_setup Value"); 6024 for (const auto *U : PreallocatedSetup->users()) { 6025 auto *UseCall = cast<CallBase>(U); 6026 const Function *Fn = UseCall->getCalledFunction(); 6027 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6028 return UseCall; 6029 } 6030 } 6031 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6032 } 6033 6034 /// If DI is a debug value with an EntryValue expression, lower it using the 6035 /// corresponding physical register of the associated Argument value 6036 /// (guaranteed to exist by the verifier). 6037 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6038 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6039 DIExpression *Expr, DebugLoc DbgLoc) { 6040 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6041 return false; 6042 6043 // These properties are guaranteed by the verifier. 6044 const Argument *Arg = cast<Argument>(Values[0]); 6045 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6046 6047 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6048 if (ArgIt == FuncInfo.ValueMap.end()) { 6049 LLVM_DEBUG( 6050 dbgs() << "Dropping dbg.value: expression is entry_value but " 6051 "couldn't find an associated register for the Argument\n"); 6052 return true; 6053 } 6054 Register ArgVReg = ArgIt->getSecond(); 6055 6056 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6057 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6058 SDDbgValue *SDV = DAG.getVRegDbgValue( 6059 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6060 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6061 return true; 6062 } 6063 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6064 "couldn't find a physical register\n"); 6065 return true; 6066 } 6067 6068 /// Lower the call to the specified intrinsic function. 6069 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6070 unsigned Intrinsic) { 6071 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6072 SDLoc sdl = getCurSDLoc(); 6073 DebugLoc dl = getCurDebugLoc(); 6074 SDValue Res; 6075 6076 SDNodeFlags Flags; 6077 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6078 Flags.copyFMF(*FPOp); 6079 6080 switch (Intrinsic) { 6081 default: 6082 // By default, turn this into a target intrinsic node. 6083 visitTargetIntrinsic(I, Intrinsic); 6084 return; 6085 case Intrinsic::vscale: { 6086 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6087 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6088 return; 6089 } 6090 case Intrinsic::vastart: visitVAStart(I); return; 6091 case Intrinsic::vaend: visitVAEnd(I); return; 6092 case Intrinsic::vacopy: visitVACopy(I); return; 6093 case Intrinsic::returnaddress: 6094 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6095 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6096 getValue(I.getArgOperand(0)))); 6097 return; 6098 case Intrinsic::addressofreturnaddress: 6099 setValue(&I, 6100 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6101 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6102 return; 6103 case Intrinsic::sponentry: 6104 setValue(&I, 6105 DAG.getNode(ISD::SPONENTRY, sdl, 6106 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6107 return; 6108 case Intrinsic::frameaddress: 6109 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6110 TLI.getFrameIndexTy(DAG.getDataLayout()), 6111 getValue(I.getArgOperand(0)))); 6112 return; 6113 case Intrinsic::read_volatile_register: 6114 case Intrinsic::read_register: { 6115 Value *Reg = I.getArgOperand(0); 6116 SDValue Chain = getRoot(); 6117 SDValue RegName = 6118 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6119 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6120 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6121 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6122 setValue(&I, Res); 6123 DAG.setRoot(Res.getValue(1)); 6124 return; 6125 } 6126 case Intrinsic::write_register: { 6127 Value *Reg = I.getArgOperand(0); 6128 Value *RegValue = I.getArgOperand(1); 6129 SDValue Chain = getRoot(); 6130 SDValue RegName = 6131 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6132 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6133 RegName, getValue(RegValue))); 6134 return; 6135 } 6136 case Intrinsic::memcpy: { 6137 const auto &MCI = cast<MemCpyInst>(I); 6138 SDValue Op1 = getValue(I.getArgOperand(0)); 6139 SDValue Op2 = getValue(I.getArgOperand(1)); 6140 SDValue Op3 = getValue(I.getArgOperand(2)); 6141 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6142 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6143 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6144 Align Alignment = std::min(DstAlign, SrcAlign); 6145 bool isVol = MCI.isVolatile(); 6146 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6147 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6148 // node. 6149 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6150 SDValue MC = DAG.getMemcpy( 6151 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6152 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6153 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6154 updateDAGForMaybeTailCall(MC); 6155 return; 6156 } 6157 case Intrinsic::memcpy_inline: { 6158 const auto &MCI = cast<MemCpyInlineInst>(I); 6159 SDValue Dst = getValue(I.getArgOperand(0)); 6160 SDValue Src = getValue(I.getArgOperand(1)); 6161 SDValue Size = getValue(I.getArgOperand(2)); 6162 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6163 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6164 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6165 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6166 Align Alignment = std::min(DstAlign, SrcAlign); 6167 bool isVol = MCI.isVolatile(); 6168 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6169 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6170 // node. 6171 SDValue MC = DAG.getMemcpy( 6172 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6173 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6174 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6175 updateDAGForMaybeTailCall(MC); 6176 return; 6177 } 6178 case Intrinsic::memset: { 6179 const auto &MSI = cast<MemSetInst>(I); 6180 SDValue Op1 = getValue(I.getArgOperand(0)); 6181 SDValue Op2 = getValue(I.getArgOperand(1)); 6182 SDValue Op3 = getValue(I.getArgOperand(2)); 6183 // @llvm.memset defines 0 and 1 to both mean no alignment. 6184 Align Alignment = MSI.getDestAlign().valueOrOne(); 6185 bool isVol = MSI.isVolatile(); 6186 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6187 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6188 SDValue MS = DAG.getMemset( 6189 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6190 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6191 updateDAGForMaybeTailCall(MS); 6192 return; 6193 } 6194 case Intrinsic::memset_inline: { 6195 const auto &MSII = cast<MemSetInlineInst>(I); 6196 SDValue Dst = getValue(I.getArgOperand(0)); 6197 SDValue Value = getValue(I.getArgOperand(1)); 6198 SDValue Size = getValue(I.getArgOperand(2)); 6199 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6200 // @llvm.memset defines 0 and 1 to both mean no alignment. 6201 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6202 bool isVol = MSII.isVolatile(); 6203 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6204 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6205 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6206 /* AlwaysInline */ true, isTC, 6207 MachinePointerInfo(I.getArgOperand(0)), 6208 I.getAAMetadata()); 6209 updateDAGForMaybeTailCall(MC); 6210 return; 6211 } 6212 case Intrinsic::memmove: { 6213 const auto &MMI = cast<MemMoveInst>(I); 6214 SDValue Op1 = getValue(I.getArgOperand(0)); 6215 SDValue Op2 = getValue(I.getArgOperand(1)); 6216 SDValue Op3 = getValue(I.getArgOperand(2)); 6217 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6218 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6219 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6220 Align Alignment = std::min(DstAlign, SrcAlign); 6221 bool isVol = MMI.isVolatile(); 6222 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6223 // FIXME: Support passing different dest/src alignments to the memmove DAG 6224 // node. 6225 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6226 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6227 isTC, MachinePointerInfo(I.getArgOperand(0)), 6228 MachinePointerInfo(I.getArgOperand(1)), 6229 I.getAAMetadata(), AA); 6230 updateDAGForMaybeTailCall(MM); 6231 return; 6232 } 6233 case Intrinsic::memcpy_element_unordered_atomic: { 6234 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6235 SDValue Dst = getValue(MI.getRawDest()); 6236 SDValue Src = getValue(MI.getRawSource()); 6237 SDValue Length = getValue(MI.getLength()); 6238 6239 Type *LengthTy = MI.getLength()->getType(); 6240 unsigned ElemSz = MI.getElementSizeInBytes(); 6241 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6242 SDValue MC = 6243 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6244 isTC, MachinePointerInfo(MI.getRawDest()), 6245 MachinePointerInfo(MI.getRawSource())); 6246 updateDAGForMaybeTailCall(MC); 6247 return; 6248 } 6249 case Intrinsic::memmove_element_unordered_atomic: { 6250 auto &MI = cast<AtomicMemMoveInst>(I); 6251 SDValue Dst = getValue(MI.getRawDest()); 6252 SDValue Src = getValue(MI.getRawSource()); 6253 SDValue Length = getValue(MI.getLength()); 6254 6255 Type *LengthTy = MI.getLength()->getType(); 6256 unsigned ElemSz = MI.getElementSizeInBytes(); 6257 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6258 SDValue MC = 6259 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6260 isTC, MachinePointerInfo(MI.getRawDest()), 6261 MachinePointerInfo(MI.getRawSource())); 6262 updateDAGForMaybeTailCall(MC); 6263 return; 6264 } 6265 case Intrinsic::memset_element_unordered_atomic: { 6266 auto &MI = cast<AtomicMemSetInst>(I); 6267 SDValue Dst = getValue(MI.getRawDest()); 6268 SDValue Val = getValue(MI.getValue()); 6269 SDValue Length = getValue(MI.getLength()); 6270 6271 Type *LengthTy = MI.getLength()->getType(); 6272 unsigned ElemSz = MI.getElementSizeInBytes(); 6273 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6274 SDValue MC = 6275 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6276 isTC, MachinePointerInfo(MI.getRawDest())); 6277 updateDAGForMaybeTailCall(MC); 6278 return; 6279 } 6280 case Intrinsic::call_preallocated_setup: { 6281 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6282 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6283 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6284 getRoot(), SrcValue); 6285 setValue(&I, Res); 6286 DAG.setRoot(Res); 6287 return; 6288 } 6289 case Intrinsic::call_preallocated_arg: { 6290 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6291 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6292 SDValue Ops[3]; 6293 Ops[0] = getRoot(); 6294 Ops[1] = SrcValue; 6295 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6296 MVT::i32); // arg index 6297 SDValue Res = DAG.getNode( 6298 ISD::PREALLOCATED_ARG, sdl, 6299 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6300 setValue(&I, Res); 6301 DAG.setRoot(Res.getValue(1)); 6302 return; 6303 } 6304 case Intrinsic::dbg_declare: { 6305 const auto &DI = cast<DbgDeclareInst>(I); 6306 // Debug intrinsics are handled separately in assignment tracking mode. 6307 // Some intrinsics are handled right after Argument lowering. 6308 if (AssignmentTrackingEnabled || 6309 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6310 return; 6311 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6312 DILocalVariable *Variable = DI.getVariable(); 6313 DIExpression *Expression = DI.getExpression(); 6314 dropDanglingDebugInfo(Variable, Expression); 6315 // Assume dbg.declare can not currently use DIArgList, i.e. 6316 // it is non-variadic. 6317 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6318 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6319 DI.getDebugLoc()); 6320 return; 6321 } 6322 case Intrinsic::dbg_label: { 6323 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6324 DILabel *Label = DI.getLabel(); 6325 assert(Label && "Missing label"); 6326 6327 SDDbgLabel *SDV; 6328 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6329 DAG.AddDbgLabel(SDV); 6330 return; 6331 } 6332 case Intrinsic::dbg_assign: { 6333 // Debug intrinsics are handled seperately in assignment tracking mode. 6334 if (AssignmentTrackingEnabled) 6335 return; 6336 // If assignment tracking hasn't been enabled then fall through and treat 6337 // the dbg.assign as a dbg.value. 6338 [[fallthrough]]; 6339 } 6340 case Intrinsic::dbg_value: { 6341 // Debug intrinsics are handled seperately in assignment tracking mode. 6342 if (AssignmentTrackingEnabled) 6343 return; 6344 const DbgValueInst &DI = cast<DbgValueInst>(I); 6345 assert(DI.getVariable() && "Missing variable"); 6346 6347 DILocalVariable *Variable = DI.getVariable(); 6348 DIExpression *Expression = DI.getExpression(); 6349 dropDanglingDebugInfo(Variable, Expression); 6350 6351 if (DI.isKillLocation()) { 6352 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6353 return; 6354 } 6355 6356 SmallVector<Value *, 4> Values(DI.getValues()); 6357 if (Values.empty()) 6358 return; 6359 6360 bool IsVariadic = DI.hasArgList(); 6361 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6362 SDNodeOrder, IsVariadic)) 6363 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6364 DI.getDebugLoc(), SDNodeOrder); 6365 return; 6366 } 6367 6368 case Intrinsic::eh_typeid_for: { 6369 // Find the type id for the given typeinfo. 6370 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6371 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6372 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6373 setValue(&I, Res); 6374 return; 6375 } 6376 6377 case Intrinsic::eh_return_i32: 6378 case Intrinsic::eh_return_i64: 6379 DAG.getMachineFunction().setCallsEHReturn(true); 6380 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6381 MVT::Other, 6382 getControlRoot(), 6383 getValue(I.getArgOperand(0)), 6384 getValue(I.getArgOperand(1)))); 6385 return; 6386 case Intrinsic::eh_unwind_init: 6387 DAG.getMachineFunction().setCallsUnwindInit(true); 6388 return; 6389 case Intrinsic::eh_dwarf_cfa: 6390 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6391 TLI.getPointerTy(DAG.getDataLayout()), 6392 getValue(I.getArgOperand(0)))); 6393 return; 6394 case Intrinsic::eh_sjlj_callsite: { 6395 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6396 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6397 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6398 6399 MMI.setCurrentCallSite(CI->getZExtValue()); 6400 return; 6401 } 6402 case Intrinsic::eh_sjlj_functioncontext: { 6403 // Get and store the index of the function context. 6404 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6405 AllocaInst *FnCtx = 6406 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6407 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6408 MFI.setFunctionContextIndex(FI); 6409 return; 6410 } 6411 case Intrinsic::eh_sjlj_setjmp: { 6412 SDValue Ops[2]; 6413 Ops[0] = getRoot(); 6414 Ops[1] = getValue(I.getArgOperand(0)); 6415 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6416 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6417 setValue(&I, Op.getValue(0)); 6418 DAG.setRoot(Op.getValue(1)); 6419 return; 6420 } 6421 case Intrinsic::eh_sjlj_longjmp: 6422 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6423 getRoot(), getValue(I.getArgOperand(0)))); 6424 return; 6425 case Intrinsic::eh_sjlj_setup_dispatch: 6426 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6427 getRoot())); 6428 return; 6429 case Intrinsic::masked_gather: 6430 visitMaskedGather(I); 6431 return; 6432 case Intrinsic::masked_load: 6433 visitMaskedLoad(I); 6434 return; 6435 case Intrinsic::masked_scatter: 6436 visitMaskedScatter(I); 6437 return; 6438 case Intrinsic::masked_store: 6439 visitMaskedStore(I); 6440 return; 6441 case Intrinsic::masked_expandload: 6442 visitMaskedLoad(I, true /* IsExpanding */); 6443 return; 6444 case Intrinsic::masked_compressstore: 6445 visitMaskedStore(I, true /* IsCompressing */); 6446 return; 6447 case Intrinsic::powi: 6448 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6449 getValue(I.getArgOperand(1)), DAG)); 6450 return; 6451 case Intrinsic::log: 6452 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6453 return; 6454 case Intrinsic::log2: 6455 setValue(&I, 6456 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6457 return; 6458 case Intrinsic::log10: 6459 setValue(&I, 6460 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6461 return; 6462 case Intrinsic::exp: 6463 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6464 return; 6465 case Intrinsic::exp2: 6466 setValue(&I, 6467 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6468 return; 6469 case Intrinsic::pow: 6470 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6471 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6472 return; 6473 case Intrinsic::sqrt: 6474 case Intrinsic::fabs: 6475 case Intrinsic::sin: 6476 case Intrinsic::cos: 6477 case Intrinsic::exp10: 6478 case Intrinsic::floor: 6479 case Intrinsic::ceil: 6480 case Intrinsic::trunc: 6481 case Intrinsic::rint: 6482 case Intrinsic::nearbyint: 6483 case Intrinsic::round: 6484 case Intrinsic::roundeven: 6485 case Intrinsic::canonicalize: { 6486 unsigned Opcode; 6487 switch (Intrinsic) { 6488 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6489 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6490 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6491 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6492 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6493 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6494 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6495 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6496 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6497 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6498 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6499 case Intrinsic::round: Opcode = ISD::FROUND; break; 6500 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6501 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6502 } 6503 6504 setValue(&I, DAG.getNode(Opcode, sdl, 6505 getValue(I.getArgOperand(0)).getValueType(), 6506 getValue(I.getArgOperand(0)), Flags)); 6507 return; 6508 } 6509 case Intrinsic::lround: 6510 case Intrinsic::llround: 6511 case Intrinsic::lrint: 6512 case Intrinsic::llrint: { 6513 unsigned Opcode; 6514 switch (Intrinsic) { 6515 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6516 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6517 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6518 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6519 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6520 } 6521 6522 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6523 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6524 getValue(I.getArgOperand(0)))); 6525 return; 6526 } 6527 case Intrinsic::minnum: 6528 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6529 getValue(I.getArgOperand(0)).getValueType(), 6530 getValue(I.getArgOperand(0)), 6531 getValue(I.getArgOperand(1)), Flags)); 6532 return; 6533 case Intrinsic::maxnum: 6534 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6535 getValue(I.getArgOperand(0)).getValueType(), 6536 getValue(I.getArgOperand(0)), 6537 getValue(I.getArgOperand(1)), Flags)); 6538 return; 6539 case Intrinsic::minimum: 6540 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6541 getValue(I.getArgOperand(0)).getValueType(), 6542 getValue(I.getArgOperand(0)), 6543 getValue(I.getArgOperand(1)), Flags)); 6544 return; 6545 case Intrinsic::maximum: 6546 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6547 getValue(I.getArgOperand(0)).getValueType(), 6548 getValue(I.getArgOperand(0)), 6549 getValue(I.getArgOperand(1)), Flags)); 6550 return; 6551 case Intrinsic::copysign: 6552 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6553 getValue(I.getArgOperand(0)).getValueType(), 6554 getValue(I.getArgOperand(0)), 6555 getValue(I.getArgOperand(1)), Flags)); 6556 return; 6557 case Intrinsic::ldexp: 6558 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6559 getValue(I.getArgOperand(0)).getValueType(), 6560 getValue(I.getArgOperand(0)), 6561 getValue(I.getArgOperand(1)), Flags)); 6562 return; 6563 case Intrinsic::frexp: { 6564 SmallVector<EVT, 2> ValueVTs; 6565 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6566 SDVTList VTs = DAG.getVTList(ValueVTs); 6567 setValue(&I, 6568 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6569 return; 6570 } 6571 case Intrinsic::arithmetic_fence: { 6572 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6573 getValue(I.getArgOperand(0)).getValueType(), 6574 getValue(I.getArgOperand(0)), Flags)); 6575 return; 6576 } 6577 case Intrinsic::fma: 6578 setValue(&I, DAG.getNode( 6579 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6580 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6581 getValue(I.getArgOperand(2)), Flags)); 6582 return; 6583 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6584 case Intrinsic::INTRINSIC: 6585 #include "llvm/IR/ConstrainedOps.def" 6586 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6587 return; 6588 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6589 #include "llvm/IR/VPIntrinsics.def" 6590 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6591 return; 6592 case Intrinsic::fptrunc_round: { 6593 // Get the last argument, the metadata and convert it to an integer in the 6594 // call 6595 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6596 std::optional<RoundingMode> RoundMode = 6597 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6598 6599 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6600 6601 // Propagate fast-math-flags from IR to node(s). 6602 SDNodeFlags Flags; 6603 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6604 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6605 6606 SDValue Result; 6607 Result = DAG.getNode( 6608 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6609 DAG.getTargetConstant((int)*RoundMode, sdl, 6610 TLI.getPointerTy(DAG.getDataLayout()))); 6611 setValue(&I, Result); 6612 6613 return; 6614 } 6615 case Intrinsic::fmuladd: { 6616 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6617 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6618 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6619 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6620 getValue(I.getArgOperand(0)).getValueType(), 6621 getValue(I.getArgOperand(0)), 6622 getValue(I.getArgOperand(1)), 6623 getValue(I.getArgOperand(2)), Flags)); 6624 } else { 6625 // TODO: Intrinsic calls should have fast-math-flags. 6626 SDValue Mul = DAG.getNode( 6627 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6628 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6629 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6630 getValue(I.getArgOperand(0)).getValueType(), 6631 Mul, getValue(I.getArgOperand(2)), Flags); 6632 setValue(&I, Add); 6633 } 6634 return; 6635 } 6636 case Intrinsic::convert_to_fp16: 6637 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6638 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6639 getValue(I.getArgOperand(0)), 6640 DAG.getTargetConstant(0, sdl, 6641 MVT::i32)))); 6642 return; 6643 case Intrinsic::convert_from_fp16: 6644 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6645 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6646 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6647 getValue(I.getArgOperand(0))))); 6648 return; 6649 case Intrinsic::fptosi_sat: { 6650 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6651 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6652 getValue(I.getArgOperand(0)), 6653 DAG.getValueType(VT.getScalarType()))); 6654 return; 6655 } 6656 case Intrinsic::fptoui_sat: { 6657 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6658 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6659 getValue(I.getArgOperand(0)), 6660 DAG.getValueType(VT.getScalarType()))); 6661 return; 6662 } 6663 case Intrinsic::set_rounding: 6664 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6665 {getRoot(), getValue(I.getArgOperand(0))}); 6666 setValue(&I, Res); 6667 DAG.setRoot(Res.getValue(0)); 6668 return; 6669 case Intrinsic::is_fpclass: { 6670 const DataLayout DLayout = DAG.getDataLayout(); 6671 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6672 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6673 FPClassTest Test = static_cast<FPClassTest>( 6674 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6675 MachineFunction &MF = DAG.getMachineFunction(); 6676 const Function &F = MF.getFunction(); 6677 SDValue Op = getValue(I.getArgOperand(0)); 6678 SDNodeFlags Flags; 6679 Flags.setNoFPExcept( 6680 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6681 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6682 // expansion can use illegal types. Making expansion early allows 6683 // legalizing these types prior to selection. 6684 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6685 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6686 setValue(&I, Result); 6687 return; 6688 } 6689 6690 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6691 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6692 setValue(&I, V); 6693 return; 6694 } 6695 case Intrinsic::get_fpenv: { 6696 const DataLayout DLayout = DAG.getDataLayout(); 6697 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6698 Align TempAlign = DAG.getEVTAlign(EnvVT); 6699 SDValue Chain = getRoot(); 6700 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6701 // and temporary storage in stack. 6702 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6703 Res = DAG.getNode( 6704 ISD::GET_FPENV, sdl, 6705 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6706 MVT::Other), 6707 Chain); 6708 } else { 6709 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6710 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6711 auto MPI = 6712 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6713 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6714 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6715 TempAlign); 6716 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6717 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6718 } 6719 setValue(&I, Res); 6720 DAG.setRoot(Res.getValue(1)); 6721 return; 6722 } 6723 case Intrinsic::set_fpenv: { 6724 const DataLayout DLayout = DAG.getDataLayout(); 6725 SDValue Env = getValue(I.getArgOperand(0)); 6726 EVT EnvVT = Env.getValueType(); 6727 Align TempAlign = DAG.getEVTAlign(EnvVT); 6728 SDValue Chain = getRoot(); 6729 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6730 // environment from memory. 6731 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6732 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6733 } else { 6734 // Allocate space in stack, copy environment bits into it and use this 6735 // memory in SET_FPENV_MEM. 6736 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6737 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6738 auto MPI = 6739 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6740 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6741 MachineMemOperand::MOStore); 6742 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6743 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6744 TempAlign); 6745 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6746 } 6747 DAG.setRoot(Chain); 6748 return; 6749 } 6750 case Intrinsic::reset_fpenv: 6751 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6752 return; 6753 case Intrinsic::get_fpmode: 6754 Res = DAG.getNode( 6755 ISD::GET_FPMODE, sdl, 6756 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6757 MVT::Other), 6758 DAG.getRoot()); 6759 setValue(&I, Res); 6760 DAG.setRoot(Res.getValue(1)); 6761 return; 6762 case Intrinsic::set_fpmode: 6763 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6764 getValue(I.getArgOperand(0))); 6765 DAG.setRoot(Res); 6766 return; 6767 case Intrinsic::reset_fpmode: { 6768 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6769 DAG.setRoot(Res); 6770 return; 6771 } 6772 case Intrinsic::pcmarker: { 6773 SDValue Tmp = getValue(I.getArgOperand(0)); 6774 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6775 return; 6776 } 6777 case Intrinsic::readcyclecounter: { 6778 SDValue Op = getRoot(); 6779 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6780 DAG.getVTList(MVT::i64, MVT::Other), Op); 6781 setValue(&I, Res); 6782 DAG.setRoot(Res.getValue(1)); 6783 return; 6784 } 6785 case Intrinsic::readsteadycounter: { 6786 SDValue Op = getRoot(); 6787 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 6788 DAG.getVTList(MVT::i64, MVT::Other), Op); 6789 setValue(&I, Res); 6790 DAG.setRoot(Res.getValue(1)); 6791 return; 6792 } 6793 case Intrinsic::bitreverse: 6794 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6795 getValue(I.getArgOperand(0)).getValueType(), 6796 getValue(I.getArgOperand(0)))); 6797 return; 6798 case Intrinsic::bswap: 6799 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6800 getValue(I.getArgOperand(0)).getValueType(), 6801 getValue(I.getArgOperand(0)))); 6802 return; 6803 case Intrinsic::cttz: { 6804 SDValue Arg = getValue(I.getArgOperand(0)); 6805 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6806 EVT Ty = Arg.getValueType(); 6807 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6808 sdl, Ty, Arg)); 6809 return; 6810 } 6811 case Intrinsic::ctlz: { 6812 SDValue Arg = getValue(I.getArgOperand(0)); 6813 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6814 EVT Ty = Arg.getValueType(); 6815 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6816 sdl, Ty, Arg)); 6817 return; 6818 } 6819 case Intrinsic::ctpop: { 6820 SDValue Arg = getValue(I.getArgOperand(0)); 6821 EVT Ty = Arg.getValueType(); 6822 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6823 return; 6824 } 6825 case Intrinsic::fshl: 6826 case Intrinsic::fshr: { 6827 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6828 SDValue X = getValue(I.getArgOperand(0)); 6829 SDValue Y = getValue(I.getArgOperand(1)); 6830 SDValue Z = getValue(I.getArgOperand(2)); 6831 EVT VT = X.getValueType(); 6832 6833 if (X == Y) { 6834 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6835 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6836 } else { 6837 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6838 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6839 } 6840 return; 6841 } 6842 case Intrinsic::sadd_sat: { 6843 SDValue Op1 = getValue(I.getArgOperand(0)); 6844 SDValue Op2 = getValue(I.getArgOperand(1)); 6845 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6846 return; 6847 } 6848 case Intrinsic::uadd_sat: { 6849 SDValue Op1 = getValue(I.getArgOperand(0)); 6850 SDValue Op2 = getValue(I.getArgOperand(1)); 6851 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6852 return; 6853 } 6854 case Intrinsic::ssub_sat: { 6855 SDValue Op1 = getValue(I.getArgOperand(0)); 6856 SDValue Op2 = getValue(I.getArgOperand(1)); 6857 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6858 return; 6859 } 6860 case Intrinsic::usub_sat: { 6861 SDValue Op1 = getValue(I.getArgOperand(0)); 6862 SDValue Op2 = getValue(I.getArgOperand(1)); 6863 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6864 return; 6865 } 6866 case Intrinsic::sshl_sat: { 6867 SDValue Op1 = getValue(I.getArgOperand(0)); 6868 SDValue Op2 = getValue(I.getArgOperand(1)); 6869 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6870 return; 6871 } 6872 case Intrinsic::ushl_sat: { 6873 SDValue Op1 = getValue(I.getArgOperand(0)); 6874 SDValue Op2 = getValue(I.getArgOperand(1)); 6875 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6876 return; 6877 } 6878 case Intrinsic::smul_fix: 6879 case Intrinsic::umul_fix: 6880 case Intrinsic::smul_fix_sat: 6881 case Intrinsic::umul_fix_sat: { 6882 SDValue Op1 = getValue(I.getArgOperand(0)); 6883 SDValue Op2 = getValue(I.getArgOperand(1)); 6884 SDValue Op3 = getValue(I.getArgOperand(2)); 6885 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6886 Op1.getValueType(), Op1, Op2, Op3)); 6887 return; 6888 } 6889 case Intrinsic::sdiv_fix: 6890 case Intrinsic::udiv_fix: 6891 case Intrinsic::sdiv_fix_sat: 6892 case Intrinsic::udiv_fix_sat: { 6893 SDValue Op1 = getValue(I.getArgOperand(0)); 6894 SDValue Op2 = getValue(I.getArgOperand(1)); 6895 SDValue Op3 = getValue(I.getArgOperand(2)); 6896 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6897 Op1, Op2, Op3, DAG, TLI)); 6898 return; 6899 } 6900 case Intrinsic::smax: { 6901 SDValue Op1 = getValue(I.getArgOperand(0)); 6902 SDValue Op2 = getValue(I.getArgOperand(1)); 6903 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6904 return; 6905 } 6906 case Intrinsic::smin: { 6907 SDValue Op1 = getValue(I.getArgOperand(0)); 6908 SDValue Op2 = getValue(I.getArgOperand(1)); 6909 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6910 return; 6911 } 6912 case Intrinsic::umax: { 6913 SDValue Op1 = getValue(I.getArgOperand(0)); 6914 SDValue Op2 = getValue(I.getArgOperand(1)); 6915 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6916 return; 6917 } 6918 case Intrinsic::umin: { 6919 SDValue Op1 = getValue(I.getArgOperand(0)); 6920 SDValue Op2 = getValue(I.getArgOperand(1)); 6921 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6922 return; 6923 } 6924 case Intrinsic::abs: { 6925 // TODO: Preserve "int min is poison" arg in SDAG? 6926 SDValue Op1 = getValue(I.getArgOperand(0)); 6927 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6928 return; 6929 } 6930 case Intrinsic::stacksave: { 6931 SDValue Op = getRoot(); 6932 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6933 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6934 setValue(&I, Res); 6935 DAG.setRoot(Res.getValue(1)); 6936 return; 6937 } 6938 case Intrinsic::stackrestore: 6939 Res = getValue(I.getArgOperand(0)); 6940 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6941 return; 6942 case Intrinsic::get_dynamic_area_offset: { 6943 SDValue Op = getRoot(); 6944 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6945 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6946 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6947 // target. 6948 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6949 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6950 " intrinsic!"); 6951 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6952 Op); 6953 DAG.setRoot(Op); 6954 setValue(&I, Res); 6955 return; 6956 } 6957 case Intrinsic::stackguard: { 6958 MachineFunction &MF = DAG.getMachineFunction(); 6959 const Module &M = *MF.getFunction().getParent(); 6960 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6961 SDValue Chain = getRoot(); 6962 if (TLI.useLoadStackGuardNode()) { 6963 Res = getLoadStackGuard(DAG, sdl, Chain); 6964 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 6965 } else { 6966 const Value *Global = TLI.getSDagStackGuard(M); 6967 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6968 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6969 MachinePointerInfo(Global, 0), Align, 6970 MachineMemOperand::MOVolatile); 6971 } 6972 if (TLI.useStackGuardXorFP()) 6973 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6974 DAG.setRoot(Chain); 6975 setValue(&I, Res); 6976 return; 6977 } 6978 case Intrinsic::stackprotector: { 6979 // Emit code into the DAG to store the stack guard onto the stack. 6980 MachineFunction &MF = DAG.getMachineFunction(); 6981 MachineFrameInfo &MFI = MF.getFrameInfo(); 6982 SDValue Src, Chain = getRoot(); 6983 6984 if (TLI.useLoadStackGuardNode()) 6985 Src = getLoadStackGuard(DAG, sdl, Chain); 6986 else 6987 Src = getValue(I.getArgOperand(0)); // The guard's value. 6988 6989 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6990 6991 int FI = FuncInfo.StaticAllocaMap[Slot]; 6992 MFI.setStackProtectorIndex(FI); 6993 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6994 6995 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6996 6997 // Store the stack protector onto the stack. 6998 Res = DAG.getStore( 6999 Chain, sdl, Src, FIN, 7000 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7001 MaybeAlign(), MachineMemOperand::MOVolatile); 7002 setValue(&I, Res); 7003 DAG.setRoot(Res); 7004 return; 7005 } 7006 case Intrinsic::objectsize: 7007 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7008 7009 case Intrinsic::is_constant: 7010 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7011 7012 case Intrinsic::annotation: 7013 case Intrinsic::ptr_annotation: 7014 case Intrinsic::launder_invariant_group: 7015 case Intrinsic::strip_invariant_group: 7016 // Drop the intrinsic, but forward the value 7017 setValue(&I, getValue(I.getOperand(0))); 7018 return; 7019 7020 case Intrinsic::assume: 7021 case Intrinsic::experimental_noalias_scope_decl: 7022 case Intrinsic::var_annotation: 7023 case Intrinsic::sideeffect: 7024 // Discard annotate attributes, noalias scope declarations, assumptions, and 7025 // artificial side-effects. 7026 return; 7027 7028 case Intrinsic::codeview_annotation: { 7029 // Emit a label associated with this metadata. 7030 MachineFunction &MF = DAG.getMachineFunction(); 7031 MCSymbol *Label = 7032 MF.getMMI().getContext().createTempSymbol("annotation", true); 7033 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7034 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7035 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7036 DAG.setRoot(Res); 7037 return; 7038 } 7039 7040 case Intrinsic::init_trampoline: { 7041 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7042 7043 SDValue Ops[6]; 7044 Ops[0] = getRoot(); 7045 Ops[1] = getValue(I.getArgOperand(0)); 7046 Ops[2] = getValue(I.getArgOperand(1)); 7047 Ops[3] = getValue(I.getArgOperand(2)); 7048 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7049 Ops[5] = DAG.getSrcValue(F); 7050 7051 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7052 7053 DAG.setRoot(Res); 7054 return; 7055 } 7056 case Intrinsic::adjust_trampoline: 7057 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7058 TLI.getPointerTy(DAG.getDataLayout()), 7059 getValue(I.getArgOperand(0)))); 7060 return; 7061 case Intrinsic::gcroot: { 7062 assert(DAG.getMachineFunction().getFunction().hasGC() && 7063 "only valid in functions with gc specified, enforced by Verifier"); 7064 assert(GFI && "implied by previous"); 7065 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7066 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7067 7068 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7069 GFI->addStackRoot(FI->getIndex(), TypeMap); 7070 return; 7071 } 7072 case Intrinsic::gcread: 7073 case Intrinsic::gcwrite: 7074 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7075 case Intrinsic::get_rounding: 7076 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7077 setValue(&I, Res); 7078 DAG.setRoot(Res.getValue(1)); 7079 return; 7080 7081 case Intrinsic::expect: 7082 // Just replace __builtin_expect(exp, c) with EXP. 7083 setValue(&I, getValue(I.getArgOperand(0))); 7084 return; 7085 7086 case Intrinsic::ubsantrap: 7087 case Intrinsic::debugtrap: 7088 case Intrinsic::trap: { 7089 StringRef TrapFuncName = 7090 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7091 if (TrapFuncName.empty()) { 7092 switch (Intrinsic) { 7093 case Intrinsic::trap: 7094 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7095 break; 7096 case Intrinsic::debugtrap: 7097 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7098 break; 7099 case Intrinsic::ubsantrap: 7100 DAG.setRoot(DAG.getNode( 7101 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7102 DAG.getTargetConstant( 7103 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7104 MVT::i32))); 7105 break; 7106 default: llvm_unreachable("unknown trap intrinsic"); 7107 } 7108 return; 7109 } 7110 TargetLowering::ArgListTy Args; 7111 if (Intrinsic == Intrinsic::ubsantrap) { 7112 Args.push_back(TargetLoweringBase::ArgListEntry()); 7113 Args[0].Val = I.getArgOperand(0); 7114 Args[0].Node = getValue(Args[0].Val); 7115 Args[0].Ty = Args[0].Val->getType(); 7116 } 7117 7118 TargetLowering::CallLoweringInfo CLI(DAG); 7119 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7120 CallingConv::C, I.getType(), 7121 DAG.getExternalSymbol(TrapFuncName.data(), 7122 TLI.getPointerTy(DAG.getDataLayout())), 7123 std::move(Args)); 7124 7125 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7126 DAG.setRoot(Result.second); 7127 return; 7128 } 7129 7130 case Intrinsic::uadd_with_overflow: 7131 case Intrinsic::sadd_with_overflow: 7132 case Intrinsic::usub_with_overflow: 7133 case Intrinsic::ssub_with_overflow: 7134 case Intrinsic::umul_with_overflow: 7135 case Intrinsic::smul_with_overflow: { 7136 ISD::NodeType Op; 7137 switch (Intrinsic) { 7138 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7139 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7140 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7141 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7142 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7143 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7144 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7145 } 7146 SDValue Op1 = getValue(I.getArgOperand(0)); 7147 SDValue Op2 = getValue(I.getArgOperand(1)); 7148 7149 EVT ResultVT = Op1.getValueType(); 7150 EVT OverflowVT = MVT::i1; 7151 if (ResultVT.isVector()) 7152 OverflowVT = EVT::getVectorVT( 7153 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7154 7155 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7156 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7157 return; 7158 } 7159 case Intrinsic::prefetch: { 7160 SDValue Ops[5]; 7161 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7162 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7163 Ops[0] = DAG.getRoot(); 7164 Ops[1] = getValue(I.getArgOperand(0)); 7165 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7166 MVT::i32); 7167 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7168 MVT::i32); 7169 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7170 MVT::i32); 7171 SDValue Result = DAG.getMemIntrinsicNode( 7172 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7173 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7174 /* align */ std::nullopt, Flags); 7175 7176 // Chain the prefetch in parallel with any pending loads, to stay out of 7177 // the way of later optimizations. 7178 PendingLoads.push_back(Result); 7179 Result = getRoot(); 7180 DAG.setRoot(Result); 7181 return; 7182 } 7183 case Intrinsic::lifetime_start: 7184 case Intrinsic::lifetime_end: { 7185 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7186 // Stack coloring is not enabled in O0, discard region information. 7187 if (TM.getOptLevel() == CodeGenOptLevel::None) 7188 return; 7189 7190 const int64_t ObjectSize = 7191 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7192 Value *const ObjectPtr = I.getArgOperand(1); 7193 SmallVector<const Value *, 4> Allocas; 7194 getUnderlyingObjects(ObjectPtr, Allocas); 7195 7196 for (const Value *Alloca : Allocas) { 7197 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7198 7199 // Could not find an Alloca. 7200 if (!LifetimeObject) 7201 continue; 7202 7203 // First check that the Alloca is static, otherwise it won't have a 7204 // valid frame index. 7205 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7206 if (SI == FuncInfo.StaticAllocaMap.end()) 7207 return; 7208 7209 const int FrameIndex = SI->second; 7210 int64_t Offset; 7211 if (GetPointerBaseWithConstantOffset( 7212 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7213 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7214 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7215 Offset); 7216 DAG.setRoot(Res); 7217 } 7218 return; 7219 } 7220 case Intrinsic::pseudoprobe: { 7221 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7222 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7223 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7224 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7225 DAG.setRoot(Res); 7226 return; 7227 } 7228 case Intrinsic::invariant_start: 7229 // Discard region information. 7230 setValue(&I, 7231 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7232 return; 7233 case Intrinsic::invariant_end: 7234 // Discard region information. 7235 return; 7236 case Intrinsic::clear_cache: 7237 /// FunctionName may be null. 7238 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7239 lowerCallToExternalSymbol(I, FunctionName); 7240 return; 7241 case Intrinsic::donothing: 7242 case Intrinsic::seh_try_begin: 7243 case Intrinsic::seh_scope_begin: 7244 case Intrinsic::seh_try_end: 7245 case Intrinsic::seh_scope_end: 7246 // ignore 7247 return; 7248 case Intrinsic::experimental_stackmap: 7249 visitStackmap(I); 7250 return; 7251 case Intrinsic::experimental_patchpoint_void: 7252 case Intrinsic::experimental_patchpoint_i64: 7253 visitPatchpoint(I); 7254 return; 7255 case Intrinsic::experimental_gc_statepoint: 7256 LowerStatepoint(cast<GCStatepointInst>(I)); 7257 return; 7258 case Intrinsic::experimental_gc_result: 7259 visitGCResult(cast<GCResultInst>(I)); 7260 return; 7261 case Intrinsic::experimental_gc_relocate: 7262 visitGCRelocate(cast<GCRelocateInst>(I)); 7263 return; 7264 case Intrinsic::instrprof_cover: 7265 llvm_unreachable("instrprof failed to lower a cover"); 7266 case Intrinsic::instrprof_increment: 7267 llvm_unreachable("instrprof failed to lower an increment"); 7268 case Intrinsic::instrprof_timestamp: 7269 llvm_unreachable("instrprof failed to lower a timestamp"); 7270 case Intrinsic::instrprof_value_profile: 7271 llvm_unreachable("instrprof failed to lower a value profiling call"); 7272 case Intrinsic::instrprof_mcdc_parameters: 7273 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7274 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7275 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7276 case Intrinsic::instrprof_mcdc_condbitmap_update: 7277 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7278 case Intrinsic::localescape: { 7279 MachineFunction &MF = DAG.getMachineFunction(); 7280 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7281 7282 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7283 // is the same on all targets. 7284 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7285 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7286 if (isa<ConstantPointerNull>(Arg)) 7287 continue; // Skip null pointers. They represent a hole in index space. 7288 AllocaInst *Slot = cast<AllocaInst>(Arg); 7289 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7290 "can only escape static allocas"); 7291 int FI = FuncInfo.StaticAllocaMap[Slot]; 7292 MCSymbol *FrameAllocSym = 7293 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7294 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7296 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7297 .addSym(FrameAllocSym) 7298 .addFrameIndex(FI); 7299 } 7300 7301 return; 7302 } 7303 7304 case Intrinsic::localrecover: { 7305 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7306 MachineFunction &MF = DAG.getMachineFunction(); 7307 7308 // Get the symbol that defines the frame offset. 7309 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7310 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7311 unsigned IdxVal = 7312 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7313 MCSymbol *FrameAllocSym = 7314 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7315 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7316 7317 Value *FP = I.getArgOperand(1); 7318 SDValue FPVal = getValue(FP); 7319 EVT PtrVT = FPVal.getValueType(); 7320 7321 // Create a MCSymbol for the label to avoid any target lowering 7322 // that would make this PC relative. 7323 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7324 SDValue OffsetVal = 7325 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7326 7327 // Add the offset to the FP. 7328 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7329 setValue(&I, Add); 7330 7331 return; 7332 } 7333 7334 case Intrinsic::eh_exceptionpointer: 7335 case Intrinsic::eh_exceptioncode: { 7336 // Get the exception pointer vreg, copy from it, and resize it to fit. 7337 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7338 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7339 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7340 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7341 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7342 if (Intrinsic == Intrinsic::eh_exceptioncode) 7343 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7344 setValue(&I, N); 7345 return; 7346 } 7347 case Intrinsic::xray_customevent: { 7348 // Here we want to make sure that the intrinsic behaves as if it has a 7349 // specific calling convention. 7350 const auto &Triple = DAG.getTarget().getTargetTriple(); 7351 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7352 return; 7353 7354 SmallVector<SDValue, 8> Ops; 7355 7356 // We want to say that we always want the arguments in registers. 7357 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7358 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7359 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7360 SDValue Chain = getRoot(); 7361 Ops.push_back(LogEntryVal); 7362 Ops.push_back(StrSizeVal); 7363 Ops.push_back(Chain); 7364 7365 // We need to enforce the calling convention for the callsite, so that 7366 // argument ordering is enforced correctly, and that register allocation can 7367 // see that some registers may be assumed clobbered and have to preserve 7368 // them across calls to the intrinsic. 7369 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7370 sdl, NodeTys, Ops); 7371 SDValue patchableNode = SDValue(MN, 0); 7372 DAG.setRoot(patchableNode); 7373 setValue(&I, patchableNode); 7374 return; 7375 } 7376 case Intrinsic::xray_typedevent: { 7377 // Here we want to make sure that the intrinsic behaves as if it has a 7378 // specific calling convention. 7379 const auto &Triple = DAG.getTarget().getTargetTriple(); 7380 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7381 return; 7382 7383 SmallVector<SDValue, 8> Ops; 7384 7385 // We want to say that we always want the arguments in registers. 7386 // It's unclear to me how manipulating the selection DAG here forces callers 7387 // to provide arguments in registers instead of on the stack. 7388 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7389 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7390 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7391 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7392 SDValue Chain = getRoot(); 7393 Ops.push_back(LogTypeId); 7394 Ops.push_back(LogEntryVal); 7395 Ops.push_back(StrSizeVal); 7396 Ops.push_back(Chain); 7397 7398 // We need to enforce the calling convention for the callsite, so that 7399 // argument ordering is enforced correctly, and that register allocation can 7400 // see that some registers may be assumed clobbered and have to preserve 7401 // them across calls to the intrinsic. 7402 MachineSDNode *MN = DAG.getMachineNode( 7403 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7404 SDValue patchableNode = SDValue(MN, 0); 7405 DAG.setRoot(patchableNode); 7406 setValue(&I, patchableNode); 7407 return; 7408 } 7409 case Intrinsic::experimental_deoptimize: 7410 LowerDeoptimizeCall(&I); 7411 return; 7412 case Intrinsic::experimental_stepvector: 7413 visitStepVector(I); 7414 return; 7415 case Intrinsic::vector_reduce_fadd: 7416 case Intrinsic::vector_reduce_fmul: 7417 case Intrinsic::vector_reduce_add: 7418 case Intrinsic::vector_reduce_mul: 7419 case Intrinsic::vector_reduce_and: 7420 case Intrinsic::vector_reduce_or: 7421 case Intrinsic::vector_reduce_xor: 7422 case Intrinsic::vector_reduce_smax: 7423 case Intrinsic::vector_reduce_smin: 7424 case Intrinsic::vector_reduce_umax: 7425 case Intrinsic::vector_reduce_umin: 7426 case Intrinsic::vector_reduce_fmax: 7427 case Intrinsic::vector_reduce_fmin: 7428 case Intrinsic::vector_reduce_fmaximum: 7429 case Intrinsic::vector_reduce_fminimum: 7430 visitVectorReduce(I, Intrinsic); 7431 return; 7432 7433 case Intrinsic::icall_branch_funnel: { 7434 SmallVector<SDValue, 16> Ops; 7435 Ops.push_back(getValue(I.getArgOperand(0))); 7436 7437 int64_t Offset; 7438 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7439 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7440 if (!Base) 7441 report_fatal_error( 7442 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7443 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7444 7445 struct BranchFunnelTarget { 7446 int64_t Offset; 7447 SDValue Target; 7448 }; 7449 SmallVector<BranchFunnelTarget, 8> Targets; 7450 7451 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7452 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7453 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7454 if (ElemBase != Base) 7455 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7456 "to the same GlobalValue"); 7457 7458 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7459 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7460 if (!GA) 7461 report_fatal_error( 7462 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7463 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7464 GA->getGlobal(), sdl, Val.getValueType(), 7465 GA->getOffset())}); 7466 } 7467 llvm::sort(Targets, 7468 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7469 return T1.Offset < T2.Offset; 7470 }); 7471 7472 for (auto &T : Targets) { 7473 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7474 Ops.push_back(T.Target); 7475 } 7476 7477 Ops.push_back(DAG.getRoot()); // Chain 7478 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7479 MVT::Other, Ops), 7480 0); 7481 DAG.setRoot(N); 7482 setValue(&I, N); 7483 HasTailCall = true; 7484 return; 7485 } 7486 7487 case Intrinsic::wasm_landingpad_index: 7488 // Information this intrinsic contained has been transferred to 7489 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7490 // delete it now. 7491 return; 7492 7493 case Intrinsic::aarch64_settag: 7494 case Intrinsic::aarch64_settag_zero: { 7495 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7496 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7497 SDValue Val = TSI.EmitTargetCodeForSetTag( 7498 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7499 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7500 ZeroMemory); 7501 DAG.setRoot(Val); 7502 setValue(&I, Val); 7503 return; 7504 } 7505 case Intrinsic::amdgcn_cs_chain: { 7506 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7507 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7508 "Non-zero flags not supported yet"); 7509 7510 // At this point we don't care if it's amdgpu_cs_chain or 7511 // amdgpu_cs_chain_preserve. 7512 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7513 7514 Type *RetTy = I.getType(); 7515 assert(RetTy->isVoidTy() && "Should not return"); 7516 7517 SDValue Callee = getValue(I.getOperand(0)); 7518 7519 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7520 // We'll also tack the value of the EXEC mask at the end. 7521 TargetLowering::ArgListTy Args; 7522 Args.reserve(3); 7523 7524 for (unsigned Idx : {2, 3, 1}) { 7525 TargetLowering::ArgListEntry Arg; 7526 Arg.Node = getValue(I.getOperand(Idx)); 7527 Arg.Ty = I.getOperand(Idx)->getType(); 7528 Arg.setAttributes(&I, Idx); 7529 Args.push_back(Arg); 7530 } 7531 7532 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7533 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7534 Args[2].IsInReg = true; // EXEC should be inreg 7535 7536 TargetLowering::CallLoweringInfo CLI(DAG); 7537 CLI.setDebugLoc(getCurSDLoc()) 7538 .setChain(getRoot()) 7539 .setCallee(CC, RetTy, Callee, std::move(Args)) 7540 .setNoReturn(true) 7541 .setTailCall(true) 7542 .setConvergent(I.isConvergent()); 7543 CLI.CB = &I; 7544 std::pair<SDValue, SDValue> Result = 7545 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7546 (void)Result; 7547 assert(!Result.first.getNode() && !Result.second.getNode() && 7548 "Should've lowered as tail call"); 7549 7550 HasTailCall = true; 7551 return; 7552 } 7553 case Intrinsic::ptrmask: { 7554 SDValue Ptr = getValue(I.getOperand(0)); 7555 SDValue Mask = getValue(I.getOperand(1)); 7556 7557 EVT PtrVT = Ptr.getValueType(); 7558 assert(PtrVT == Mask.getValueType() && 7559 "Pointers with different index type are not supported by SDAG"); 7560 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7561 return; 7562 } 7563 case Intrinsic::threadlocal_address: { 7564 setValue(&I, getValue(I.getOperand(0))); 7565 return; 7566 } 7567 case Intrinsic::get_active_lane_mask: { 7568 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7569 SDValue Index = getValue(I.getOperand(0)); 7570 EVT ElementVT = Index.getValueType(); 7571 7572 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7573 visitTargetIntrinsic(I, Intrinsic); 7574 return; 7575 } 7576 7577 SDValue TripCount = getValue(I.getOperand(1)); 7578 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7579 CCVT.getVectorElementCount()); 7580 7581 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7582 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7583 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7584 SDValue VectorInduction = DAG.getNode( 7585 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7586 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7587 VectorTripCount, ISD::CondCode::SETULT); 7588 setValue(&I, SetCC); 7589 return; 7590 } 7591 case Intrinsic::experimental_get_vector_length: { 7592 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7593 "Expected positive VF"); 7594 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7595 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7596 7597 SDValue Count = getValue(I.getOperand(0)); 7598 EVT CountVT = Count.getValueType(); 7599 7600 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7601 visitTargetIntrinsic(I, Intrinsic); 7602 return; 7603 } 7604 7605 // Expand to a umin between the trip count and the maximum elements the type 7606 // can hold. 7607 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7608 7609 // Extend the trip count to at least the result VT. 7610 if (CountVT.bitsLT(VT)) { 7611 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7612 CountVT = VT; 7613 } 7614 7615 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7616 ElementCount::get(VF, IsScalable)); 7617 7618 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7619 // Clip to the result type if needed. 7620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7621 7622 setValue(&I, Trunc); 7623 return; 7624 } 7625 case Intrinsic::experimental_cttz_elts: { 7626 auto DL = getCurSDLoc(); 7627 SDValue Op = getValue(I.getOperand(0)); 7628 EVT OpVT = Op.getValueType(); 7629 7630 if (!TLI.shouldExpandCttzElements(OpVT)) { 7631 visitTargetIntrinsic(I, Intrinsic); 7632 return; 7633 } 7634 7635 if (OpVT.getScalarType() != MVT::i1) { 7636 // Compare the input vector elements to zero & use to count trailing zeros 7637 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7638 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7639 OpVT.getVectorElementCount()); 7640 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7641 } 7642 7643 // Find the smallest "sensible" element type to use for the expansion. 7644 ConstantRange CR( 7645 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7646 if (OpVT.isScalableVT()) 7647 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7648 7649 // If the zero-is-poison flag is set, we can assume the upper limit 7650 // of the result is VF-1. 7651 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7652 CR = CR.subtract(APInt(64, 1)); 7653 7654 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7655 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7656 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7657 7658 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7659 7660 // Create the new vector type & get the vector length 7661 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7662 OpVT.getVectorElementCount()); 7663 7664 SDValue VL = 7665 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7666 7667 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7668 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7669 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7670 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7671 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7672 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7673 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7674 7675 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7676 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7677 7678 setValue(&I, Ret); 7679 return; 7680 } 7681 case Intrinsic::vector_insert: { 7682 SDValue Vec = getValue(I.getOperand(0)); 7683 SDValue SubVec = getValue(I.getOperand(1)); 7684 SDValue Index = getValue(I.getOperand(2)); 7685 7686 // The intrinsic's index type is i64, but the SDNode requires an index type 7687 // suitable for the target. Convert the index as required. 7688 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7689 if (Index.getValueType() != VectorIdxTy) 7690 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7691 7692 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7693 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7694 Index)); 7695 return; 7696 } 7697 case Intrinsic::vector_extract: { 7698 SDValue Vec = getValue(I.getOperand(0)); 7699 SDValue Index = getValue(I.getOperand(1)); 7700 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7701 7702 // The intrinsic's index type is i64, but the SDNode requires an index type 7703 // suitable for the target. Convert the index as required. 7704 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7705 if (Index.getValueType() != VectorIdxTy) 7706 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7707 7708 setValue(&I, 7709 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7710 return; 7711 } 7712 case Intrinsic::experimental_vector_reverse: 7713 visitVectorReverse(I); 7714 return; 7715 case Intrinsic::experimental_vector_splice: 7716 visitVectorSplice(I); 7717 return; 7718 case Intrinsic::callbr_landingpad: 7719 visitCallBrLandingPad(I); 7720 return; 7721 case Intrinsic::experimental_vector_interleave2: 7722 visitVectorInterleave(I); 7723 return; 7724 case Intrinsic::experimental_vector_deinterleave2: 7725 visitVectorDeinterleave(I); 7726 return; 7727 } 7728 } 7729 7730 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7731 const ConstrainedFPIntrinsic &FPI) { 7732 SDLoc sdl = getCurSDLoc(); 7733 7734 // We do not need to serialize constrained FP intrinsics against 7735 // each other or against (nonvolatile) loads, so they can be 7736 // chained like loads. 7737 SDValue Chain = DAG.getRoot(); 7738 SmallVector<SDValue, 4> Opers; 7739 Opers.push_back(Chain); 7740 if (FPI.isUnaryOp()) { 7741 Opers.push_back(getValue(FPI.getArgOperand(0))); 7742 } else if (FPI.isTernaryOp()) { 7743 Opers.push_back(getValue(FPI.getArgOperand(0))); 7744 Opers.push_back(getValue(FPI.getArgOperand(1))); 7745 Opers.push_back(getValue(FPI.getArgOperand(2))); 7746 } else { 7747 Opers.push_back(getValue(FPI.getArgOperand(0))); 7748 Opers.push_back(getValue(FPI.getArgOperand(1))); 7749 } 7750 7751 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7752 assert(Result.getNode()->getNumValues() == 2); 7753 7754 // Push node to the appropriate list so that future instructions can be 7755 // chained up correctly. 7756 SDValue OutChain = Result.getValue(1); 7757 switch (EB) { 7758 case fp::ExceptionBehavior::ebIgnore: 7759 // The only reason why ebIgnore nodes still need to be chained is that 7760 // they might depend on the current rounding mode, and therefore must 7761 // not be moved across instruction that may change that mode. 7762 [[fallthrough]]; 7763 case fp::ExceptionBehavior::ebMayTrap: 7764 // These must not be moved across calls or instructions that may change 7765 // floating-point exception masks. 7766 PendingConstrainedFP.push_back(OutChain); 7767 break; 7768 case fp::ExceptionBehavior::ebStrict: 7769 // These must not be moved across calls or instructions that may change 7770 // floating-point exception masks or read floating-point exception flags. 7771 // In addition, they cannot be optimized out even if unused. 7772 PendingConstrainedFPStrict.push_back(OutChain); 7773 break; 7774 } 7775 }; 7776 7777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7778 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7779 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7780 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7781 7782 SDNodeFlags Flags; 7783 if (EB == fp::ExceptionBehavior::ebIgnore) 7784 Flags.setNoFPExcept(true); 7785 7786 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7787 Flags.copyFMF(*FPOp); 7788 7789 unsigned Opcode; 7790 switch (FPI.getIntrinsicID()) { 7791 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7792 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7793 case Intrinsic::INTRINSIC: \ 7794 Opcode = ISD::STRICT_##DAGN; \ 7795 break; 7796 #include "llvm/IR/ConstrainedOps.def" 7797 case Intrinsic::experimental_constrained_fmuladd: { 7798 Opcode = ISD::STRICT_FMA; 7799 // Break fmuladd into fmul and fadd. 7800 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7801 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7802 Opers.pop_back(); 7803 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7804 pushOutChain(Mul, EB); 7805 Opcode = ISD::STRICT_FADD; 7806 Opers.clear(); 7807 Opers.push_back(Mul.getValue(1)); 7808 Opers.push_back(Mul.getValue(0)); 7809 Opers.push_back(getValue(FPI.getArgOperand(2))); 7810 } 7811 break; 7812 } 7813 } 7814 7815 // A few strict DAG nodes carry additional operands that are not 7816 // set up by the default code above. 7817 switch (Opcode) { 7818 default: break; 7819 case ISD::STRICT_FP_ROUND: 7820 Opers.push_back( 7821 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7822 break; 7823 case ISD::STRICT_FSETCC: 7824 case ISD::STRICT_FSETCCS: { 7825 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7826 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7827 if (TM.Options.NoNaNsFPMath) 7828 Condition = getFCmpCodeWithoutNaN(Condition); 7829 Opers.push_back(DAG.getCondCode(Condition)); 7830 break; 7831 } 7832 } 7833 7834 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7835 pushOutChain(Result, EB); 7836 7837 SDValue FPResult = Result.getValue(0); 7838 setValue(&FPI, FPResult); 7839 } 7840 7841 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7842 std::optional<unsigned> ResOPC; 7843 switch (VPIntrin.getIntrinsicID()) { 7844 case Intrinsic::vp_ctlz: { 7845 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7846 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7847 break; 7848 } 7849 case Intrinsic::vp_cttz: { 7850 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7851 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7852 break; 7853 } 7854 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7855 case Intrinsic::VPID: \ 7856 ResOPC = ISD::VPSD; \ 7857 break; 7858 #include "llvm/IR/VPIntrinsics.def" 7859 } 7860 7861 if (!ResOPC) 7862 llvm_unreachable( 7863 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7864 7865 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7866 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7867 if (VPIntrin.getFastMathFlags().allowReassoc()) 7868 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7869 : ISD::VP_REDUCE_FMUL; 7870 } 7871 7872 return *ResOPC; 7873 } 7874 7875 void SelectionDAGBuilder::visitVPLoad( 7876 const VPIntrinsic &VPIntrin, EVT VT, 7877 const SmallVectorImpl<SDValue> &OpValues) { 7878 SDLoc DL = getCurSDLoc(); 7879 Value *PtrOperand = VPIntrin.getArgOperand(0); 7880 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7881 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7882 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7883 SDValue LD; 7884 // Do not serialize variable-length loads of constant memory with 7885 // anything. 7886 if (!Alignment) 7887 Alignment = DAG.getEVTAlign(VT); 7888 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7889 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7890 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7891 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7892 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7893 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7894 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7895 MMO, false /*IsExpanding */); 7896 if (AddToChain) 7897 PendingLoads.push_back(LD.getValue(1)); 7898 setValue(&VPIntrin, LD); 7899 } 7900 7901 void SelectionDAGBuilder::visitVPGather( 7902 const VPIntrinsic &VPIntrin, EVT VT, 7903 const SmallVectorImpl<SDValue> &OpValues) { 7904 SDLoc DL = getCurSDLoc(); 7905 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7906 Value *PtrOperand = VPIntrin.getArgOperand(0); 7907 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7908 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7909 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7910 SDValue LD; 7911 if (!Alignment) 7912 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7913 unsigned AS = 7914 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7915 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7916 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7917 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7918 SDValue Base, Index, Scale; 7919 ISD::MemIndexType IndexType; 7920 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7921 this, VPIntrin.getParent(), 7922 VT.getScalarStoreSize()); 7923 if (!UniformBase) { 7924 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7925 Index = getValue(PtrOperand); 7926 IndexType = ISD::SIGNED_SCALED; 7927 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7928 } 7929 EVT IdxVT = Index.getValueType(); 7930 EVT EltTy = IdxVT.getVectorElementType(); 7931 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7932 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7933 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7934 } 7935 LD = DAG.getGatherVP( 7936 DAG.getVTList(VT, MVT::Other), VT, DL, 7937 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7938 IndexType); 7939 PendingLoads.push_back(LD.getValue(1)); 7940 setValue(&VPIntrin, LD); 7941 } 7942 7943 void SelectionDAGBuilder::visitVPStore( 7944 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7945 SDLoc DL = getCurSDLoc(); 7946 Value *PtrOperand = VPIntrin.getArgOperand(1); 7947 EVT VT = OpValues[0].getValueType(); 7948 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7949 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7950 SDValue ST; 7951 if (!Alignment) 7952 Alignment = DAG.getEVTAlign(VT); 7953 SDValue Ptr = OpValues[1]; 7954 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7955 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7956 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7957 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7958 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7959 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7960 /* IsTruncating */ false, /*IsCompressing*/ false); 7961 DAG.setRoot(ST); 7962 setValue(&VPIntrin, ST); 7963 } 7964 7965 void SelectionDAGBuilder::visitVPScatter( 7966 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7967 SDLoc DL = getCurSDLoc(); 7968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7969 Value *PtrOperand = VPIntrin.getArgOperand(1); 7970 EVT VT = OpValues[0].getValueType(); 7971 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7972 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7973 SDValue ST; 7974 if (!Alignment) 7975 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7976 unsigned AS = 7977 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7978 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7979 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7980 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7981 SDValue Base, Index, Scale; 7982 ISD::MemIndexType IndexType; 7983 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7984 this, VPIntrin.getParent(), 7985 VT.getScalarStoreSize()); 7986 if (!UniformBase) { 7987 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7988 Index = getValue(PtrOperand); 7989 IndexType = ISD::SIGNED_SCALED; 7990 Scale = 7991 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7992 } 7993 EVT IdxVT = Index.getValueType(); 7994 EVT EltTy = IdxVT.getVectorElementType(); 7995 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7996 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7997 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7998 } 7999 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8000 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8001 OpValues[2], OpValues[3]}, 8002 MMO, IndexType); 8003 DAG.setRoot(ST); 8004 setValue(&VPIntrin, ST); 8005 } 8006 8007 void SelectionDAGBuilder::visitVPStridedLoad( 8008 const VPIntrinsic &VPIntrin, EVT VT, 8009 const SmallVectorImpl<SDValue> &OpValues) { 8010 SDLoc DL = getCurSDLoc(); 8011 Value *PtrOperand = VPIntrin.getArgOperand(0); 8012 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8013 if (!Alignment) 8014 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8015 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8016 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8017 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8018 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8019 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8020 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8021 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8022 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 8023 8024 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8025 OpValues[2], OpValues[3], MMO, 8026 false /*IsExpanding*/); 8027 8028 if (AddToChain) 8029 PendingLoads.push_back(LD.getValue(1)); 8030 setValue(&VPIntrin, LD); 8031 } 8032 8033 void SelectionDAGBuilder::visitVPStridedStore( 8034 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8035 SDLoc DL = getCurSDLoc(); 8036 Value *PtrOperand = VPIntrin.getArgOperand(1); 8037 EVT VT = OpValues[0].getValueType(); 8038 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8039 if (!Alignment) 8040 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8041 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8042 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8043 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8044 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8045 8046 SDValue ST = DAG.getStridedStoreVP( 8047 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8048 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8049 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8050 /*IsCompressing*/ false); 8051 8052 DAG.setRoot(ST); 8053 setValue(&VPIntrin, ST); 8054 } 8055 8056 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8057 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8058 SDLoc DL = getCurSDLoc(); 8059 8060 ISD::CondCode Condition; 8061 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8062 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8063 if (IsFP) { 8064 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8065 // flags, but calls that don't return floating-point types can't be 8066 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8067 Condition = getFCmpCondCode(CondCode); 8068 if (TM.Options.NoNaNsFPMath) 8069 Condition = getFCmpCodeWithoutNaN(Condition); 8070 } else { 8071 Condition = getICmpCondCode(CondCode); 8072 } 8073 8074 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8075 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8076 // #2 is the condition code 8077 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8078 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8079 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8080 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8081 "Unexpected target EVL type"); 8082 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8083 8084 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8085 VPIntrin.getType()); 8086 setValue(&VPIntrin, 8087 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8088 } 8089 8090 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8091 const VPIntrinsic &VPIntrin) { 8092 SDLoc DL = getCurSDLoc(); 8093 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8094 8095 auto IID = VPIntrin.getIntrinsicID(); 8096 8097 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8098 return visitVPCmp(*CmpI); 8099 8100 SmallVector<EVT, 4> ValueVTs; 8101 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8102 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8103 SDVTList VTs = DAG.getVTList(ValueVTs); 8104 8105 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8106 8107 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8108 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8109 "Unexpected target EVL type"); 8110 8111 // Request operands. 8112 SmallVector<SDValue, 7> OpValues; 8113 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8114 auto Op = getValue(VPIntrin.getArgOperand(I)); 8115 if (I == EVLParamPos) 8116 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8117 OpValues.push_back(Op); 8118 } 8119 8120 switch (Opcode) { 8121 default: { 8122 SDNodeFlags SDFlags; 8123 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8124 SDFlags.copyFMF(*FPMO); 8125 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8126 setValue(&VPIntrin, Result); 8127 break; 8128 } 8129 case ISD::VP_LOAD: 8130 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8131 break; 8132 case ISD::VP_GATHER: 8133 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8134 break; 8135 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8136 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8137 break; 8138 case ISD::VP_STORE: 8139 visitVPStore(VPIntrin, OpValues); 8140 break; 8141 case ISD::VP_SCATTER: 8142 visitVPScatter(VPIntrin, OpValues); 8143 break; 8144 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8145 visitVPStridedStore(VPIntrin, OpValues); 8146 break; 8147 case ISD::VP_FMULADD: { 8148 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8149 SDNodeFlags SDFlags; 8150 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8151 SDFlags.copyFMF(*FPMO); 8152 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8153 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8154 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8155 } else { 8156 SDValue Mul = DAG.getNode( 8157 ISD::VP_FMUL, DL, VTs, 8158 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8159 SDValue Add = 8160 DAG.getNode(ISD::VP_FADD, DL, VTs, 8161 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8162 setValue(&VPIntrin, Add); 8163 } 8164 break; 8165 } 8166 case ISD::VP_IS_FPCLASS: { 8167 const DataLayout DLayout = DAG.getDataLayout(); 8168 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8169 auto Constant = OpValues[1]->getAsZExtVal(); 8170 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8171 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8172 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8173 setValue(&VPIntrin, V); 8174 return; 8175 } 8176 case ISD::VP_INTTOPTR: { 8177 SDValue N = OpValues[0]; 8178 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8179 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8180 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8181 OpValues[2]); 8182 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8183 OpValues[2]); 8184 setValue(&VPIntrin, N); 8185 break; 8186 } 8187 case ISD::VP_PTRTOINT: { 8188 SDValue N = OpValues[0]; 8189 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8190 VPIntrin.getType()); 8191 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8192 VPIntrin.getOperand(0)->getType()); 8193 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8194 OpValues[2]); 8195 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8196 OpValues[2]); 8197 setValue(&VPIntrin, N); 8198 break; 8199 } 8200 case ISD::VP_ABS: 8201 case ISD::VP_CTLZ: 8202 case ISD::VP_CTLZ_ZERO_UNDEF: 8203 case ISD::VP_CTTZ: 8204 case ISD::VP_CTTZ_ZERO_UNDEF: { 8205 SDValue Result = 8206 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8207 setValue(&VPIntrin, Result); 8208 break; 8209 } 8210 } 8211 } 8212 8213 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8214 const BasicBlock *EHPadBB, 8215 MCSymbol *&BeginLabel) { 8216 MachineFunction &MF = DAG.getMachineFunction(); 8217 MachineModuleInfo &MMI = MF.getMMI(); 8218 8219 // Insert a label before the invoke call to mark the try range. This can be 8220 // used to detect deletion of the invoke via the MachineModuleInfo. 8221 BeginLabel = MMI.getContext().createTempSymbol(); 8222 8223 // For SjLj, keep track of which landing pads go with which invokes 8224 // so as to maintain the ordering of pads in the LSDA. 8225 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8226 if (CallSiteIndex) { 8227 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8228 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8229 8230 // Now that the call site is handled, stop tracking it. 8231 MMI.setCurrentCallSite(0); 8232 } 8233 8234 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8235 } 8236 8237 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8238 const BasicBlock *EHPadBB, 8239 MCSymbol *BeginLabel) { 8240 assert(BeginLabel && "BeginLabel should've been set"); 8241 8242 MachineFunction &MF = DAG.getMachineFunction(); 8243 MachineModuleInfo &MMI = MF.getMMI(); 8244 8245 // Insert a label at the end of the invoke call to mark the try range. This 8246 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8247 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8248 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8249 8250 // Inform MachineModuleInfo of range. 8251 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8252 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8253 // actually use outlined funclets and their LSDA info style. 8254 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8255 assert(II && "II should've been set"); 8256 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8257 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8258 } else if (!isScopedEHPersonality(Pers)) { 8259 assert(EHPadBB); 8260 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8261 } 8262 8263 return Chain; 8264 } 8265 8266 std::pair<SDValue, SDValue> 8267 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8268 const BasicBlock *EHPadBB) { 8269 MCSymbol *BeginLabel = nullptr; 8270 8271 if (EHPadBB) { 8272 // Both PendingLoads and PendingExports must be flushed here; 8273 // this call might not return. 8274 (void)getRoot(); 8275 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8276 CLI.setChain(getRoot()); 8277 } 8278 8279 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8280 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8281 8282 assert((CLI.IsTailCall || Result.second.getNode()) && 8283 "Non-null chain expected with non-tail call!"); 8284 assert((Result.second.getNode() || !Result.first.getNode()) && 8285 "Null value expected with tail call!"); 8286 8287 if (!Result.second.getNode()) { 8288 // As a special case, a null chain means that a tail call has been emitted 8289 // and the DAG root is already updated. 8290 HasTailCall = true; 8291 8292 // Since there's no actual continuation from this block, nothing can be 8293 // relying on us setting vregs for them. 8294 PendingExports.clear(); 8295 } else { 8296 DAG.setRoot(Result.second); 8297 } 8298 8299 if (EHPadBB) { 8300 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8301 BeginLabel)); 8302 } 8303 8304 return Result; 8305 } 8306 8307 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8308 bool isTailCall, 8309 bool isMustTailCall, 8310 const BasicBlock *EHPadBB) { 8311 auto &DL = DAG.getDataLayout(); 8312 FunctionType *FTy = CB.getFunctionType(); 8313 Type *RetTy = CB.getType(); 8314 8315 TargetLowering::ArgListTy Args; 8316 Args.reserve(CB.arg_size()); 8317 8318 const Value *SwiftErrorVal = nullptr; 8319 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8320 8321 if (isTailCall) { 8322 // Avoid emitting tail calls in functions with the disable-tail-calls 8323 // attribute. 8324 auto *Caller = CB.getParent()->getParent(); 8325 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8326 "true" && !isMustTailCall) 8327 isTailCall = false; 8328 8329 // We can't tail call inside a function with a swifterror argument. Lowering 8330 // does not support this yet. It would have to move into the swifterror 8331 // register before the call. 8332 if (TLI.supportSwiftError() && 8333 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8334 isTailCall = false; 8335 } 8336 8337 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8338 TargetLowering::ArgListEntry Entry; 8339 const Value *V = *I; 8340 8341 // Skip empty types 8342 if (V->getType()->isEmptyTy()) 8343 continue; 8344 8345 SDValue ArgNode = getValue(V); 8346 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8347 8348 Entry.setAttributes(&CB, I - CB.arg_begin()); 8349 8350 // Use swifterror virtual register as input to the call. 8351 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8352 SwiftErrorVal = V; 8353 // We find the virtual register for the actual swifterror argument. 8354 // Instead of using the Value, we use the virtual register instead. 8355 Entry.Node = 8356 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8357 EVT(TLI.getPointerTy(DL))); 8358 } 8359 8360 Args.push_back(Entry); 8361 8362 // If we have an explicit sret argument that is an Instruction, (i.e., it 8363 // might point to function-local memory), we can't meaningfully tail-call. 8364 if (Entry.IsSRet && isa<Instruction>(V)) 8365 isTailCall = false; 8366 } 8367 8368 // If call site has a cfguardtarget operand bundle, create and add an 8369 // additional ArgListEntry. 8370 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8371 TargetLowering::ArgListEntry Entry; 8372 Value *V = Bundle->Inputs[0]; 8373 SDValue ArgNode = getValue(V); 8374 Entry.Node = ArgNode; 8375 Entry.Ty = V->getType(); 8376 Entry.IsCFGuardTarget = true; 8377 Args.push_back(Entry); 8378 } 8379 8380 // Check if target-independent constraints permit a tail call here. 8381 // Target-dependent constraints are checked within TLI->LowerCallTo. 8382 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8383 isTailCall = false; 8384 8385 // Disable tail calls if there is an swifterror argument. Targets have not 8386 // been updated to support tail calls. 8387 if (TLI.supportSwiftError() && SwiftErrorVal) 8388 isTailCall = false; 8389 8390 ConstantInt *CFIType = nullptr; 8391 if (CB.isIndirectCall()) { 8392 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8393 if (!TLI.supportKCFIBundles()) 8394 report_fatal_error( 8395 "Target doesn't support calls with kcfi operand bundles."); 8396 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8397 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8398 } 8399 } 8400 8401 TargetLowering::CallLoweringInfo CLI(DAG); 8402 CLI.setDebugLoc(getCurSDLoc()) 8403 .setChain(getRoot()) 8404 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8405 .setTailCall(isTailCall) 8406 .setConvergent(CB.isConvergent()) 8407 .setIsPreallocated( 8408 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8409 .setCFIType(CFIType); 8410 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8411 8412 if (Result.first.getNode()) { 8413 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8414 setValue(&CB, Result.first); 8415 } 8416 8417 // The last element of CLI.InVals has the SDValue for swifterror return. 8418 // Here we copy it to a virtual register and update SwiftErrorMap for 8419 // book-keeping. 8420 if (SwiftErrorVal && TLI.supportSwiftError()) { 8421 // Get the last element of InVals. 8422 SDValue Src = CLI.InVals.back(); 8423 Register VReg = 8424 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8425 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8426 DAG.setRoot(CopyNode); 8427 } 8428 } 8429 8430 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8431 SelectionDAGBuilder &Builder) { 8432 // Check to see if this load can be trivially constant folded, e.g. if the 8433 // input is from a string literal. 8434 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8435 // Cast pointer to the type we really want to load. 8436 Type *LoadTy = 8437 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8438 if (LoadVT.isVector()) 8439 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8440 8441 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8442 PointerType::getUnqual(LoadTy)); 8443 8444 if (const Constant *LoadCst = 8445 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8446 LoadTy, Builder.DAG.getDataLayout())) 8447 return Builder.getValue(LoadCst); 8448 } 8449 8450 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8451 // still constant memory, the input chain can be the entry node. 8452 SDValue Root; 8453 bool ConstantMemory = false; 8454 8455 // Do not serialize (non-volatile) loads of constant memory with anything. 8456 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8457 Root = Builder.DAG.getEntryNode(); 8458 ConstantMemory = true; 8459 } else { 8460 // Do not serialize non-volatile loads against each other. 8461 Root = Builder.DAG.getRoot(); 8462 } 8463 8464 SDValue Ptr = Builder.getValue(PtrVal); 8465 SDValue LoadVal = 8466 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8467 MachinePointerInfo(PtrVal), Align(1)); 8468 8469 if (!ConstantMemory) 8470 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8471 return LoadVal; 8472 } 8473 8474 /// Record the value for an instruction that produces an integer result, 8475 /// converting the type where necessary. 8476 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8477 SDValue Value, 8478 bool IsSigned) { 8479 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8480 I.getType(), true); 8481 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8482 setValue(&I, Value); 8483 } 8484 8485 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8486 /// true and lower it. Otherwise return false, and it will be lowered like a 8487 /// normal call. 8488 /// The caller already checked that \p I calls the appropriate LibFunc with a 8489 /// correct prototype. 8490 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8491 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8492 const Value *Size = I.getArgOperand(2); 8493 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8494 if (CSize && CSize->getZExtValue() == 0) { 8495 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8496 I.getType(), true); 8497 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8498 return true; 8499 } 8500 8501 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8502 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8503 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8504 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8505 if (Res.first.getNode()) { 8506 processIntegerCallValue(I, Res.first, true); 8507 PendingLoads.push_back(Res.second); 8508 return true; 8509 } 8510 8511 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8512 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8513 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8514 return false; 8515 8516 // If the target has a fast compare for the given size, it will return a 8517 // preferred load type for that size. Require that the load VT is legal and 8518 // that the target supports unaligned loads of that type. Otherwise, return 8519 // INVALID. 8520 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8521 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8522 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8523 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8524 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8525 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8526 // TODO: Check alignment of src and dest ptrs. 8527 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8528 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8529 if (!TLI.isTypeLegal(LVT) || 8530 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8531 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8532 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8533 } 8534 8535 return LVT; 8536 }; 8537 8538 // This turns into unaligned loads. We only do this if the target natively 8539 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8540 // we'll only produce a small number of byte loads. 8541 MVT LoadVT; 8542 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8543 switch (NumBitsToCompare) { 8544 default: 8545 return false; 8546 case 16: 8547 LoadVT = MVT::i16; 8548 break; 8549 case 32: 8550 LoadVT = MVT::i32; 8551 break; 8552 case 64: 8553 case 128: 8554 case 256: 8555 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8556 break; 8557 } 8558 8559 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8560 return false; 8561 8562 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8563 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8564 8565 // Bitcast to a wide integer type if the loads are vectors. 8566 if (LoadVT.isVector()) { 8567 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8568 LoadL = DAG.getBitcast(CmpVT, LoadL); 8569 LoadR = DAG.getBitcast(CmpVT, LoadR); 8570 } 8571 8572 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8573 processIntegerCallValue(I, Cmp, false); 8574 return true; 8575 } 8576 8577 /// See if we can lower a memchr call into an optimized form. If so, return 8578 /// true and lower it. Otherwise return false, and it will be lowered like a 8579 /// normal call. 8580 /// The caller already checked that \p I calls the appropriate LibFunc with a 8581 /// correct prototype. 8582 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8583 const Value *Src = I.getArgOperand(0); 8584 const Value *Char = I.getArgOperand(1); 8585 const Value *Length = I.getArgOperand(2); 8586 8587 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8588 std::pair<SDValue, SDValue> Res = 8589 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8590 getValue(Src), getValue(Char), getValue(Length), 8591 MachinePointerInfo(Src)); 8592 if (Res.first.getNode()) { 8593 setValue(&I, Res.first); 8594 PendingLoads.push_back(Res.second); 8595 return true; 8596 } 8597 8598 return false; 8599 } 8600 8601 /// See if we can lower a mempcpy call into an optimized form. If so, return 8602 /// true and lower it. Otherwise return false, and it will be lowered like a 8603 /// normal call. 8604 /// The caller already checked that \p I calls the appropriate LibFunc with a 8605 /// correct prototype. 8606 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8607 SDValue Dst = getValue(I.getArgOperand(0)); 8608 SDValue Src = getValue(I.getArgOperand(1)); 8609 SDValue Size = getValue(I.getArgOperand(2)); 8610 8611 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8612 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8613 // DAG::getMemcpy needs Alignment to be defined. 8614 Align Alignment = std::min(DstAlign, SrcAlign); 8615 8616 SDLoc sdl = getCurSDLoc(); 8617 8618 // In the mempcpy context we need to pass in a false value for isTailCall 8619 // because the return pointer needs to be adjusted by the size of 8620 // the copied memory. 8621 SDValue Root = getMemoryRoot(); 8622 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8623 /*isTailCall=*/false, 8624 MachinePointerInfo(I.getArgOperand(0)), 8625 MachinePointerInfo(I.getArgOperand(1)), 8626 I.getAAMetadata()); 8627 assert(MC.getNode() != nullptr && 8628 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8629 DAG.setRoot(MC); 8630 8631 // Check if Size needs to be truncated or extended. 8632 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8633 8634 // Adjust return pointer to point just past the last dst byte. 8635 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8636 Dst, Size); 8637 setValue(&I, DstPlusSize); 8638 return true; 8639 } 8640 8641 /// See if we can lower a strcpy call into an optimized form. If so, return 8642 /// true and lower it, otherwise return false and it will be lowered like a 8643 /// normal call. 8644 /// The caller already checked that \p I calls the appropriate LibFunc with a 8645 /// correct prototype. 8646 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8647 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8648 8649 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8650 std::pair<SDValue, SDValue> Res = 8651 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8652 getValue(Arg0), getValue(Arg1), 8653 MachinePointerInfo(Arg0), 8654 MachinePointerInfo(Arg1), isStpcpy); 8655 if (Res.first.getNode()) { 8656 setValue(&I, Res.first); 8657 DAG.setRoot(Res.second); 8658 return true; 8659 } 8660 8661 return false; 8662 } 8663 8664 /// See if we can lower a strcmp call into an optimized form. If so, return 8665 /// true and lower it, otherwise return false and it will be lowered like a 8666 /// normal call. 8667 /// The caller already checked that \p I calls the appropriate LibFunc with a 8668 /// correct prototype. 8669 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8670 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8671 8672 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8673 std::pair<SDValue, SDValue> Res = 8674 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8675 getValue(Arg0), getValue(Arg1), 8676 MachinePointerInfo(Arg0), 8677 MachinePointerInfo(Arg1)); 8678 if (Res.first.getNode()) { 8679 processIntegerCallValue(I, Res.first, true); 8680 PendingLoads.push_back(Res.second); 8681 return true; 8682 } 8683 8684 return false; 8685 } 8686 8687 /// See if we can lower a strlen call into an optimized form. If so, return 8688 /// true and lower it, otherwise return false and it will be lowered like a 8689 /// normal call. 8690 /// The caller already checked that \p I calls the appropriate LibFunc with a 8691 /// correct prototype. 8692 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8693 const Value *Arg0 = I.getArgOperand(0); 8694 8695 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8696 std::pair<SDValue, SDValue> Res = 8697 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8698 getValue(Arg0), MachinePointerInfo(Arg0)); 8699 if (Res.first.getNode()) { 8700 processIntegerCallValue(I, Res.first, false); 8701 PendingLoads.push_back(Res.second); 8702 return true; 8703 } 8704 8705 return false; 8706 } 8707 8708 /// See if we can lower a strnlen call into an optimized form. If so, return 8709 /// true and lower it, otherwise return false and it will be lowered like a 8710 /// normal call. 8711 /// The caller already checked that \p I calls the appropriate LibFunc with a 8712 /// correct prototype. 8713 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8714 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8715 8716 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8717 std::pair<SDValue, SDValue> Res = 8718 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8719 getValue(Arg0), getValue(Arg1), 8720 MachinePointerInfo(Arg0)); 8721 if (Res.first.getNode()) { 8722 processIntegerCallValue(I, Res.first, false); 8723 PendingLoads.push_back(Res.second); 8724 return true; 8725 } 8726 8727 return false; 8728 } 8729 8730 /// See if we can lower a unary floating-point operation into an SDNode with 8731 /// the specified Opcode. If so, return true and lower it, otherwise return 8732 /// false and it will be lowered like a normal call. 8733 /// The caller already checked that \p I calls the appropriate LibFunc with a 8734 /// correct prototype. 8735 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8736 unsigned Opcode) { 8737 // We already checked this call's prototype; verify it doesn't modify errno. 8738 if (!I.onlyReadsMemory()) 8739 return false; 8740 8741 SDNodeFlags Flags; 8742 Flags.copyFMF(cast<FPMathOperator>(I)); 8743 8744 SDValue Tmp = getValue(I.getArgOperand(0)); 8745 setValue(&I, 8746 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8747 return true; 8748 } 8749 8750 /// See if we can lower a binary floating-point operation into an SDNode with 8751 /// the specified Opcode. If so, return true and lower it. Otherwise return 8752 /// false, and it will be lowered like a normal call. 8753 /// The caller already checked that \p I calls the appropriate LibFunc with a 8754 /// correct prototype. 8755 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8756 unsigned Opcode) { 8757 // We already checked this call's prototype; verify it doesn't modify errno. 8758 if (!I.onlyReadsMemory()) 8759 return false; 8760 8761 SDNodeFlags Flags; 8762 Flags.copyFMF(cast<FPMathOperator>(I)); 8763 8764 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8765 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8766 EVT VT = Tmp0.getValueType(); 8767 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8768 return true; 8769 } 8770 8771 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8772 // Handle inline assembly differently. 8773 if (I.isInlineAsm()) { 8774 visitInlineAsm(I); 8775 return; 8776 } 8777 8778 diagnoseDontCall(I); 8779 8780 if (Function *F = I.getCalledFunction()) { 8781 if (F->isDeclaration()) { 8782 // Is this an LLVM intrinsic or a target-specific intrinsic? 8783 unsigned IID = F->getIntrinsicID(); 8784 if (!IID) 8785 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8786 IID = II->getIntrinsicID(F); 8787 8788 if (IID) { 8789 visitIntrinsicCall(I, IID); 8790 return; 8791 } 8792 } 8793 8794 // Check for well-known libc/libm calls. If the function is internal, it 8795 // can't be a library call. Don't do the check if marked as nobuiltin for 8796 // some reason or the call site requires strict floating point semantics. 8797 LibFunc Func; 8798 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8799 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8800 LibInfo->hasOptimizedCodeGen(Func)) { 8801 switch (Func) { 8802 default: break; 8803 case LibFunc_bcmp: 8804 if (visitMemCmpBCmpCall(I)) 8805 return; 8806 break; 8807 case LibFunc_copysign: 8808 case LibFunc_copysignf: 8809 case LibFunc_copysignl: 8810 // We already checked this call's prototype; verify it doesn't modify 8811 // errno. 8812 if (I.onlyReadsMemory()) { 8813 SDValue LHS = getValue(I.getArgOperand(0)); 8814 SDValue RHS = getValue(I.getArgOperand(1)); 8815 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8816 LHS.getValueType(), LHS, RHS)); 8817 return; 8818 } 8819 break; 8820 case LibFunc_fabs: 8821 case LibFunc_fabsf: 8822 case LibFunc_fabsl: 8823 if (visitUnaryFloatCall(I, ISD::FABS)) 8824 return; 8825 break; 8826 case LibFunc_fmin: 8827 case LibFunc_fminf: 8828 case LibFunc_fminl: 8829 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8830 return; 8831 break; 8832 case LibFunc_fmax: 8833 case LibFunc_fmaxf: 8834 case LibFunc_fmaxl: 8835 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8836 return; 8837 break; 8838 case LibFunc_sin: 8839 case LibFunc_sinf: 8840 case LibFunc_sinl: 8841 if (visitUnaryFloatCall(I, ISD::FSIN)) 8842 return; 8843 break; 8844 case LibFunc_cos: 8845 case LibFunc_cosf: 8846 case LibFunc_cosl: 8847 if (visitUnaryFloatCall(I, ISD::FCOS)) 8848 return; 8849 break; 8850 case LibFunc_sqrt: 8851 case LibFunc_sqrtf: 8852 case LibFunc_sqrtl: 8853 case LibFunc_sqrt_finite: 8854 case LibFunc_sqrtf_finite: 8855 case LibFunc_sqrtl_finite: 8856 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8857 return; 8858 break; 8859 case LibFunc_floor: 8860 case LibFunc_floorf: 8861 case LibFunc_floorl: 8862 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8863 return; 8864 break; 8865 case LibFunc_nearbyint: 8866 case LibFunc_nearbyintf: 8867 case LibFunc_nearbyintl: 8868 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8869 return; 8870 break; 8871 case LibFunc_ceil: 8872 case LibFunc_ceilf: 8873 case LibFunc_ceill: 8874 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8875 return; 8876 break; 8877 case LibFunc_rint: 8878 case LibFunc_rintf: 8879 case LibFunc_rintl: 8880 if (visitUnaryFloatCall(I, ISD::FRINT)) 8881 return; 8882 break; 8883 case LibFunc_round: 8884 case LibFunc_roundf: 8885 case LibFunc_roundl: 8886 if (visitUnaryFloatCall(I, ISD::FROUND)) 8887 return; 8888 break; 8889 case LibFunc_trunc: 8890 case LibFunc_truncf: 8891 case LibFunc_truncl: 8892 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8893 return; 8894 break; 8895 case LibFunc_log2: 8896 case LibFunc_log2f: 8897 case LibFunc_log2l: 8898 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8899 return; 8900 break; 8901 case LibFunc_exp2: 8902 case LibFunc_exp2f: 8903 case LibFunc_exp2l: 8904 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8905 return; 8906 break; 8907 case LibFunc_exp10: 8908 case LibFunc_exp10f: 8909 case LibFunc_exp10l: 8910 if (visitUnaryFloatCall(I, ISD::FEXP10)) 8911 return; 8912 break; 8913 case LibFunc_ldexp: 8914 case LibFunc_ldexpf: 8915 case LibFunc_ldexpl: 8916 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8917 return; 8918 break; 8919 case LibFunc_memcmp: 8920 if (visitMemCmpBCmpCall(I)) 8921 return; 8922 break; 8923 case LibFunc_mempcpy: 8924 if (visitMemPCpyCall(I)) 8925 return; 8926 break; 8927 case LibFunc_memchr: 8928 if (visitMemChrCall(I)) 8929 return; 8930 break; 8931 case LibFunc_strcpy: 8932 if (visitStrCpyCall(I, false)) 8933 return; 8934 break; 8935 case LibFunc_stpcpy: 8936 if (visitStrCpyCall(I, true)) 8937 return; 8938 break; 8939 case LibFunc_strcmp: 8940 if (visitStrCmpCall(I)) 8941 return; 8942 break; 8943 case LibFunc_strlen: 8944 if (visitStrLenCall(I)) 8945 return; 8946 break; 8947 case LibFunc_strnlen: 8948 if (visitStrNLenCall(I)) 8949 return; 8950 break; 8951 } 8952 } 8953 } 8954 8955 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8956 // have to do anything here to lower funclet bundles. 8957 // CFGuardTarget bundles are lowered in LowerCallTo. 8958 assert(!I.hasOperandBundlesOtherThan( 8959 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8960 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8961 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8962 "Cannot lower calls with arbitrary operand bundles!"); 8963 8964 SDValue Callee = getValue(I.getCalledOperand()); 8965 8966 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8967 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8968 else 8969 // Check if we can potentially perform a tail call. More detailed checking 8970 // is be done within LowerCallTo, after more information about the call is 8971 // known. 8972 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8973 } 8974 8975 namespace { 8976 8977 /// AsmOperandInfo - This contains information for each constraint that we are 8978 /// lowering. 8979 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8980 public: 8981 /// CallOperand - If this is the result output operand or a clobber 8982 /// this is null, otherwise it is the incoming operand to the CallInst. 8983 /// This gets modified as the asm is processed. 8984 SDValue CallOperand; 8985 8986 /// AssignedRegs - If this is a register or register class operand, this 8987 /// contains the set of register corresponding to the operand. 8988 RegsForValue AssignedRegs; 8989 8990 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8991 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8992 } 8993 8994 /// Whether or not this operand accesses memory 8995 bool hasMemory(const TargetLowering &TLI) const { 8996 // Indirect operand accesses access memory. 8997 if (isIndirect) 8998 return true; 8999 9000 for (const auto &Code : Codes) 9001 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9002 return true; 9003 9004 return false; 9005 } 9006 }; 9007 9008 9009 } // end anonymous namespace 9010 9011 /// Make sure that the output operand \p OpInfo and its corresponding input 9012 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9013 /// out). 9014 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9015 SDISelAsmOperandInfo &MatchingOpInfo, 9016 SelectionDAG &DAG) { 9017 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9018 return; 9019 9020 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9021 const auto &TLI = DAG.getTargetLoweringInfo(); 9022 9023 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9024 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9025 OpInfo.ConstraintVT); 9026 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9027 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9028 MatchingOpInfo.ConstraintVT); 9029 if ((OpInfo.ConstraintVT.isInteger() != 9030 MatchingOpInfo.ConstraintVT.isInteger()) || 9031 (MatchRC.second != InputRC.second)) { 9032 // FIXME: error out in a more elegant fashion 9033 report_fatal_error("Unsupported asm: input constraint" 9034 " with a matching output constraint of" 9035 " incompatible type!"); 9036 } 9037 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9038 } 9039 9040 /// Get a direct memory input to behave well as an indirect operand. 9041 /// This may introduce stores, hence the need for a \p Chain. 9042 /// \return The (possibly updated) chain. 9043 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9044 SDISelAsmOperandInfo &OpInfo, 9045 SelectionDAG &DAG) { 9046 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9047 9048 // If we don't have an indirect input, put it in the constpool if we can, 9049 // otherwise spill it to a stack slot. 9050 // TODO: This isn't quite right. We need to handle these according to 9051 // the addressing mode that the constraint wants. Also, this may take 9052 // an additional register for the computation and we don't want that 9053 // either. 9054 9055 // If the operand is a float, integer, or vector constant, spill to a 9056 // constant pool entry to get its address. 9057 const Value *OpVal = OpInfo.CallOperandVal; 9058 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9059 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9060 OpInfo.CallOperand = DAG.getConstantPool( 9061 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9062 return Chain; 9063 } 9064 9065 // Otherwise, create a stack slot and emit a store to it before the asm. 9066 Type *Ty = OpVal->getType(); 9067 auto &DL = DAG.getDataLayout(); 9068 uint64_t TySize = DL.getTypeAllocSize(Ty); 9069 MachineFunction &MF = DAG.getMachineFunction(); 9070 int SSFI = MF.getFrameInfo().CreateStackObject( 9071 TySize, DL.getPrefTypeAlign(Ty), false); 9072 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9073 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9074 MachinePointerInfo::getFixedStack(MF, SSFI), 9075 TLI.getMemValueType(DL, Ty)); 9076 OpInfo.CallOperand = StackSlot; 9077 9078 return Chain; 9079 } 9080 9081 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9082 /// specified operand. We prefer to assign virtual registers, to allow the 9083 /// register allocator to handle the assignment process. However, if the asm 9084 /// uses features that we can't model on machineinstrs, we have SDISel do the 9085 /// allocation. This produces generally horrible, but correct, code. 9086 /// 9087 /// OpInfo describes the operand 9088 /// RefOpInfo describes the matching operand if any, the operand otherwise 9089 static std::optional<unsigned> 9090 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9091 SDISelAsmOperandInfo &OpInfo, 9092 SDISelAsmOperandInfo &RefOpInfo) { 9093 LLVMContext &Context = *DAG.getContext(); 9094 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9095 9096 MachineFunction &MF = DAG.getMachineFunction(); 9097 SmallVector<unsigned, 4> Regs; 9098 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9099 9100 // No work to do for memory/address operands. 9101 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9102 OpInfo.ConstraintType == TargetLowering::C_Address) 9103 return std::nullopt; 9104 9105 // If this is a constraint for a single physreg, or a constraint for a 9106 // register class, find it. 9107 unsigned AssignedReg; 9108 const TargetRegisterClass *RC; 9109 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9110 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9111 // RC is unset only on failure. Return immediately. 9112 if (!RC) 9113 return std::nullopt; 9114 9115 // Get the actual register value type. This is important, because the user 9116 // may have asked for (e.g.) the AX register in i32 type. We need to 9117 // remember that AX is actually i16 to get the right extension. 9118 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9119 9120 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9121 // If this is an FP operand in an integer register (or visa versa), or more 9122 // generally if the operand value disagrees with the register class we plan 9123 // to stick it in, fix the operand type. 9124 // 9125 // If this is an input value, the bitcast to the new type is done now. 9126 // Bitcast for output value is done at the end of visitInlineAsm(). 9127 if ((OpInfo.Type == InlineAsm::isOutput || 9128 OpInfo.Type == InlineAsm::isInput) && 9129 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9130 // Try to convert to the first EVT that the reg class contains. If the 9131 // types are identical size, use a bitcast to convert (e.g. two differing 9132 // vector types). Note: output bitcast is done at the end of 9133 // visitInlineAsm(). 9134 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9135 // Exclude indirect inputs while they are unsupported because the code 9136 // to perform the load is missing and thus OpInfo.CallOperand still 9137 // refers to the input address rather than the pointed-to value. 9138 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9139 OpInfo.CallOperand = 9140 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9141 OpInfo.ConstraintVT = RegVT; 9142 // If the operand is an FP value and we want it in integer registers, 9143 // use the corresponding integer type. This turns an f64 value into 9144 // i64, which can be passed with two i32 values on a 32-bit machine. 9145 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9146 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9147 if (OpInfo.Type == InlineAsm::isInput) 9148 OpInfo.CallOperand = 9149 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9150 OpInfo.ConstraintVT = VT; 9151 } 9152 } 9153 } 9154 9155 // No need to allocate a matching input constraint since the constraint it's 9156 // matching to has already been allocated. 9157 if (OpInfo.isMatchingInputConstraint()) 9158 return std::nullopt; 9159 9160 EVT ValueVT = OpInfo.ConstraintVT; 9161 if (OpInfo.ConstraintVT == MVT::Other) 9162 ValueVT = RegVT; 9163 9164 // Initialize NumRegs. 9165 unsigned NumRegs = 1; 9166 if (OpInfo.ConstraintVT != MVT::Other) 9167 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9168 9169 // If this is a constraint for a specific physical register, like {r17}, 9170 // assign it now. 9171 9172 // If this associated to a specific register, initialize iterator to correct 9173 // place. If virtual, make sure we have enough registers 9174 9175 // Initialize iterator if necessary 9176 TargetRegisterClass::iterator I = RC->begin(); 9177 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9178 9179 // Do not check for single registers. 9180 if (AssignedReg) { 9181 I = std::find(I, RC->end(), AssignedReg); 9182 if (I == RC->end()) { 9183 // RC does not contain the selected register, which indicates a 9184 // mismatch between the register and the required type/bitwidth. 9185 return {AssignedReg}; 9186 } 9187 } 9188 9189 for (; NumRegs; --NumRegs, ++I) { 9190 assert(I != RC->end() && "Ran out of registers to allocate!"); 9191 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9192 Regs.push_back(R); 9193 } 9194 9195 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9196 return std::nullopt; 9197 } 9198 9199 static unsigned 9200 findMatchingInlineAsmOperand(unsigned OperandNo, 9201 const std::vector<SDValue> &AsmNodeOperands) { 9202 // Scan until we find the definition we already emitted of this operand. 9203 unsigned CurOp = InlineAsm::Op_FirstOperand; 9204 for (; OperandNo; --OperandNo) { 9205 // Advance to the next operand. 9206 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9207 const InlineAsm::Flag F(OpFlag); 9208 assert( 9209 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9210 "Skipped past definitions?"); 9211 CurOp += F.getNumOperandRegisters() + 1; 9212 } 9213 return CurOp; 9214 } 9215 9216 namespace { 9217 9218 class ExtraFlags { 9219 unsigned Flags = 0; 9220 9221 public: 9222 explicit ExtraFlags(const CallBase &Call) { 9223 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9224 if (IA->hasSideEffects()) 9225 Flags |= InlineAsm::Extra_HasSideEffects; 9226 if (IA->isAlignStack()) 9227 Flags |= InlineAsm::Extra_IsAlignStack; 9228 if (Call.isConvergent()) 9229 Flags |= InlineAsm::Extra_IsConvergent; 9230 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9231 } 9232 9233 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9234 // Ideally, we would only check against memory constraints. However, the 9235 // meaning of an Other constraint can be target-specific and we can't easily 9236 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9237 // for Other constraints as well. 9238 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9239 OpInfo.ConstraintType == TargetLowering::C_Other) { 9240 if (OpInfo.Type == InlineAsm::isInput) 9241 Flags |= InlineAsm::Extra_MayLoad; 9242 else if (OpInfo.Type == InlineAsm::isOutput) 9243 Flags |= InlineAsm::Extra_MayStore; 9244 else if (OpInfo.Type == InlineAsm::isClobber) 9245 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9246 } 9247 } 9248 9249 unsigned get() const { return Flags; } 9250 }; 9251 9252 } // end anonymous namespace 9253 9254 static bool isFunction(SDValue Op) { 9255 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9256 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9257 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9258 9259 // In normal "call dllimport func" instruction (non-inlineasm) it force 9260 // indirect access by specifing call opcode. And usually specially print 9261 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9262 // not do in this way now. (In fact, this is similar with "Data Access" 9263 // action). So here we ignore dllimport function. 9264 if (Fn && !Fn->hasDLLImportStorageClass()) 9265 return true; 9266 } 9267 } 9268 return false; 9269 } 9270 9271 /// visitInlineAsm - Handle a call to an InlineAsm object. 9272 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9273 const BasicBlock *EHPadBB) { 9274 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9275 9276 /// ConstraintOperands - Information about all of the constraints. 9277 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9278 9279 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9280 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9281 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9282 9283 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9284 // AsmDialect, MayLoad, MayStore). 9285 bool HasSideEffect = IA->hasSideEffects(); 9286 ExtraFlags ExtraInfo(Call); 9287 9288 for (auto &T : TargetConstraints) { 9289 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9290 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9291 9292 if (OpInfo.CallOperandVal) 9293 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9294 9295 if (!HasSideEffect) 9296 HasSideEffect = OpInfo.hasMemory(TLI); 9297 9298 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9299 // FIXME: Could we compute this on OpInfo rather than T? 9300 9301 // Compute the constraint code and ConstraintType to use. 9302 TLI.ComputeConstraintToUse(T, SDValue()); 9303 9304 if (T.ConstraintType == TargetLowering::C_Immediate && 9305 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9306 // We've delayed emitting a diagnostic like the "n" constraint because 9307 // inlining could cause an integer showing up. 9308 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9309 "' expects an integer constant " 9310 "expression"); 9311 9312 ExtraInfo.update(T); 9313 } 9314 9315 // We won't need to flush pending loads if this asm doesn't touch 9316 // memory and is nonvolatile. 9317 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9318 9319 bool EmitEHLabels = isa<InvokeInst>(Call); 9320 if (EmitEHLabels) { 9321 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9322 } 9323 bool IsCallBr = isa<CallBrInst>(Call); 9324 9325 if (IsCallBr || EmitEHLabels) { 9326 // If this is a callbr or invoke we need to flush pending exports since 9327 // inlineasm_br and invoke are terminators. 9328 // We need to do this before nodes are glued to the inlineasm_br node. 9329 Chain = getControlRoot(); 9330 } 9331 9332 MCSymbol *BeginLabel = nullptr; 9333 if (EmitEHLabels) { 9334 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9335 } 9336 9337 int OpNo = -1; 9338 SmallVector<StringRef> AsmStrs; 9339 IA->collectAsmStrs(AsmStrs); 9340 9341 // Second pass over the constraints: compute which constraint option to use. 9342 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9343 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9344 OpNo++; 9345 9346 // If this is an output operand with a matching input operand, look up the 9347 // matching input. If their types mismatch, e.g. one is an integer, the 9348 // other is floating point, or their sizes are different, flag it as an 9349 // error. 9350 if (OpInfo.hasMatchingInput()) { 9351 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9352 patchMatchingInput(OpInfo, Input, DAG); 9353 } 9354 9355 // Compute the constraint code and ConstraintType to use. 9356 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9357 9358 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9359 OpInfo.Type == InlineAsm::isClobber) || 9360 OpInfo.ConstraintType == TargetLowering::C_Address) 9361 continue; 9362 9363 // In Linux PIC model, there are 4 cases about value/label addressing: 9364 // 9365 // 1: Function call or Label jmp inside the module. 9366 // 2: Data access (such as global variable, static variable) inside module. 9367 // 3: Function call or Label jmp outside the module. 9368 // 4: Data access (such as global variable) outside the module. 9369 // 9370 // Due to current llvm inline asm architecture designed to not "recognize" 9371 // the asm code, there are quite troubles for us to treat mem addressing 9372 // differently for same value/adress used in different instuctions. 9373 // For example, in pic model, call a func may in plt way or direclty 9374 // pc-related, but lea/mov a function adress may use got. 9375 // 9376 // Here we try to "recognize" function call for the case 1 and case 3 in 9377 // inline asm. And try to adjust the constraint for them. 9378 // 9379 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9380 // label, so here we don't handle jmp function label now, but we need to 9381 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9382 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9383 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9384 TM.getCodeModel() != CodeModel::Large) { 9385 OpInfo.isIndirect = false; 9386 OpInfo.ConstraintType = TargetLowering::C_Address; 9387 } 9388 9389 // If this is a memory input, and if the operand is not indirect, do what we 9390 // need to provide an address for the memory input. 9391 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9392 !OpInfo.isIndirect) { 9393 assert((OpInfo.isMultipleAlternative || 9394 (OpInfo.Type == InlineAsm::isInput)) && 9395 "Can only indirectify direct input operands!"); 9396 9397 // Memory operands really want the address of the value. 9398 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9399 9400 // There is no longer a Value* corresponding to this operand. 9401 OpInfo.CallOperandVal = nullptr; 9402 9403 // It is now an indirect operand. 9404 OpInfo.isIndirect = true; 9405 } 9406 9407 } 9408 9409 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9410 std::vector<SDValue> AsmNodeOperands; 9411 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9412 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9413 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9414 9415 // If we have a !srcloc metadata node associated with it, we want to attach 9416 // this to the ultimately generated inline asm machineinstr. To do this, we 9417 // pass in the third operand as this (potentially null) inline asm MDNode. 9418 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9419 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9420 9421 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9422 // bits as operand 3. 9423 AsmNodeOperands.push_back(DAG.getTargetConstant( 9424 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9425 9426 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9427 // this, assign virtual and physical registers for inputs and otput. 9428 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9429 // Assign Registers. 9430 SDISelAsmOperandInfo &RefOpInfo = 9431 OpInfo.isMatchingInputConstraint() 9432 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9433 : OpInfo; 9434 const auto RegError = 9435 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9436 if (RegError) { 9437 const MachineFunction &MF = DAG.getMachineFunction(); 9438 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9439 const char *RegName = TRI.getName(*RegError); 9440 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9441 "' allocated for constraint '" + 9442 Twine(OpInfo.ConstraintCode) + 9443 "' does not match required type"); 9444 return; 9445 } 9446 9447 auto DetectWriteToReservedRegister = [&]() { 9448 const MachineFunction &MF = DAG.getMachineFunction(); 9449 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9450 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9451 if (Register::isPhysicalRegister(Reg) && 9452 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9453 const char *RegName = TRI.getName(Reg); 9454 emitInlineAsmError(Call, "write to reserved register '" + 9455 Twine(RegName) + "'"); 9456 return true; 9457 } 9458 } 9459 return false; 9460 }; 9461 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9462 (OpInfo.Type == InlineAsm::isInput && 9463 !OpInfo.isMatchingInputConstraint())) && 9464 "Only address as input operand is allowed."); 9465 9466 switch (OpInfo.Type) { 9467 case InlineAsm::isOutput: 9468 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9469 const InlineAsm::ConstraintCode ConstraintID = 9470 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9471 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9472 "Failed to convert memory constraint code to constraint id."); 9473 9474 // Add information to the INLINEASM node to know about this output. 9475 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9476 OpFlags.setMemConstraint(ConstraintID); 9477 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9478 MVT::i32)); 9479 AsmNodeOperands.push_back(OpInfo.CallOperand); 9480 } else { 9481 // Otherwise, this outputs to a register (directly for C_Register / 9482 // C_RegisterClass, and a target-defined fashion for 9483 // C_Immediate/C_Other). Find a register that we can use. 9484 if (OpInfo.AssignedRegs.Regs.empty()) { 9485 emitInlineAsmError( 9486 Call, "couldn't allocate output register for constraint '" + 9487 Twine(OpInfo.ConstraintCode) + "'"); 9488 return; 9489 } 9490 9491 if (DetectWriteToReservedRegister()) 9492 return; 9493 9494 // Add information to the INLINEASM node to know that this register is 9495 // set. 9496 OpInfo.AssignedRegs.AddInlineAsmOperands( 9497 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9498 : InlineAsm::Kind::RegDef, 9499 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9500 } 9501 break; 9502 9503 case InlineAsm::isInput: 9504 case InlineAsm::isLabel: { 9505 SDValue InOperandVal = OpInfo.CallOperand; 9506 9507 if (OpInfo.isMatchingInputConstraint()) { 9508 // If this is required to match an output register we have already set, 9509 // just use its register. 9510 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9511 AsmNodeOperands); 9512 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9513 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9514 if (OpInfo.isIndirect) { 9515 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9516 emitInlineAsmError(Call, "inline asm not supported yet: " 9517 "don't know how to handle tied " 9518 "indirect register inputs"); 9519 return; 9520 } 9521 9522 SmallVector<unsigned, 4> Regs; 9523 MachineFunction &MF = DAG.getMachineFunction(); 9524 MachineRegisterInfo &MRI = MF.getRegInfo(); 9525 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9526 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9527 Register TiedReg = R->getReg(); 9528 MVT RegVT = R->getSimpleValueType(0); 9529 const TargetRegisterClass *RC = 9530 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9531 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9532 : TRI.getMinimalPhysRegClass(TiedReg); 9533 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9534 Regs.push_back(MRI.createVirtualRegister(RC)); 9535 9536 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9537 9538 SDLoc dl = getCurSDLoc(); 9539 // Use the produced MatchedRegs object to 9540 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9541 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9542 OpInfo.getMatchedOperand(), dl, DAG, 9543 AsmNodeOperands); 9544 break; 9545 } 9546 9547 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9548 assert(Flag.getNumOperandRegisters() == 1 && 9549 "Unexpected number of operands"); 9550 // Add information to the INLINEASM node to know about this input. 9551 // See InlineAsm.h isUseOperandTiedToDef. 9552 Flag.clearMemConstraint(); 9553 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9554 AsmNodeOperands.push_back(DAG.getTargetConstant( 9555 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9556 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9557 break; 9558 } 9559 9560 // Treat indirect 'X' constraint as memory. 9561 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9562 OpInfo.isIndirect) 9563 OpInfo.ConstraintType = TargetLowering::C_Memory; 9564 9565 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9566 OpInfo.ConstraintType == TargetLowering::C_Other) { 9567 std::vector<SDValue> Ops; 9568 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9569 Ops, DAG); 9570 if (Ops.empty()) { 9571 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9572 if (isa<ConstantSDNode>(InOperandVal)) { 9573 emitInlineAsmError(Call, "value out of range for constraint '" + 9574 Twine(OpInfo.ConstraintCode) + "'"); 9575 return; 9576 } 9577 9578 emitInlineAsmError(Call, 9579 "invalid operand for inline asm constraint '" + 9580 Twine(OpInfo.ConstraintCode) + "'"); 9581 return; 9582 } 9583 9584 // Add information to the INLINEASM node to know about this input. 9585 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9586 AsmNodeOperands.push_back(DAG.getTargetConstant( 9587 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9588 llvm::append_range(AsmNodeOperands, Ops); 9589 break; 9590 } 9591 9592 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9593 assert((OpInfo.isIndirect || 9594 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9595 "Operand must be indirect to be a mem!"); 9596 assert(InOperandVal.getValueType() == 9597 TLI.getPointerTy(DAG.getDataLayout()) && 9598 "Memory operands expect pointer values"); 9599 9600 const InlineAsm::ConstraintCode ConstraintID = 9601 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9602 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9603 "Failed to convert memory constraint code to constraint id."); 9604 9605 // Add information to the INLINEASM node to know about this input. 9606 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9607 ResOpType.setMemConstraint(ConstraintID); 9608 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9609 getCurSDLoc(), 9610 MVT::i32)); 9611 AsmNodeOperands.push_back(InOperandVal); 9612 break; 9613 } 9614 9615 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9616 const InlineAsm::ConstraintCode ConstraintID = 9617 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9618 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9619 "Failed to convert memory constraint code to constraint id."); 9620 9621 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9622 9623 SDValue AsmOp = InOperandVal; 9624 if (isFunction(InOperandVal)) { 9625 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9626 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9627 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9628 InOperandVal.getValueType(), 9629 GA->getOffset()); 9630 } 9631 9632 // Add information to the INLINEASM node to know about this input. 9633 ResOpType.setMemConstraint(ConstraintID); 9634 9635 AsmNodeOperands.push_back( 9636 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9637 9638 AsmNodeOperands.push_back(AsmOp); 9639 break; 9640 } 9641 9642 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9643 OpInfo.ConstraintType == TargetLowering::C_Register) && 9644 "Unknown constraint type!"); 9645 9646 // TODO: Support this. 9647 if (OpInfo.isIndirect) { 9648 emitInlineAsmError( 9649 Call, "Don't know how to handle indirect register inputs yet " 9650 "for constraint '" + 9651 Twine(OpInfo.ConstraintCode) + "'"); 9652 return; 9653 } 9654 9655 // Copy the input into the appropriate registers. 9656 if (OpInfo.AssignedRegs.Regs.empty()) { 9657 emitInlineAsmError(Call, 9658 "couldn't allocate input reg for constraint '" + 9659 Twine(OpInfo.ConstraintCode) + "'"); 9660 return; 9661 } 9662 9663 if (DetectWriteToReservedRegister()) 9664 return; 9665 9666 SDLoc dl = getCurSDLoc(); 9667 9668 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9669 &Call); 9670 9671 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9672 0, dl, DAG, AsmNodeOperands); 9673 break; 9674 } 9675 case InlineAsm::isClobber: 9676 // Add the clobbered value to the operand list, so that the register 9677 // allocator is aware that the physreg got clobbered. 9678 if (!OpInfo.AssignedRegs.Regs.empty()) 9679 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9680 false, 0, getCurSDLoc(), DAG, 9681 AsmNodeOperands); 9682 break; 9683 } 9684 } 9685 9686 // Finish up input operands. Set the input chain and add the flag last. 9687 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9688 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9689 9690 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9691 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9692 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9693 Glue = Chain.getValue(1); 9694 9695 // Do additional work to generate outputs. 9696 9697 SmallVector<EVT, 1> ResultVTs; 9698 SmallVector<SDValue, 1> ResultValues; 9699 SmallVector<SDValue, 8> OutChains; 9700 9701 llvm::Type *CallResultType = Call.getType(); 9702 ArrayRef<Type *> ResultTypes; 9703 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9704 ResultTypes = StructResult->elements(); 9705 else if (!CallResultType->isVoidTy()) 9706 ResultTypes = ArrayRef(CallResultType); 9707 9708 auto CurResultType = ResultTypes.begin(); 9709 auto handleRegAssign = [&](SDValue V) { 9710 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9711 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9712 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9713 ++CurResultType; 9714 // If the type of the inline asm call site return value is different but has 9715 // same size as the type of the asm output bitcast it. One example of this 9716 // is for vectors with different width / number of elements. This can 9717 // happen for register classes that can contain multiple different value 9718 // types. The preg or vreg allocated may not have the same VT as was 9719 // expected. 9720 // 9721 // This can also happen for a return value that disagrees with the register 9722 // class it is put in, eg. a double in a general-purpose register on a 9723 // 32-bit machine. 9724 if (ResultVT != V.getValueType() && 9725 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9726 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9727 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9728 V.getValueType().isInteger()) { 9729 // If a result value was tied to an input value, the computed result 9730 // may have a wider width than the expected result. Extract the 9731 // relevant portion. 9732 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9733 } 9734 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9735 ResultVTs.push_back(ResultVT); 9736 ResultValues.push_back(V); 9737 }; 9738 9739 // Deal with output operands. 9740 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9741 if (OpInfo.Type == InlineAsm::isOutput) { 9742 SDValue Val; 9743 // Skip trivial output operands. 9744 if (OpInfo.AssignedRegs.Regs.empty()) 9745 continue; 9746 9747 switch (OpInfo.ConstraintType) { 9748 case TargetLowering::C_Register: 9749 case TargetLowering::C_RegisterClass: 9750 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9751 Chain, &Glue, &Call); 9752 break; 9753 case TargetLowering::C_Immediate: 9754 case TargetLowering::C_Other: 9755 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9756 OpInfo, DAG); 9757 break; 9758 case TargetLowering::C_Memory: 9759 break; // Already handled. 9760 case TargetLowering::C_Address: 9761 break; // Silence warning. 9762 case TargetLowering::C_Unknown: 9763 assert(false && "Unexpected unknown constraint"); 9764 } 9765 9766 // Indirect output manifest as stores. Record output chains. 9767 if (OpInfo.isIndirect) { 9768 const Value *Ptr = OpInfo.CallOperandVal; 9769 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9770 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9771 MachinePointerInfo(Ptr)); 9772 OutChains.push_back(Store); 9773 } else { 9774 // generate CopyFromRegs to associated registers. 9775 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9776 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9777 for (const SDValue &V : Val->op_values()) 9778 handleRegAssign(V); 9779 } else 9780 handleRegAssign(Val); 9781 } 9782 } 9783 } 9784 9785 // Set results. 9786 if (!ResultValues.empty()) { 9787 assert(CurResultType == ResultTypes.end() && 9788 "Mismatch in number of ResultTypes"); 9789 assert(ResultValues.size() == ResultTypes.size() && 9790 "Mismatch in number of output operands in asm result"); 9791 9792 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9793 DAG.getVTList(ResultVTs), ResultValues); 9794 setValue(&Call, V); 9795 } 9796 9797 // Collect store chains. 9798 if (!OutChains.empty()) 9799 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9800 9801 if (EmitEHLabels) { 9802 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9803 } 9804 9805 // Only Update Root if inline assembly has a memory effect. 9806 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9807 EmitEHLabels) 9808 DAG.setRoot(Chain); 9809 } 9810 9811 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9812 const Twine &Message) { 9813 LLVMContext &Ctx = *DAG.getContext(); 9814 Ctx.emitError(&Call, Message); 9815 9816 // Make sure we leave the DAG in a valid state 9817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9818 SmallVector<EVT, 1> ValueVTs; 9819 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9820 9821 if (ValueVTs.empty()) 9822 return; 9823 9824 SmallVector<SDValue, 1> Ops; 9825 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9826 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9827 9828 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9829 } 9830 9831 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9832 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9833 MVT::Other, getRoot(), 9834 getValue(I.getArgOperand(0)), 9835 DAG.getSrcValue(I.getArgOperand(0)))); 9836 } 9837 9838 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9839 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9840 const DataLayout &DL = DAG.getDataLayout(); 9841 SDValue V = DAG.getVAArg( 9842 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9843 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9844 DL.getABITypeAlign(I.getType()).value()); 9845 DAG.setRoot(V.getValue(1)); 9846 9847 if (I.getType()->isPointerTy()) 9848 V = DAG.getPtrExtOrTrunc( 9849 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9850 setValue(&I, V); 9851 } 9852 9853 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9854 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9855 MVT::Other, getRoot(), 9856 getValue(I.getArgOperand(0)), 9857 DAG.getSrcValue(I.getArgOperand(0)))); 9858 } 9859 9860 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9861 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9862 MVT::Other, getRoot(), 9863 getValue(I.getArgOperand(0)), 9864 getValue(I.getArgOperand(1)), 9865 DAG.getSrcValue(I.getArgOperand(0)), 9866 DAG.getSrcValue(I.getArgOperand(1)))); 9867 } 9868 9869 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9870 const Instruction &I, 9871 SDValue Op) { 9872 const MDNode *Range = getRangeMetadata(I); 9873 if (!Range) 9874 return Op; 9875 9876 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9877 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9878 return Op; 9879 9880 APInt Lo = CR.getUnsignedMin(); 9881 if (!Lo.isMinValue()) 9882 return Op; 9883 9884 APInt Hi = CR.getUnsignedMax(); 9885 unsigned Bits = std::max(Hi.getActiveBits(), 9886 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9887 9888 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9889 9890 SDLoc SL = getCurSDLoc(); 9891 9892 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9893 DAG.getValueType(SmallVT)); 9894 unsigned NumVals = Op.getNode()->getNumValues(); 9895 if (NumVals == 1) 9896 return ZExt; 9897 9898 SmallVector<SDValue, 4> Ops; 9899 9900 Ops.push_back(ZExt); 9901 for (unsigned I = 1; I != NumVals; ++I) 9902 Ops.push_back(Op.getValue(I)); 9903 9904 return DAG.getMergeValues(Ops, SL); 9905 } 9906 9907 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9908 /// the call being lowered. 9909 /// 9910 /// This is a helper for lowering intrinsics that follow a target calling 9911 /// convention or require stack pointer adjustment. Only a subset of the 9912 /// intrinsic's operands need to participate in the calling convention. 9913 void SelectionDAGBuilder::populateCallLoweringInfo( 9914 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9915 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9916 AttributeSet RetAttrs, bool IsPatchPoint) { 9917 TargetLowering::ArgListTy Args; 9918 Args.reserve(NumArgs); 9919 9920 // Populate the argument list. 9921 // Attributes for args start at offset 1, after the return attribute. 9922 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9923 ArgI != ArgE; ++ArgI) { 9924 const Value *V = Call->getOperand(ArgI); 9925 9926 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9927 9928 TargetLowering::ArgListEntry Entry; 9929 Entry.Node = getValue(V); 9930 Entry.Ty = V->getType(); 9931 Entry.setAttributes(Call, ArgI); 9932 Args.push_back(Entry); 9933 } 9934 9935 CLI.setDebugLoc(getCurSDLoc()) 9936 .setChain(getRoot()) 9937 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 9938 RetAttrs) 9939 .setDiscardResult(Call->use_empty()) 9940 .setIsPatchPoint(IsPatchPoint) 9941 .setIsPreallocated( 9942 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9943 } 9944 9945 /// Add a stack map intrinsic call's live variable operands to a stackmap 9946 /// or patchpoint target node's operand list. 9947 /// 9948 /// Constants are converted to TargetConstants purely as an optimization to 9949 /// avoid constant materialization and register allocation. 9950 /// 9951 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9952 /// generate addess computation nodes, and so FinalizeISel can convert the 9953 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9954 /// address materialization and register allocation, but may also be required 9955 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9956 /// alloca in the entry block, then the runtime may assume that the alloca's 9957 /// StackMap location can be read immediately after compilation and that the 9958 /// location is valid at any point during execution (this is similar to the 9959 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9960 /// only available in a register, then the runtime would need to trap when 9961 /// execution reaches the StackMap in order to read the alloca's location. 9962 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9963 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9964 SelectionDAGBuilder &Builder) { 9965 SelectionDAG &DAG = Builder.DAG; 9966 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9967 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9968 9969 // Things on the stack are pointer-typed, meaning that they are already 9970 // legal and can be emitted directly to target nodes. 9971 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9972 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9973 } else { 9974 // Otherwise emit a target independent node to be legalised. 9975 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9976 } 9977 } 9978 } 9979 9980 /// Lower llvm.experimental.stackmap. 9981 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9982 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9983 // [live variables...]) 9984 9985 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9986 9987 SDValue Chain, InGlue, Callee; 9988 SmallVector<SDValue, 32> Ops; 9989 9990 SDLoc DL = getCurSDLoc(); 9991 Callee = getValue(CI.getCalledOperand()); 9992 9993 // The stackmap intrinsic only records the live variables (the arguments 9994 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9995 // intrinsic, this won't be lowered to a function call. This means we don't 9996 // have to worry about calling conventions and target specific lowering code. 9997 // Instead we perform the call lowering right here. 9998 // 9999 // chain, flag = CALLSEQ_START(chain, 0, 0) 10000 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10001 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10002 // 10003 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10004 InGlue = Chain.getValue(1); 10005 10006 // Add the STACKMAP operands, starting with DAG house-keeping. 10007 Ops.push_back(Chain); 10008 Ops.push_back(InGlue); 10009 10010 // Add the <id>, <numShadowBytes> operands. 10011 // 10012 // These do not require legalisation, and can be emitted directly to target 10013 // constant nodes. 10014 SDValue ID = getValue(CI.getArgOperand(0)); 10015 assert(ID.getValueType() == MVT::i64); 10016 SDValue IDConst = 10017 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10018 Ops.push_back(IDConst); 10019 10020 SDValue Shad = getValue(CI.getArgOperand(1)); 10021 assert(Shad.getValueType() == MVT::i32); 10022 SDValue ShadConst = 10023 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10024 Ops.push_back(ShadConst); 10025 10026 // Add the live variables. 10027 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10028 10029 // Create the STACKMAP node. 10030 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10031 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10032 InGlue = Chain.getValue(1); 10033 10034 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10035 10036 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10037 10038 // Set the root to the target-lowered call chain. 10039 DAG.setRoot(Chain); 10040 10041 // Inform the Frame Information that we have a stackmap in this function. 10042 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10043 } 10044 10045 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10046 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10047 const BasicBlock *EHPadBB) { 10048 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 10049 // i32 <numBytes>, 10050 // i8* <target>, 10051 // i32 <numArgs>, 10052 // [Args...], 10053 // [live variables...]) 10054 10055 CallingConv::ID CC = CB.getCallingConv(); 10056 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10057 bool HasDef = !CB.getType()->isVoidTy(); 10058 SDLoc dl = getCurSDLoc(); 10059 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10060 10061 // Handle immediate and symbolic callees. 10062 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10063 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10064 /*isTarget=*/true); 10065 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10066 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10067 SDLoc(SymbolicCallee), 10068 SymbolicCallee->getValueType(0)); 10069 10070 // Get the real number of arguments participating in the call <numArgs> 10071 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10072 unsigned NumArgs = NArgVal->getAsZExtVal(); 10073 10074 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10075 // Intrinsics include all meta-operands up to but not including CC. 10076 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10077 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10078 "Not enough arguments provided to the patchpoint intrinsic"); 10079 10080 // For AnyRegCC the arguments are lowered later on manually. 10081 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10082 Type *ReturnTy = 10083 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10084 10085 TargetLowering::CallLoweringInfo CLI(DAG); 10086 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10087 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10088 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10089 10090 SDNode *CallEnd = Result.second.getNode(); 10091 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10092 CallEnd = CallEnd->getOperand(0).getNode(); 10093 10094 /// Get a call instruction from the call sequence chain. 10095 /// Tail calls are not allowed. 10096 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10097 "Expected a callseq node."); 10098 SDNode *Call = CallEnd->getOperand(0).getNode(); 10099 bool HasGlue = Call->getGluedNode(); 10100 10101 // Replace the target specific call node with the patchable intrinsic. 10102 SmallVector<SDValue, 8> Ops; 10103 10104 // Push the chain. 10105 Ops.push_back(*(Call->op_begin())); 10106 10107 // Optionally, push the glue (if any). 10108 if (HasGlue) 10109 Ops.push_back(*(Call->op_end() - 1)); 10110 10111 // Push the register mask info. 10112 if (HasGlue) 10113 Ops.push_back(*(Call->op_end() - 2)); 10114 else 10115 Ops.push_back(*(Call->op_end() - 1)); 10116 10117 // Add the <id> and <numBytes> constants. 10118 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10119 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10120 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10121 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10122 10123 // Add the callee. 10124 Ops.push_back(Callee); 10125 10126 // Adjust <numArgs> to account for any arguments that have been passed on the 10127 // stack instead. 10128 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10129 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10130 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10131 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10132 10133 // Add the calling convention 10134 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10135 10136 // Add the arguments we omitted previously. The register allocator should 10137 // place these in any free register. 10138 if (IsAnyRegCC) 10139 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10140 Ops.push_back(getValue(CB.getArgOperand(i))); 10141 10142 // Push the arguments from the call instruction. 10143 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10144 Ops.append(Call->op_begin() + 2, e); 10145 10146 // Push live variables for the stack map. 10147 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10148 10149 SDVTList NodeTys; 10150 if (IsAnyRegCC && HasDef) { 10151 // Create the return types based on the intrinsic definition 10152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10153 SmallVector<EVT, 3> ValueVTs; 10154 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10155 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10156 10157 // There is always a chain and a glue type at the end 10158 ValueVTs.push_back(MVT::Other); 10159 ValueVTs.push_back(MVT::Glue); 10160 NodeTys = DAG.getVTList(ValueVTs); 10161 } else 10162 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10163 10164 // Replace the target specific call node with a PATCHPOINT node. 10165 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10166 10167 // Update the NodeMap. 10168 if (HasDef) { 10169 if (IsAnyRegCC) 10170 setValue(&CB, SDValue(PPV.getNode(), 0)); 10171 else 10172 setValue(&CB, Result.first); 10173 } 10174 10175 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10176 // call sequence. Furthermore the location of the chain and glue can change 10177 // when the AnyReg calling convention is used and the intrinsic returns a 10178 // value. 10179 if (IsAnyRegCC && HasDef) { 10180 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10181 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10182 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10183 } else 10184 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10185 DAG.DeleteNode(Call); 10186 10187 // Inform the Frame Information that we have a patchpoint in this function. 10188 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10189 } 10190 10191 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10192 unsigned Intrinsic) { 10193 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10194 SDValue Op1 = getValue(I.getArgOperand(0)); 10195 SDValue Op2; 10196 if (I.arg_size() > 1) 10197 Op2 = getValue(I.getArgOperand(1)); 10198 SDLoc dl = getCurSDLoc(); 10199 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10200 SDValue Res; 10201 SDNodeFlags SDFlags; 10202 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10203 SDFlags.copyFMF(*FPMO); 10204 10205 switch (Intrinsic) { 10206 case Intrinsic::vector_reduce_fadd: 10207 if (SDFlags.hasAllowReassociation()) 10208 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10209 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10210 SDFlags); 10211 else 10212 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10213 break; 10214 case Intrinsic::vector_reduce_fmul: 10215 if (SDFlags.hasAllowReassociation()) 10216 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10217 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10218 SDFlags); 10219 else 10220 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10221 break; 10222 case Intrinsic::vector_reduce_add: 10223 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10224 break; 10225 case Intrinsic::vector_reduce_mul: 10226 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10227 break; 10228 case Intrinsic::vector_reduce_and: 10229 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10230 break; 10231 case Intrinsic::vector_reduce_or: 10232 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10233 break; 10234 case Intrinsic::vector_reduce_xor: 10235 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10236 break; 10237 case Intrinsic::vector_reduce_smax: 10238 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10239 break; 10240 case Intrinsic::vector_reduce_smin: 10241 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10242 break; 10243 case Intrinsic::vector_reduce_umax: 10244 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10245 break; 10246 case Intrinsic::vector_reduce_umin: 10247 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10248 break; 10249 case Intrinsic::vector_reduce_fmax: 10250 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10251 break; 10252 case Intrinsic::vector_reduce_fmin: 10253 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10254 break; 10255 case Intrinsic::vector_reduce_fmaximum: 10256 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10257 break; 10258 case Intrinsic::vector_reduce_fminimum: 10259 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10260 break; 10261 default: 10262 llvm_unreachable("Unhandled vector reduce intrinsic"); 10263 } 10264 setValue(&I, Res); 10265 } 10266 10267 /// Returns an AttributeList representing the attributes applied to the return 10268 /// value of the given call. 10269 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10270 SmallVector<Attribute::AttrKind, 2> Attrs; 10271 if (CLI.RetSExt) 10272 Attrs.push_back(Attribute::SExt); 10273 if (CLI.RetZExt) 10274 Attrs.push_back(Attribute::ZExt); 10275 if (CLI.IsInReg) 10276 Attrs.push_back(Attribute::InReg); 10277 10278 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10279 Attrs); 10280 } 10281 10282 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10283 /// implementation, which just calls LowerCall. 10284 /// FIXME: When all targets are 10285 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10286 std::pair<SDValue, SDValue> 10287 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10288 // Handle the incoming return values from the call. 10289 CLI.Ins.clear(); 10290 Type *OrigRetTy = CLI.RetTy; 10291 SmallVector<EVT, 4> RetTys; 10292 SmallVector<uint64_t, 4> Offsets; 10293 auto &DL = CLI.DAG.getDataLayout(); 10294 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10295 10296 if (CLI.IsPostTypeLegalization) { 10297 // If we are lowering a libcall after legalization, split the return type. 10298 SmallVector<EVT, 4> OldRetTys; 10299 SmallVector<uint64_t, 4> OldOffsets; 10300 RetTys.swap(OldRetTys); 10301 Offsets.swap(OldOffsets); 10302 10303 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10304 EVT RetVT = OldRetTys[i]; 10305 uint64_t Offset = OldOffsets[i]; 10306 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10307 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10308 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10309 RetTys.append(NumRegs, RegisterVT); 10310 for (unsigned j = 0; j != NumRegs; ++j) 10311 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10312 } 10313 } 10314 10315 SmallVector<ISD::OutputArg, 4> Outs; 10316 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10317 10318 bool CanLowerReturn = 10319 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10320 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10321 10322 SDValue DemoteStackSlot; 10323 int DemoteStackIdx = -100; 10324 if (!CanLowerReturn) { 10325 // FIXME: equivalent assert? 10326 // assert(!CS.hasInAllocaArgument() && 10327 // "sret demotion is incompatible with inalloca"); 10328 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10329 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10330 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10331 DemoteStackIdx = 10332 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10333 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10334 DL.getAllocaAddrSpace()); 10335 10336 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10337 ArgListEntry Entry; 10338 Entry.Node = DemoteStackSlot; 10339 Entry.Ty = StackSlotPtrType; 10340 Entry.IsSExt = false; 10341 Entry.IsZExt = false; 10342 Entry.IsInReg = false; 10343 Entry.IsSRet = true; 10344 Entry.IsNest = false; 10345 Entry.IsByVal = false; 10346 Entry.IsByRef = false; 10347 Entry.IsReturned = false; 10348 Entry.IsSwiftSelf = false; 10349 Entry.IsSwiftAsync = false; 10350 Entry.IsSwiftError = false; 10351 Entry.IsCFGuardTarget = false; 10352 Entry.Alignment = Alignment; 10353 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10354 CLI.NumFixedArgs += 1; 10355 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10356 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10357 10358 // sret demotion isn't compatible with tail-calls, since the sret argument 10359 // points into the callers stack frame. 10360 CLI.IsTailCall = false; 10361 } else { 10362 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10363 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10364 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10365 ISD::ArgFlagsTy Flags; 10366 if (NeedsRegBlock) { 10367 Flags.setInConsecutiveRegs(); 10368 if (I == RetTys.size() - 1) 10369 Flags.setInConsecutiveRegsLast(); 10370 } 10371 EVT VT = RetTys[I]; 10372 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10373 CLI.CallConv, VT); 10374 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10375 CLI.CallConv, VT); 10376 for (unsigned i = 0; i != NumRegs; ++i) { 10377 ISD::InputArg MyFlags; 10378 MyFlags.Flags = Flags; 10379 MyFlags.VT = RegisterVT; 10380 MyFlags.ArgVT = VT; 10381 MyFlags.Used = CLI.IsReturnValueUsed; 10382 if (CLI.RetTy->isPointerTy()) { 10383 MyFlags.Flags.setPointer(); 10384 MyFlags.Flags.setPointerAddrSpace( 10385 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10386 } 10387 if (CLI.RetSExt) 10388 MyFlags.Flags.setSExt(); 10389 if (CLI.RetZExt) 10390 MyFlags.Flags.setZExt(); 10391 if (CLI.IsInReg) 10392 MyFlags.Flags.setInReg(); 10393 CLI.Ins.push_back(MyFlags); 10394 } 10395 } 10396 } 10397 10398 // We push in swifterror return as the last element of CLI.Ins. 10399 ArgListTy &Args = CLI.getArgs(); 10400 if (supportSwiftError()) { 10401 for (const ArgListEntry &Arg : Args) { 10402 if (Arg.IsSwiftError) { 10403 ISD::InputArg MyFlags; 10404 MyFlags.VT = getPointerTy(DL); 10405 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10406 MyFlags.Flags.setSwiftError(); 10407 CLI.Ins.push_back(MyFlags); 10408 } 10409 } 10410 } 10411 10412 // Handle all of the outgoing arguments. 10413 CLI.Outs.clear(); 10414 CLI.OutVals.clear(); 10415 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10416 SmallVector<EVT, 4> ValueVTs; 10417 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10418 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10419 Type *FinalType = Args[i].Ty; 10420 if (Args[i].IsByVal) 10421 FinalType = Args[i].IndirectType; 10422 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10423 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10424 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10425 ++Value) { 10426 EVT VT = ValueVTs[Value]; 10427 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10428 SDValue Op = SDValue(Args[i].Node.getNode(), 10429 Args[i].Node.getResNo() + Value); 10430 ISD::ArgFlagsTy Flags; 10431 10432 // Certain targets (such as MIPS), may have a different ABI alignment 10433 // for a type depending on the context. Give the target a chance to 10434 // specify the alignment it wants. 10435 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10436 Flags.setOrigAlign(OriginalAlignment); 10437 10438 if (Args[i].Ty->isPointerTy()) { 10439 Flags.setPointer(); 10440 Flags.setPointerAddrSpace( 10441 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10442 } 10443 if (Args[i].IsZExt) 10444 Flags.setZExt(); 10445 if (Args[i].IsSExt) 10446 Flags.setSExt(); 10447 if (Args[i].IsInReg) { 10448 // If we are using vectorcall calling convention, a structure that is 10449 // passed InReg - is surely an HVA 10450 if (CLI.CallConv == CallingConv::X86_VectorCall && 10451 isa<StructType>(FinalType)) { 10452 // The first value of a structure is marked 10453 if (0 == Value) 10454 Flags.setHvaStart(); 10455 Flags.setHva(); 10456 } 10457 // Set InReg Flag 10458 Flags.setInReg(); 10459 } 10460 if (Args[i].IsSRet) 10461 Flags.setSRet(); 10462 if (Args[i].IsSwiftSelf) 10463 Flags.setSwiftSelf(); 10464 if (Args[i].IsSwiftAsync) 10465 Flags.setSwiftAsync(); 10466 if (Args[i].IsSwiftError) 10467 Flags.setSwiftError(); 10468 if (Args[i].IsCFGuardTarget) 10469 Flags.setCFGuardTarget(); 10470 if (Args[i].IsByVal) 10471 Flags.setByVal(); 10472 if (Args[i].IsByRef) 10473 Flags.setByRef(); 10474 if (Args[i].IsPreallocated) { 10475 Flags.setPreallocated(); 10476 // Set the byval flag for CCAssignFn callbacks that don't know about 10477 // preallocated. This way we can know how many bytes we should've 10478 // allocated and how many bytes a callee cleanup function will pop. If 10479 // we port preallocated to more targets, we'll have to add custom 10480 // preallocated handling in the various CC lowering callbacks. 10481 Flags.setByVal(); 10482 } 10483 if (Args[i].IsInAlloca) { 10484 Flags.setInAlloca(); 10485 // Set the byval flag for CCAssignFn callbacks that don't know about 10486 // inalloca. This way we can know how many bytes we should've allocated 10487 // and how many bytes a callee cleanup function will pop. If we port 10488 // inalloca to more targets, we'll have to add custom inalloca handling 10489 // in the various CC lowering callbacks. 10490 Flags.setByVal(); 10491 } 10492 Align MemAlign; 10493 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10494 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10495 Flags.setByValSize(FrameSize); 10496 10497 // info is not there but there are cases it cannot get right. 10498 if (auto MA = Args[i].Alignment) 10499 MemAlign = *MA; 10500 else 10501 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10502 } else if (auto MA = Args[i].Alignment) { 10503 MemAlign = *MA; 10504 } else { 10505 MemAlign = OriginalAlignment; 10506 } 10507 Flags.setMemAlign(MemAlign); 10508 if (Args[i].IsNest) 10509 Flags.setNest(); 10510 if (NeedsRegBlock) 10511 Flags.setInConsecutiveRegs(); 10512 10513 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10514 CLI.CallConv, VT); 10515 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10516 CLI.CallConv, VT); 10517 SmallVector<SDValue, 4> Parts(NumParts); 10518 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10519 10520 if (Args[i].IsSExt) 10521 ExtendKind = ISD::SIGN_EXTEND; 10522 else if (Args[i].IsZExt) 10523 ExtendKind = ISD::ZERO_EXTEND; 10524 10525 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10526 // for now. 10527 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10528 CanLowerReturn) { 10529 assert((CLI.RetTy == Args[i].Ty || 10530 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10531 CLI.RetTy->getPointerAddressSpace() == 10532 Args[i].Ty->getPointerAddressSpace())) && 10533 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10534 // Before passing 'returned' to the target lowering code, ensure that 10535 // either the register MVT and the actual EVT are the same size or that 10536 // the return value and argument are extended in the same way; in these 10537 // cases it's safe to pass the argument register value unchanged as the 10538 // return register value (although it's at the target's option whether 10539 // to do so) 10540 // TODO: allow code generation to take advantage of partially preserved 10541 // registers rather than clobbering the entire register when the 10542 // parameter extension method is not compatible with the return 10543 // extension method 10544 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10545 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10546 CLI.RetZExt == Args[i].IsZExt)) 10547 Flags.setReturned(); 10548 } 10549 10550 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10551 CLI.CallConv, ExtendKind); 10552 10553 for (unsigned j = 0; j != NumParts; ++j) { 10554 // if it isn't first piece, alignment must be 1 10555 // For scalable vectors the scalable part is currently handled 10556 // by individual targets, so we just use the known minimum size here. 10557 ISD::OutputArg MyFlags( 10558 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10559 i < CLI.NumFixedArgs, i, 10560 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10561 if (NumParts > 1 && j == 0) 10562 MyFlags.Flags.setSplit(); 10563 else if (j != 0) { 10564 MyFlags.Flags.setOrigAlign(Align(1)); 10565 if (j == NumParts - 1) 10566 MyFlags.Flags.setSplitEnd(); 10567 } 10568 10569 CLI.Outs.push_back(MyFlags); 10570 CLI.OutVals.push_back(Parts[j]); 10571 } 10572 10573 if (NeedsRegBlock && Value == NumValues - 1) 10574 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10575 } 10576 } 10577 10578 SmallVector<SDValue, 4> InVals; 10579 CLI.Chain = LowerCall(CLI, InVals); 10580 10581 // Update CLI.InVals to use outside of this function. 10582 CLI.InVals = InVals; 10583 10584 // Verify that the target's LowerCall behaved as expected. 10585 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10586 "LowerCall didn't return a valid chain!"); 10587 assert((!CLI.IsTailCall || InVals.empty()) && 10588 "LowerCall emitted a return value for a tail call!"); 10589 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10590 "LowerCall didn't emit the correct number of values!"); 10591 10592 // For a tail call, the return value is merely live-out and there aren't 10593 // any nodes in the DAG representing it. Return a special value to 10594 // indicate that a tail call has been emitted and no more Instructions 10595 // should be processed in the current block. 10596 if (CLI.IsTailCall) { 10597 CLI.DAG.setRoot(CLI.Chain); 10598 return std::make_pair(SDValue(), SDValue()); 10599 } 10600 10601 #ifndef NDEBUG 10602 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10603 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10604 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10605 "LowerCall emitted a value with the wrong type!"); 10606 } 10607 #endif 10608 10609 SmallVector<SDValue, 4> ReturnValues; 10610 if (!CanLowerReturn) { 10611 // The instruction result is the result of loading from the 10612 // hidden sret parameter. 10613 SmallVector<EVT, 1> PVTs; 10614 Type *PtrRetTy = 10615 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10616 10617 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10618 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10619 EVT PtrVT = PVTs[0]; 10620 10621 unsigned NumValues = RetTys.size(); 10622 ReturnValues.resize(NumValues); 10623 SmallVector<SDValue, 4> Chains(NumValues); 10624 10625 // An aggregate return value cannot wrap around the address space, so 10626 // offsets to its parts don't wrap either. 10627 SDNodeFlags Flags; 10628 Flags.setNoUnsignedWrap(true); 10629 10630 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10631 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10632 for (unsigned i = 0; i < NumValues; ++i) { 10633 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10634 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10635 PtrVT), Flags); 10636 SDValue L = CLI.DAG.getLoad( 10637 RetTys[i], CLI.DL, CLI.Chain, Add, 10638 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10639 DemoteStackIdx, Offsets[i]), 10640 HiddenSRetAlign); 10641 ReturnValues[i] = L; 10642 Chains[i] = L.getValue(1); 10643 } 10644 10645 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10646 } else { 10647 // Collect the legal value parts into potentially illegal values 10648 // that correspond to the original function's return values. 10649 std::optional<ISD::NodeType> AssertOp; 10650 if (CLI.RetSExt) 10651 AssertOp = ISD::AssertSext; 10652 else if (CLI.RetZExt) 10653 AssertOp = ISD::AssertZext; 10654 unsigned CurReg = 0; 10655 for (EVT VT : RetTys) { 10656 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10657 CLI.CallConv, VT); 10658 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10659 CLI.CallConv, VT); 10660 10661 ReturnValues.push_back(getCopyFromParts( 10662 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 10663 CLI.Chain, CLI.CallConv, AssertOp)); 10664 CurReg += NumRegs; 10665 } 10666 10667 // For a function returning void, there is no return value. We can't create 10668 // such a node, so we just return a null return value in that case. In 10669 // that case, nothing will actually look at the value. 10670 if (ReturnValues.empty()) 10671 return std::make_pair(SDValue(), CLI.Chain); 10672 } 10673 10674 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10675 CLI.DAG.getVTList(RetTys), ReturnValues); 10676 return std::make_pair(Res, CLI.Chain); 10677 } 10678 10679 /// Places new result values for the node in Results (their number 10680 /// and types must exactly match those of the original return values of 10681 /// the node), or leaves Results empty, which indicates that the node is not 10682 /// to be custom lowered after all. 10683 void TargetLowering::LowerOperationWrapper(SDNode *N, 10684 SmallVectorImpl<SDValue> &Results, 10685 SelectionDAG &DAG) const { 10686 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10687 10688 if (!Res.getNode()) 10689 return; 10690 10691 // If the original node has one result, take the return value from 10692 // LowerOperation as is. It might not be result number 0. 10693 if (N->getNumValues() == 1) { 10694 Results.push_back(Res); 10695 return; 10696 } 10697 10698 // If the original node has multiple results, then the return node should 10699 // have the same number of results. 10700 assert((N->getNumValues() == Res->getNumValues()) && 10701 "Lowering returned the wrong number of results!"); 10702 10703 // Places new result values base on N result number. 10704 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10705 Results.push_back(Res.getValue(I)); 10706 } 10707 10708 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10709 llvm_unreachable("LowerOperation not implemented for this target!"); 10710 } 10711 10712 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10713 unsigned Reg, 10714 ISD::NodeType ExtendType) { 10715 SDValue Op = getNonRegisterValue(V); 10716 assert((Op.getOpcode() != ISD::CopyFromReg || 10717 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10718 "Copy from a reg to the same reg!"); 10719 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10720 10721 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10722 // If this is an InlineAsm we have to match the registers required, not the 10723 // notional registers required by the type. 10724 10725 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10726 std::nullopt); // This is not an ABI copy. 10727 SDValue Chain = DAG.getEntryNode(); 10728 10729 if (ExtendType == ISD::ANY_EXTEND) { 10730 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10731 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10732 ExtendType = PreferredExtendIt->second; 10733 } 10734 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10735 PendingExports.push_back(Chain); 10736 } 10737 10738 #include "llvm/CodeGen/SelectionDAGISel.h" 10739 10740 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10741 /// entry block, return true. This includes arguments used by switches, since 10742 /// the switch may expand into multiple basic blocks. 10743 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10744 // With FastISel active, we may be splitting blocks, so force creation 10745 // of virtual registers for all non-dead arguments. 10746 if (FastISel) 10747 return A->use_empty(); 10748 10749 const BasicBlock &Entry = A->getParent()->front(); 10750 for (const User *U : A->users()) 10751 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10752 return false; // Use not in entry block. 10753 10754 return true; 10755 } 10756 10757 using ArgCopyElisionMapTy = 10758 DenseMap<const Argument *, 10759 std::pair<const AllocaInst *, const StoreInst *>>; 10760 10761 /// Scan the entry block of the function in FuncInfo for arguments that look 10762 /// like copies into a local alloca. Record any copied arguments in 10763 /// ArgCopyElisionCandidates. 10764 static void 10765 findArgumentCopyElisionCandidates(const DataLayout &DL, 10766 FunctionLoweringInfo *FuncInfo, 10767 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10768 // Record the state of every static alloca used in the entry block. Argument 10769 // allocas are all used in the entry block, so we need approximately as many 10770 // entries as we have arguments. 10771 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10772 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10773 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10774 StaticAllocas.reserve(NumArgs * 2); 10775 10776 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10777 if (!V) 10778 return nullptr; 10779 V = V->stripPointerCasts(); 10780 const auto *AI = dyn_cast<AllocaInst>(V); 10781 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10782 return nullptr; 10783 auto Iter = StaticAllocas.insert({AI, Unknown}); 10784 return &Iter.first->second; 10785 }; 10786 10787 // Look for stores of arguments to static allocas. Look through bitcasts and 10788 // GEPs to handle type coercions, as long as the alloca is fully initialized 10789 // by the store. Any non-store use of an alloca escapes it and any subsequent 10790 // unanalyzed store might write it. 10791 // FIXME: Handle structs initialized with multiple stores. 10792 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10793 // Look for stores, and handle non-store uses conservatively. 10794 const auto *SI = dyn_cast<StoreInst>(&I); 10795 if (!SI) { 10796 // We will look through cast uses, so ignore them completely. 10797 if (I.isCast()) 10798 continue; 10799 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10800 // to allocas. 10801 if (I.isDebugOrPseudoInst()) 10802 continue; 10803 // This is an unknown instruction. Assume it escapes or writes to all 10804 // static alloca operands. 10805 for (const Use &U : I.operands()) { 10806 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10807 *Info = StaticAllocaInfo::Clobbered; 10808 } 10809 continue; 10810 } 10811 10812 // If the stored value is a static alloca, mark it as escaped. 10813 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10814 *Info = StaticAllocaInfo::Clobbered; 10815 10816 // Check if the destination is a static alloca. 10817 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10818 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10819 if (!Info) 10820 continue; 10821 const AllocaInst *AI = cast<AllocaInst>(Dst); 10822 10823 // Skip allocas that have been initialized or clobbered. 10824 if (*Info != StaticAllocaInfo::Unknown) 10825 continue; 10826 10827 // Check if the stored value is an argument, and that this store fully 10828 // initializes the alloca. 10829 // If the argument type has padding bits we can't directly forward a pointer 10830 // as the upper bits may contain garbage. 10831 // Don't elide copies from the same argument twice. 10832 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10833 const auto *Arg = dyn_cast<Argument>(Val); 10834 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10835 Arg->getType()->isEmptyTy() || 10836 DL.getTypeStoreSize(Arg->getType()) != 10837 DL.getTypeAllocSize(AI->getAllocatedType()) || 10838 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10839 ArgCopyElisionCandidates.count(Arg)) { 10840 *Info = StaticAllocaInfo::Clobbered; 10841 continue; 10842 } 10843 10844 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10845 << '\n'); 10846 10847 // Mark this alloca and store for argument copy elision. 10848 *Info = StaticAllocaInfo::Elidable; 10849 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10850 10851 // Stop scanning if we've seen all arguments. This will happen early in -O0 10852 // builds, which is useful, because -O0 builds have large entry blocks and 10853 // many allocas. 10854 if (ArgCopyElisionCandidates.size() == NumArgs) 10855 break; 10856 } 10857 } 10858 10859 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10860 /// ArgVal is a load from a suitable fixed stack object. 10861 static void tryToElideArgumentCopy( 10862 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10863 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10864 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10865 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10866 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10867 // Check if this is a load from a fixed stack object. 10868 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10869 if (!LNode) 10870 return; 10871 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10872 if (!FINode) 10873 return; 10874 10875 // Check that the fixed stack object is the right size and alignment. 10876 // Look at the alignment that the user wrote on the alloca instead of looking 10877 // at the stack object. 10878 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10879 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10880 const AllocaInst *AI = ArgCopyIter->second.first; 10881 int FixedIndex = FINode->getIndex(); 10882 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10883 int OldIndex = AllocaIndex; 10884 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10885 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10886 LLVM_DEBUG( 10887 dbgs() << " argument copy elision failed due to bad fixed stack " 10888 "object size\n"); 10889 return; 10890 } 10891 Align RequiredAlignment = AI->getAlign(); 10892 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10893 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10894 "greater than stack argument alignment (" 10895 << DebugStr(RequiredAlignment) << " vs " 10896 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10897 return; 10898 } 10899 10900 // Perform the elision. Delete the old stack object and replace its only use 10901 // in the variable info map. Mark the stack object as mutable. 10902 LLVM_DEBUG({ 10903 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10904 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10905 << '\n'; 10906 }); 10907 MFI.RemoveStackObject(OldIndex); 10908 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10909 AllocaIndex = FixedIndex; 10910 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10911 for (SDValue ArgVal : ArgVals) 10912 Chains.push_back(ArgVal.getValue(1)); 10913 10914 // Avoid emitting code for the store implementing the copy. 10915 const StoreInst *SI = ArgCopyIter->second.second; 10916 ElidedArgCopyInstrs.insert(SI); 10917 10918 // Check for uses of the argument again so that we can avoid exporting ArgVal 10919 // if it is't used by anything other than the store. 10920 for (const Value *U : Arg.users()) { 10921 if (U != SI) { 10922 ArgHasUses = true; 10923 break; 10924 } 10925 } 10926 } 10927 10928 void SelectionDAGISel::LowerArguments(const Function &F) { 10929 SelectionDAG &DAG = SDB->DAG; 10930 SDLoc dl = SDB->getCurSDLoc(); 10931 const DataLayout &DL = DAG.getDataLayout(); 10932 SmallVector<ISD::InputArg, 16> Ins; 10933 10934 // In Naked functions we aren't going to save any registers. 10935 if (F.hasFnAttribute(Attribute::Naked)) 10936 return; 10937 10938 if (!FuncInfo->CanLowerReturn) { 10939 // Put in an sret pointer parameter before all the other parameters. 10940 SmallVector<EVT, 1> ValueVTs; 10941 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10942 PointerType::get(F.getContext(), 10943 DAG.getDataLayout().getAllocaAddrSpace()), 10944 ValueVTs); 10945 10946 // NOTE: Assuming that a pointer will never break down to more than one VT 10947 // or one register. 10948 ISD::ArgFlagsTy Flags; 10949 Flags.setSRet(); 10950 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10951 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10952 ISD::InputArg::NoArgIndex, 0); 10953 Ins.push_back(RetArg); 10954 } 10955 10956 // Look for stores of arguments to static allocas. Mark such arguments with a 10957 // flag to ask the target to give us the memory location of that argument if 10958 // available. 10959 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10960 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10961 ArgCopyElisionCandidates); 10962 10963 // Set up the incoming argument description vector. 10964 for (const Argument &Arg : F.args()) { 10965 unsigned ArgNo = Arg.getArgNo(); 10966 SmallVector<EVT, 4> ValueVTs; 10967 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10968 bool isArgValueUsed = !Arg.use_empty(); 10969 unsigned PartBase = 0; 10970 Type *FinalType = Arg.getType(); 10971 if (Arg.hasAttribute(Attribute::ByVal)) 10972 FinalType = Arg.getParamByValType(); 10973 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10974 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10975 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10976 Value != NumValues; ++Value) { 10977 EVT VT = ValueVTs[Value]; 10978 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10979 ISD::ArgFlagsTy Flags; 10980 10981 10982 if (Arg.getType()->isPointerTy()) { 10983 Flags.setPointer(); 10984 Flags.setPointerAddrSpace( 10985 cast<PointerType>(Arg.getType())->getAddressSpace()); 10986 } 10987 if (Arg.hasAttribute(Attribute::ZExt)) 10988 Flags.setZExt(); 10989 if (Arg.hasAttribute(Attribute::SExt)) 10990 Flags.setSExt(); 10991 if (Arg.hasAttribute(Attribute::InReg)) { 10992 // If we are using vectorcall calling convention, a structure that is 10993 // passed InReg - is surely an HVA 10994 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10995 isa<StructType>(Arg.getType())) { 10996 // The first value of a structure is marked 10997 if (0 == Value) 10998 Flags.setHvaStart(); 10999 Flags.setHva(); 11000 } 11001 // Set InReg Flag 11002 Flags.setInReg(); 11003 } 11004 if (Arg.hasAttribute(Attribute::StructRet)) 11005 Flags.setSRet(); 11006 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11007 Flags.setSwiftSelf(); 11008 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11009 Flags.setSwiftAsync(); 11010 if (Arg.hasAttribute(Attribute::SwiftError)) 11011 Flags.setSwiftError(); 11012 if (Arg.hasAttribute(Attribute::ByVal)) 11013 Flags.setByVal(); 11014 if (Arg.hasAttribute(Attribute::ByRef)) 11015 Flags.setByRef(); 11016 if (Arg.hasAttribute(Attribute::InAlloca)) { 11017 Flags.setInAlloca(); 11018 // Set the byval flag for CCAssignFn callbacks that don't know about 11019 // inalloca. This way we can know how many bytes we should've allocated 11020 // and how many bytes a callee cleanup function will pop. If we port 11021 // inalloca to more targets, we'll have to add custom inalloca handling 11022 // in the various CC lowering callbacks. 11023 Flags.setByVal(); 11024 } 11025 if (Arg.hasAttribute(Attribute::Preallocated)) { 11026 Flags.setPreallocated(); 11027 // Set the byval flag for CCAssignFn callbacks that don't know about 11028 // preallocated. This way we can know how many bytes we should've 11029 // allocated and how many bytes a callee cleanup function will pop. If 11030 // we port preallocated to more targets, we'll have to add custom 11031 // preallocated handling in the various CC lowering callbacks. 11032 Flags.setByVal(); 11033 } 11034 11035 // Certain targets (such as MIPS), may have a different ABI alignment 11036 // for a type depending on the context. Give the target a chance to 11037 // specify the alignment it wants. 11038 const Align OriginalAlignment( 11039 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11040 Flags.setOrigAlign(OriginalAlignment); 11041 11042 Align MemAlign; 11043 Type *ArgMemTy = nullptr; 11044 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11045 Flags.isByRef()) { 11046 if (!ArgMemTy) 11047 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11048 11049 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11050 11051 // For in-memory arguments, size and alignment should be passed from FE. 11052 // BE will guess if this info is not there but there are cases it cannot 11053 // get right. 11054 if (auto ParamAlign = Arg.getParamStackAlign()) 11055 MemAlign = *ParamAlign; 11056 else if ((ParamAlign = Arg.getParamAlign())) 11057 MemAlign = *ParamAlign; 11058 else 11059 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11060 if (Flags.isByRef()) 11061 Flags.setByRefSize(MemSize); 11062 else 11063 Flags.setByValSize(MemSize); 11064 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11065 MemAlign = *ParamAlign; 11066 } else { 11067 MemAlign = OriginalAlignment; 11068 } 11069 Flags.setMemAlign(MemAlign); 11070 11071 if (Arg.hasAttribute(Attribute::Nest)) 11072 Flags.setNest(); 11073 if (NeedsRegBlock) 11074 Flags.setInConsecutiveRegs(); 11075 if (ArgCopyElisionCandidates.count(&Arg)) 11076 Flags.setCopyElisionCandidate(); 11077 if (Arg.hasAttribute(Attribute::Returned)) 11078 Flags.setReturned(); 11079 11080 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11081 *CurDAG->getContext(), F.getCallingConv(), VT); 11082 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11083 *CurDAG->getContext(), F.getCallingConv(), VT); 11084 for (unsigned i = 0; i != NumRegs; ++i) { 11085 // For scalable vectors, use the minimum size; individual targets 11086 // are responsible for handling scalable vector arguments and 11087 // return values. 11088 ISD::InputArg MyFlags( 11089 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11090 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11091 if (NumRegs > 1 && i == 0) 11092 MyFlags.Flags.setSplit(); 11093 // if it isn't first piece, alignment must be 1 11094 else if (i > 0) { 11095 MyFlags.Flags.setOrigAlign(Align(1)); 11096 if (i == NumRegs - 1) 11097 MyFlags.Flags.setSplitEnd(); 11098 } 11099 Ins.push_back(MyFlags); 11100 } 11101 if (NeedsRegBlock && Value == NumValues - 1) 11102 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11103 PartBase += VT.getStoreSize().getKnownMinValue(); 11104 } 11105 } 11106 11107 // Call the target to set up the argument values. 11108 SmallVector<SDValue, 8> InVals; 11109 SDValue NewRoot = TLI->LowerFormalArguments( 11110 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11111 11112 // Verify that the target's LowerFormalArguments behaved as expected. 11113 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11114 "LowerFormalArguments didn't return a valid chain!"); 11115 assert(InVals.size() == Ins.size() && 11116 "LowerFormalArguments didn't emit the correct number of values!"); 11117 LLVM_DEBUG({ 11118 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11119 assert(InVals[i].getNode() && 11120 "LowerFormalArguments emitted a null value!"); 11121 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11122 "LowerFormalArguments emitted a value with the wrong type!"); 11123 } 11124 }); 11125 11126 // Update the DAG with the new chain value resulting from argument lowering. 11127 DAG.setRoot(NewRoot); 11128 11129 // Set up the argument values. 11130 unsigned i = 0; 11131 if (!FuncInfo->CanLowerReturn) { 11132 // Create a virtual register for the sret pointer, and put in a copy 11133 // from the sret argument into it. 11134 SmallVector<EVT, 1> ValueVTs; 11135 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11136 PointerType::get(F.getContext(), 11137 DAG.getDataLayout().getAllocaAddrSpace()), 11138 ValueVTs); 11139 MVT VT = ValueVTs[0].getSimpleVT(); 11140 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11141 std::optional<ISD::NodeType> AssertOp; 11142 SDValue ArgValue = 11143 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11144 F.getCallingConv(), AssertOp); 11145 11146 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11147 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11148 Register SRetReg = 11149 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11150 FuncInfo->DemoteRegister = SRetReg; 11151 NewRoot = 11152 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11153 DAG.setRoot(NewRoot); 11154 11155 // i indexes lowered arguments. Bump it past the hidden sret argument. 11156 ++i; 11157 } 11158 11159 SmallVector<SDValue, 4> Chains; 11160 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11161 for (const Argument &Arg : F.args()) { 11162 SmallVector<SDValue, 4> ArgValues; 11163 SmallVector<EVT, 4> ValueVTs; 11164 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11165 unsigned NumValues = ValueVTs.size(); 11166 if (NumValues == 0) 11167 continue; 11168 11169 bool ArgHasUses = !Arg.use_empty(); 11170 11171 // Elide the copying store if the target loaded this argument from a 11172 // suitable fixed stack object. 11173 if (Ins[i].Flags.isCopyElisionCandidate()) { 11174 unsigned NumParts = 0; 11175 for (EVT VT : ValueVTs) 11176 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11177 F.getCallingConv(), VT); 11178 11179 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11180 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11181 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11182 } 11183 11184 // If this argument is unused then remember its value. It is used to generate 11185 // debugging information. 11186 bool isSwiftErrorArg = 11187 TLI->supportSwiftError() && 11188 Arg.hasAttribute(Attribute::SwiftError); 11189 if (!ArgHasUses && !isSwiftErrorArg) { 11190 SDB->setUnusedArgValue(&Arg, InVals[i]); 11191 11192 // Also remember any frame index for use in FastISel. 11193 if (FrameIndexSDNode *FI = 11194 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11195 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11196 } 11197 11198 for (unsigned Val = 0; Val != NumValues; ++Val) { 11199 EVT VT = ValueVTs[Val]; 11200 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11201 F.getCallingConv(), VT); 11202 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11203 *CurDAG->getContext(), F.getCallingConv(), VT); 11204 11205 // Even an apparent 'unused' swifterror argument needs to be returned. So 11206 // we do generate a copy for it that can be used on return from the 11207 // function. 11208 if (ArgHasUses || isSwiftErrorArg) { 11209 std::optional<ISD::NodeType> AssertOp; 11210 if (Arg.hasAttribute(Attribute::SExt)) 11211 AssertOp = ISD::AssertSext; 11212 else if (Arg.hasAttribute(Attribute::ZExt)) 11213 AssertOp = ISD::AssertZext; 11214 11215 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11216 PartVT, VT, nullptr, NewRoot, 11217 F.getCallingConv(), AssertOp)); 11218 } 11219 11220 i += NumParts; 11221 } 11222 11223 // We don't need to do anything else for unused arguments. 11224 if (ArgValues.empty()) 11225 continue; 11226 11227 // Note down frame index. 11228 if (FrameIndexSDNode *FI = 11229 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11230 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11231 11232 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11233 SDB->getCurSDLoc()); 11234 11235 SDB->setValue(&Arg, Res); 11236 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11237 // We want to associate the argument with the frame index, among 11238 // involved operands, that correspond to the lowest address. The 11239 // getCopyFromParts function, called earlier, is swapping the order of 11240 // the operands to BUILD_PAIR depending on endianness. The result of 11241 // that swapping is that the least significant bits of the argument will 11242 // be in the first operand of the BUILD_PAIR node, and the most 11243 // significant bits will be in the second operand. 11244 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11245 if (LoadSDNode *LNode = 11246 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11247 if (FrameIndexSDNode *FI = 11248 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11249 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11250 } 11251 11252 // Analyses past this point are naive and don't expect an assertion. 11253 if (Res.getOpcode() == ISD::AssertZext) 11254 Res = Res.getOperand(0); 11255 11256 // Update the SwiftErrorVRegDefMap. 11257 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11258 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11259 if (Register::isVirtualRegister(Reg)) 11260 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11261 Reg); 11262 } 11263 11264 // If this argument is live outside of the entry block, insert a copy from 11265 // wherever we got it to the vreg that other BB's will reference it as. 11266 if (Res.getOpcode() == ISD::CopyFromReg) { 11267 // If we can, though, try to skip creating an unnecessary vreg. 11268 // FIXME: This isn't very clean... it would be nice to make this more 11269 // general. 11270 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11271 if (Register::isVirtualRegister(Reg)) { 11272 FuncInfo->ValueMap[&Arg] = Reg; 11273 continue; 11274 } 11275 } 11276 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11277 FuncInfo->InitializeRegForValue(&Arg); 11278 SDB->CopyToExportRegsIfNeeded(&Arg); 11279 } 11280 } 11281 11282 if (!Chains.empty()) { 11283 Chains.push_back(NewRoot); 11284 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11285 } 11286 11287 DAG.setRoot(NewRoot); 11288 11289 assert(i == InVals.size() && "Argument register count mismatch!"); 11290 11291 // If any argument copy elisions occurred and we have debug info, update the 11292 // stale frame indices used in the dbg.declare variable info table. 11293 if (!ArgCopyElisionFrameIndexMap.empty()) { 11294 for (MachineFunction::VariableDbgInfo &VI : 11295 MF->getInStackSlotVariableDbgInfo()) { 11296 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11297 if (I != ArgCopyElisionFrameIndexMap.end()) 11298 VI.updateStackSlot(I->second); 11299 } 11300 } 11301 11302 // Finally, if the target has anything special to do, allow it to do so. 11303 emitFunctionEntryCode(); 11304 } 11305 11306 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11307 /// ensure constants are generated when needed. Remember the virtual registers 11308 /// that need to be added to the Machine PHI nodes as input. We cannot just 11309 /// directly add them, because expansion might result in multiple MBB's for one 11310 /// BB. As such, the start of the BB might correspond to a different MBB than 11311 /// the end. 11312 void 11313 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11315 11316 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11317 11318 // Check PHI nodes in successors that expect a value to be available from this 11319 // block. 11320 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11321 if (!isa<PHINode>(SuccBB->begin())) continue; 11322 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11323 11324 // If this terminator has multiple identical successors (common for 11325 // switches), only handle each succ once. 11326 if (!SuccsHandled.insert(SuccMBB).second) 11327 continue; 11328 11329 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11330 11331 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11332 // nodes and Machine PHI nodes, but the incoming operands have not been 11333 // emitted yet. 11334 for (const PHINode &PN : SuccBB->phis()) { 11335 // Ignore dead phi's. 11336 if (PN.use_empty()) 11337 continue; 11338 11339 // Skip empty types 11340 if (PN.getType()->isEmptyTy()) 11341 continue; 11342 11343 unsigned Reg; 11344 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11345 11346 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11347 unsigned &RegOut = ConstantsOut[C]; 11348 if (RegOut == 0) { 11349 RegOut = FuncInfo.CreateRegs(C); 11350 // We need to zero/sign extend ConstantInt phi operands to match 11351 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11352 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11353 if (auto *CI = dyn_cast<ConstantInt>(C)) 11354 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11355 : ISD::ZERO_EXTEND; 11356 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11357 } 11358 Reg = RegOut; 11359 } else { 11360 DenseMap<const Value *, Register>::iterator I = 11361 FuncInfo.ValueMap.find(PHIOp); 11362 if (I != FuncInfo.ValueMap.end()) 11363 Reg = I->second; 11364 else { 11365 assert(isa<AllocaInst>(PHIOp) && 11366 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11367 "Didn't codegen value into a register!??"); 11368 Reg = FuncInfo.CreateRegs(PHIOp); 11369 CopyValueToVirtualRegister(PHIOp, Reg); 11370 } 11371 } 11372 11373 // Remember that this register needs to added to the machine PHI node as 11374 // the input for this MBB. 11375 SmallVector<EVT, 4> ValueVTs; 11376 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11377 for (EVT VT : ValueVTs) { 11378 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11379 for (unsigned i = 0; i != NumRegisters; ++i) 11380 FuncInfo.PHINodesToUpdate.push_back( 11381 std::make_pair(&*MBBI++, Reg + i)); 11382 Reg += NumRegisters; 11383 } 11384 } 11385 } 11386 11387 ConstantsOut.clear(); 11388 } 11389 11390 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11391 MachineFunction::iterator I(MBB); 11392 if (++I == FuncInfo.MF->end()) 11393 return nullptr; 11394 return &*I; 11395 } 11396 11397 /// During lowering new call nodes can be created (such as memset, etc.). 11398 /// Those will become new roots of the current DAG, but complications arise 11399 /// when they are tail calls. In such cases, the call lowering will update 11400 /// the root, but the builder still needs to know that a tail call has been 11401 /// lowered in order to avoid generating an additional return. 11402 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11403 // If the node is null, we do have a tail call. 11404 if (MaybeTC.getNode() != nullptr) 11405 DAG.setRoot(MaybeTC); 11406 else 11407 HasTailCall = true; 11408 } 11409 11410 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11411 MachineBasicBlock *SwitchMBB, 11412 MachineBasicBlock *DefaultMBB) { 11413 MachineFunction *CurMF = FuncInfo.MF; 11414 MachineBasicBlock *NextMBB = nullptr; 11415 MachineFunction::iterator BBI(W.MBB); 11416 if (++BBI != FuncInfo.MF->end()) 11417 NextMBB = &*BBI; 11418 11419 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11420 11421 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11422 11423 if (Size == 2 && W.MBB == SwitchMBB) { 11424 // If any two of the cases has the same destination, and if one value 11425 // is the same as the other, but has one bit unset that the other has set, 11426 // use bit manipulation to do two compares at once. For example: 11427 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11428 // TODO: This could be extended to merge any 2 cases in switches with 3 11429 // cases. 11430 // TODO: Handle cases where W.CaseBB != SwitchBB. 11431 CaseCluster &Small = *W.FirstCluster; 11432 CaseCluster &Big = *W.LastCluster; 11433 11434 if (Small.Low == Small.High && Big.Low == Big.High && 11435 Small.MBB == Big.MBB) { 11436 const APInt &SmallValue = Small.Low->getValue(); 11437 const APInt &BigValue = Big.Low->getValue(); 11438 11439 // Check that there is only one bit different. 11440 APInt CommonBit = BigValue ^ SmallValue; 11441 if (CommonBit.isPowerOf2()) { 11442 SDValue CondLHS = getValue(Cond); 11443 EVT VT = CondLHS.getValueType(); 11444 SDLoc DL = getCurSDLoc(); 11445 11446 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11447 DAG.getConstant(CommonBit, DL, VT)); 11448 SDValue Cond = DAG.getSetCC( 11449 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11450 ISD::SETEQ); 11451 11452 // Update successor info. 11453 // Both Small and Big will jump to Small.BB, so we sum up the 11454 // probabilities. 11455 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11456 if (BPI) 11457 addSuccessorWithProb( 11458 SwitchMBB, DefaultMBB, 11459 // The default destination is the first successor in IR. 11460 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11461 else 11462 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11463 11464 // Insert the true branch. 11465 SDValue BrCond = 11466 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11467 DAG.getBasicBlock(Small.MBB)); 11468 // Insert the false branch. 11469 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11470 DAG.getBasicBlock(DefaultMBB)); 11471 11472 DAG.setRoot(BrCond); 11473 return; 11474 } 11475 } 11476 } 11477 11478 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11479 // Here, we order cases by probability so the most likely case will be 11480 // checked first. However, two clusters can have the same probability in 11481 // which case their relative ordering is non-deterministic. So we use Low 11482 // as a tie-breaker as clusters are guaranteed to never overlap. 11483 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11484 [](const CaseCluster &a, const CaseCluster &b) { 11485 return a.Prob != b.Prob ? 11486 a.Prob > b.Prob : 11487 a.Low->getValue().slt(b.Low->getValue()); 11488 }); 11489 11490 // Rearrange the case blocks so that the last one falls through if possible 11491 // without changing the order of probabilities. 11492 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11493 --I; 11494 if (I->Prob > W.LastCluster->Prob) 11495 break; 11496 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11497 std::swap(*I, *W.LastCluster); 11498 break; 11499 } 11500 } 11501 } 11502 11503 // Compute total probability. 11504 BranchProbability DefaultProb = W.DefaultProb; 11505 BranchProbability UnhandledProbs = DefaultProb; 11506 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11507 UnhandledProbs += I->Prob; 11508 11509 MachineBasicBlock *CurMBB = W.MBB; 11510 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11511 bool FallthroughUnreachable = false; 11512 MachineBasicBlock *Fallthrough; 11513 if (I == W.LastCluster) { 11514 // For the last cluster, fall through to the default destination. 11515 Fallthrough = DefaultMBB; 11516 FallthroughUnreachable = isa<UnreachableInst>( 11517 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11518 } else { 11519 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11520 CurMF->insert(BBI, Fallthrough); 11521 // Put Cond in a virtual register to make it available from the new blocks. 11522 ExportFromCurrentBlock(Cond); 11523 } 11524 UnhandledProbs -= I->Prob; 11525 11526 switch (I->Kind) { 11527 case CC_JumpTable: { 11528 // FIXME: Optimize away range check based on pivot comparisons. 11529 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11530 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11531 11532 // The jump block hasn't been inserted yet; insert it here. 11533 MachineBasicBlock *JumpMBB = JT->MBB; 11534 CurMF->insert(BBI, JumpMBB); 11535 11536 auto JumpProb = I->Prob; 11537 auto FallthroughProb = UnhandledProbs; 11538 11539 // If the default statement is a target of the jump table, we evenly 11540 // distribute the default probability to successors of CurMBB. Also 11541 // update the probability on the edge from JumpMBB to Fallthrough. 11542 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11543 SE = JumpMBB->succ_end(); 11544 SI != SE; ++SI) { 11545 if (*SI == DefaultMBB) { 11546 JumpProb += DefaultProb / 2; 11547 FallthroughProb -= DefaultProb / 2; 11548 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11549 JumpMBB->normalizeSuccProbs(); 11550 break; 11551 } 11552 } 11553 11554 // If the default clause is unreachable, propagate that knowledge into 11555 // JTH->FallthroughUnreachable which will use it to suppress the range 11556 // check. 11557 // 11558 // However, don't do this if we're doing branch target enforcement, 11559 // because a table branch _without_ a range check can be a tempting JOP 11560 // gadget - out-of-bounds inputs that are impossible in correct 11561 // execution become possible again if an attacker can influence the 11562 // control flow. So if an attacker doesn't already have a BTI bypass 11563 // available, we don't want them to be able to get one out of this 11564 // table branch. 11565 if (FallthroughUnreachable) { 11566 Function &CurFunc = CurMF->getFunction(); 11567 bool HasBranchTargetEnforcement = false; 11568 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11569 HasBranchTargetEnforcement = 11570 CurFunc.getFnAttribute("branch-target-enforcement") 11571 .getValueAsBool(); 11572 } else { 11573 HasBranchTargetEnforcement = 11574 CurMF->getMMI().getModule()->getModuleFlag( 11575 "branch-target-enforcement"); 11576 } 11577 if (!HasBranchTargetEnforcement) 11578 JTH->FallthroughUnreachable = true; 11579 } 11580 11581 if (!JTH->FallthroughUnreachable) 11582 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11583 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11584 CurMBB->normalizeSuccProbs(); 11585 11586 // The jump table header will be inserted in our current block, do the 11587 // range check, and fall through to our fallthrough block. 11588 JTH->HeaderBB = CurMBB; 11589 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11590 11591 // If we're in the right place, emit the jump table header right now. 11592 if (CurMBB == SwitchMBB) { 11593 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11594 JTH->Emitted = true; 11595 } 11596 break; 11597 } 11598 case CC_BitTests: { 11599 // FIXME: Optimize away range check based on pivot comparisons. 11600 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11601 11602 // The bit test blocks haven't been inserted yet; insert them here. 11603 for (BitTestCase &BTC : BTB->Cases) 11604 CurMF->insert(BBI, BTC.ThisBB); 11605 11606 // Fill in fields of the BitTestBlock. 11607 BTB->Parent = CurMBB; 11608 BTB->Default = Fallthrough; 11609 11610 BTB->DefaultProb = UnhandledProbs; 11611 // If the cases in bit test don't form a contiguous range, we evenly 11612 // distribute the probability on the edge to Fallthrough to two 11613 // successors of CurMBB. 11614 if (!BTB->ContiguousRange) { 11615 BTB->Prob += DefaultProb / 2; 11616 BTB->DefaultProb -= DefaultProb / 2; 11617 } 11618 11619 if (FallthroughUnreachable) 11620 BTB->FallthroughUnreachable = true; 11621 11622 // If we're in the right place, emit the bit test header right now. 11623 if (CurMBB == SwitchMBB) { 11624 visitBitTestHeader(*BTB, SwitchMBB); 11625 BTB->Emitted = true; 11626 } 11627 break; 11628 } 11629 case CC_Range: { 11630 const Value *RHS, *LHS, *MHS; 11631 ISD::CondCode CC; 11632 if (I->Low == I->High) { 11633 // Check Cond == I->Low. 11634 CC = ISD::SETEQ; 11635 LHS = Cond; 11636 RHS=I->Low; 11637 MHS = nullptr; 11638 } else { 11639 // Check I->Low <= Cond <= I->High. 11640 CC = ISD::SETLE; 11641 LHS = I->Low; 11642 MHS = Cond; 11643 RHS = I->High; 11644 } 11645 11646 // If Fallthrough is unreachable, fold away the comparison. 11647 if (FallthroughUnreachable) 11648 CC = ISD::SETTRUE; 11649 11650 // The false probability is the sum of all unhandled cases. 11651 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11652 getCurSDLoc(), I->Prob, UnhandledProbs); 11653 11654 if (CurMBB == SwitchMBB) 11655 visitSwitchCase(CB, SwitchMBB); 11656 else 11657 SL->SwitchCases.push_back(CB); 11658 11659 break; 11660 } 11661 } 11662 CurMBB = Fallthrough; 11663 } 11664 } 11665 11666 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11667 const SwitchWorkListItem &W, 11668 Value *Cond, 11669 MachineBasicBlock *SwitchMBB) { 11670 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11671 "Clusters not sorted?"); 11672 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11673 11674 auto [LastLeft, FirstRight, LeftProb, RightProb] = 11675 SL->computeSplitWorkItemInfo(W); 11676 11677 // Use the first element on the right as pivot since we will make less-than 11678 // comparisons against it. 11679 CaseClusterIt PivotCluster = FirstRight; 11680 assert(PivotCluster > W.FirstCluster); 11681 assert(PivotCluster <= W.LastCluster); 11682 11683 CaseClusterIt FirstLeft = W.FirstCluster; 11684 CaseClusterIt LastRight = W.LastCluster; 11685 11686 const ConstantInt *Pivot = PivotCluster->Low; 11687 11688 // New blocks will be inserted immediately after the current one. 11689 MachineFunction::iterator BBI(W.MBB); 11690 ++BBI; 11691 11692 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11693 // we can branch to its destination directly if it's squeezed exactly in 11694 // between the known lower bound and Pivot - 1. 11695 MachineBasicBlock *LeftMBB; 11696 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11697 FirstLeft->Low == W.GE && 11698 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11699 LeftMBB = FirstLeft->MBB; 11700 } else { 11701 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11702 FuncInfo.MF->insert(BBI, LeftMBB); 11703 WorkList.push_back( 11704 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11705 // Put Cond in a virtual register to make it available from the new blocks. 11706 ExportFromCurrentBlock(Cond); 11707 } 11708 11709 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11710 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11711 // directly if RHS.High equals the current upper bound. 11712 MachineBasicBlock *RightMBB; 11713 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11714 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11715 RightMBB = FirstRight->MBB; 11716 } else { 11717 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11718 FuncInfo.MF->insert(BBI, RightMBB); 11719 WorkList.push_back( 11720 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11721 // Put Cond in a virtual register to make it available from the new blocks. 11722 ExportFromCurrentBlock(Cond); 11723 } 11724 11725 // Create the CaseBlock record that will be used to lower the branch. 11726 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11727 getCurSDLoc(), LeftProb, RightProb); 11728 11729 if (W.MBB == SwitchMBB) 11730 visitSwitchCase(CB, SwitchMBB); 11731 else 11732 SL->SwitchCases.push_back(CB); 11733 } 11734 11735 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11736 // from the swith statement. 11737 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11738 BranchProbability PeeledCaseProb) { 11739 if (PeeledCaseProb == BranchProbability::getOne()) 11740 return BranchProbability::getZero(); 11741 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11742 11743 uint32_t Numerator = CaseProb.getNumerator(); 11744 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11745 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11746 } 11747 11748 // Try to peel the top probability case if it exceeds the threshold. 11749 // Return current MachineBasicBlock for the switch statement if the peeling 11750 // does not occur. 11751 // If the peeling is performed, return the newly created MachineBasicBlock 11752 // for the peeled switch statement. Also update Clusters to remove the peeled 11753 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11754 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11755 const SwitchInst &SI, CaseClusterVector &Clusters, 11756 BranchProbability &PeeledCaseProb) { 11757 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11758 // Don't perform if there is only one cluster or optimizing for size. 11759 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11760 TM.getOptLevel() == CodeGenOptLevel::None || 11761 SwitchMBB->getParent()->getFunction().hasMinSize()) 11762 return SwitchMBB; 11763 11764 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11765 unsigned PeeledCaseIndex = 0; 11766 bool SwitchPeeled = false; 11767 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11768 CaseCluster &CC = Clusters[Index]; 11769 if (CC.Prob < TopCaseProb) 11770 continue; 11771 TopCaseProb = CC.Prob; 11772 PeeledCaseIndex = Index; 11773 SwitchPeeled = true; 11774 } 11775 if (!SwitchPeeled) 11776 return SwitchMBB; 11777 11778 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11779 << TopCaseProb << "\n"); 11780 11781 // Record the MBB for the peeled switch statement. 11782 MachineFunction::iterator BBI(SwitchMBB); 11783 ++BBI; 11784 MachineBasicBlock *PeeledSwitchMBB = 11785 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11786 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11787 11788 ExportFromCurrentBlock(SI.getCondition()); 11789 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11790 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11791 nullptr, nullptr, TopCaseProb.getCompl()}; 11792 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11793 11794 Clusters.erase(PeeledCaseIt); 11795 for (CaseCluster &CC : Clusters) { 11796 LLVM_DEBUG( 11797 dbgs() << "Scale the probablity for one cluster, before scaling: " 11798 << CC.Prob << "\n"); 11799 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11800 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11801 } 11802 PeeledCaseProb = TopCaseProb; 11803 return PeeledSwitchMBB; 11804 } 11805 11806 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11807 // Extract cases from the switch. 11808 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11809 CaseClusterVector Clusters; 11810 Clusters.reserve(SI.getNumCases()); 11811 for (auto I : SI.cases()) { 11812 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11813 const ConstantInt *CaseVal = I.getCaseValue(); 11814 BranchProbability Prob = 11815 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11816 : BranchProbability(1, SI.getNumCases() + 1); 11817 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11818 } 11819 11820 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11821 11822 // Cluster adjacent cases with the same destination. We do this at all 11823 // optimization levels because it's cheap to do and will make codegen faster 11824 // if there are many clusters. 11825 sortAndRangeify(Clusters); 11826 11827 // The branch probablity of the peeled case. 11828 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11829 MachineBasicBlock *PeeledSwitchMBB = 11830 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11831 11832 // If there is only the default destination, jump there directly. 11833 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11834 if (Clusters.empty()) { 11835 assert(PeeledSwitchMBB == SwitchMBB); 11836 SwitchMBB->addSuccessor(DefaultMBB); 11837 if (DefaultMBB != NextBlock(SwitchMBB)) { 11838 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11839 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11840 } 11841 return; 11842 } 11843 11844 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 11845 DAG.getBFI()); 11846 SL->findBitTestClusters(Clusters, &SI); 11847 11848 LLVM_DEBUG({ 11849 dbgs() << "Case clusters: "; 11850 for (const CaseCluster &C : Clusters) { 11851 if (C.Kind == CC_JumpTable) 11852 dbgs() << "JT:"; 11853 if (C.Kind == CC_BitTests) 11854 dbgs() << "BT:"; 11855 11856 C.Low->getValue().print(dbgs(), true); 11857 if (C.Low != C.High) { 11858 dbgs() << '-'; 11859 C.High->getValue().print(dbgs(), true); 11860 } 11861 dbgs() << ' '; 11862 } 11863 dbgs() << '\n'; 11864 }); 11865 11866 assert(!Clusters.empty()); 11867 SwitchWorkList WorkList; 11868 CaseClusterIt First = Clusters.begin(); 11869 CaseClusterIt Last = Clusters.end() - 1; 11870 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11871 // Scale the branchprobability for DefaultMBB if the peel occurs and 11872 // DefaultMBB is not replaced. 11873 if (PeeledCaseProb != BranchProbability::getZero() && 11874 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11875 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11876 WorkList.push_back( 11877 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11878 11879 while (!WorkList.empty()) { 11880 SwitchWorkListItem W = WorkList.pop_back_val(); 11881 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11882 11883 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 11884 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11885 // For optimized builds, lower large range as a balanced binary tree. 11886 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11887 continue; 11888 } 11889 11890 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11891 } 11892 } 11893 11894 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11896 auto DL = getCurSDLoc(); 11897 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11898 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11899 } 11900 11901 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11903 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11904 11905 SDLoc DL = getCurSDLoc(); 11906 SDValue V = getValue(I.getOperand(0)); 11907 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11908 11909 if (VT.isScalableVector()) { 11910 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11911 return; 11912 } 11913 11914 // Use VECTOR_SHUFFLE for the fixed-length vector 11915 // to maintain existing behavior. 11916 SmallVector<int, 8> Mask; 11917 unsigned NumElts = VT.getVectorMinNumElements(); 11918 for (unsigned i = 0; i != NumElts; ++i) 11919 Mask.push_back(NumElts - 1 - i); 11920 11921 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11922 } 11923 11924 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11925 auto DL = getCurSDLoc(); 11926 SDValue InVec = getValue(I.getOperand(0)); 11927 EVT OutVT = 11928 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11929 11930 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11931 11932 // ISD Node needs the input vectors split into two equal parts 11933 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11934 DAG.getVectorIdxConstant(0, DL)); 11935 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11936 DAG.getVectorIdxConstant(OutNumElts, DL)); 11937 11938 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11939 // legalisation and combines. 11940 if (OutVT.isFixedLengthVector()) { 11941 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11942 createStrideMask(0, 2, OutNumElts)); 11943 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11944 createStrideMask(1, 2, OutNumElts)); 11945 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11946 setValue(&I, Res); 11947 return; 11948 } 11949 11950 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11951 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11952 setValue(&I, Res); 11953 } 11954 11955 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11956 auto DL = getCurSDLoc(); 11957 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11958 SDValue InVec0 = getValue(I.getOperand(0)); 11959 SDValue InVec1 = getValue(I.getOperand(1)); 11960 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11961 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11962 11963 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11964 // legalisation and combines. 11965 if (OutVT.isFixedLengthVector()) { 11966 unsigned NumElts = InVT.getVectorMinNumElements(); 11967 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11968 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11969 createInterleaveMask(NumElts, 2))); 11970 return; 11971 } 11972 11973 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11974 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11975 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11976 Res.getValue(1)); 11977 setValue(&I, Res); 11978 } 11979 11980 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11981 SmallVector<EVT, 4> ValueVTs; 11982 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11983 ValueVTs); 11984 unsigned NumValues = ValueVTs.size(); 11985 if (NumValues == 0) return; 11986 11987 SmallVector<SDValue, 4> Values(NumValues); 11988 SDValue Op = getValue(I.getOperand(0)); 11989 11990 for (unsigned i = 0; i != NumValues; ++i) 11991 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11992 SDValue(Op.getNode(), Op.getResNo() + i)); 11993 11994 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11995 DAG.getVTList(ValueVTs), Values)); 11996 } 11997 11998 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11999 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12000 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12001 12002 SDLoc DL = getCurSDLoc(); 12003 SDValue V1 = getValue(I.getOperand(0)); 12004 SDValue V2 = getValue(I.getOperand(1)); 12005 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12006 12007 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12008 if (VT.isScalableVector()) { 12009 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12010 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12011 DAG.getConstant(Imm, DL, IdxVT))); 12012 return; 12013 } 12014 12015 unsigned NumElts = VT.getVectorNumElements(); 12016 12017 uint64_t Idx = (NumElts + Imm) % NumElts; 12018 12019 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12020 SmallVector<int, 8> Mask; 12021 for (unsigned i = 0; i < NumElts; ++i) 12022 Mask.push_back(Idx + i); 12023 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12024 } 12025 12026 // Consider the following MIR after SelectionDAG, which produces output in 12027 // phyregs in the first case or virtregs in the second case. 12028 // 12029 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12030 // %5:gr32 = COPY $ebx 12031 // %6:gr32 = COPY $edx 12032 // %1:gr32 = COPY %6:gr32 12033 // %0:gr32 = COPY %5:gr32 12034 // 12035 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12036 // %1:gr32 = COPY %6:gr32 12037 // %0:gr32 = COPY %5:gr32 12038 // 12039 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12040 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12041 // 12042 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12043 // to a single virtreg (such as %0). The remaining outputs monotonically 12044 // increase in virtreg number from there. If a callbr has no outputs, then it 12045 // should not have a corresponding callbr landingpad; in fact, the callbr 12046 // landingpad would not even be able to refer to such a callbr. 12047 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12048 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12049 // There is definitely at least one copy. 12050 assert(MI->getOpcode() == TargetOpcode::COPY && 12051 "start of copy chain MUST be COPY"); 12052 Reg = MI->getOperand(1).getReg(); 12053 MI = MRI.def_begin(Reg)->getParent(); 12054 // There may be an optional second copy. 12055 if (MI->getOpcode() == TargetOpcode::COPY) { 12056 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12057 Reg = MI->getOperand(1).getReg(); 12058 assert(Reg.isPhysical() && "expected COPY of physical register"); 12059 MI = MRI.def_begin(Reg)->getParent(); 12060 } 12061 // The start of the chain must be an INLINEASM_BR. 12062 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12063 "end of copy chain MUST be INLINEASM_BR"); 12064 return Reg; 12065 } 12066 12067 // We must do this walk rather than the simpler 12068 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12069 // otherwise we will end up with copies of virtregs only valid along direct 12070 // edges. 12071 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12072 SmallVector<EVT, 8> ResultVTs; 12073 SmallVector<SDValue, 8> ResultValues; 12074 const auto *CBR = 12075 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12076 12077 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12078 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12079 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12080 12081 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12082 SDValue Chain = DAG.getRoot(); 12083 12084 // Re-parse the asm constraints string. 12085 TargetLowering::AsmOperandInfoVector TargetConstraints = 12086 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12087 for (auto &T : TargetConstraints) { 12088 SDISelAsmOperandInfo OpInfo(T); 12089 if (OpInfo.Type != InlineAsm::isOutput) 12090 continue; 12091 12092 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12093 // individual constraint. 12094 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12095 12096 switch (OpInfo.ConstraintType) { 12097 case TargetLowering::C_Register: 12098 case TargetLowering::C_RegisterClass: { 12099 // Fill in OpInfo.AssignedRegs.Regs. 12100 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12101 12102 // getRegistersForValue may produce 1 to many registers based on whether 12103 // the OpInfo.ConstraintVT is legal on the target or not. 12104 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12105 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12106 if (Register::isPhysicalRegister(OriginalDef)) 12107 FuncInfo.MBB->addLiveIn(OriginalDef); 12108 // Update the assigned registers to use the original defs. 12109 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12110 } 12111 12112 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12113 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12114 ResultValues.push_back(V); 12115 ResultVTs.push_back(OpInfo.ConstraintVT); 12116 break; 12117 } 12118 case TargetLowering::C_Other: { 12119 SDValue Flag; 12120 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12121 OpInfo, DAG); 12122 ++InitialDef; 12123 ResultValues.push_back(V); 12124 ResultVTs.push_back(OpInfo.ConstraintVT); 12125 break; 12126 } 12127 default: 12128 break; 12129 } 12130 } 12131 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12132 DAG.getVTList(ResultVTs), ResultValues); 12133 setValue(&I, V); 12134 } 12135