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/TargetTransformInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/Analysis/VectorUtils.h" 32 #include "llvm/CodeGen/Analysis.h" 33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 34 #include "llvm/CodeGen/CodeGenCommonISel.h" 35 #include "llvm/CodeGen/FunctionLoweringInfo.h" 36 #include "llvm/CodeGen/GCMetadata.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstrBuilder.h" 42 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 43 #include "llvm/CodeGen/MachineMemOperand.h" 44 #include "llvm/CodeGen/MachineModuleInfo.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachineRegisterInfo.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/MemoryModelRelaxationAnnotations.h" 83 #include "llvm/IR/Metadata.h" 84 #include "llvm/IR/Module.h" 85 #include "llvm/IR/Operator.h" 86 #include "llvm/IR/PatternMatch.h" 87 #include "llvm/IR/Statepoint.h" 88 #include "llvm/IR/Type.h" 89 #include "llvm/IR/User.h" 90 #include "llvm/IR/Value.h" 91 #include "llvm/MC/MCContext.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/InstructionCost.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/raw_ostream.h" 100 #include "llvm/Target/TargetIntrinsicInfo.h" 101 #include "llvm/Target/TargetMachine.h" 102 #include "llvm/Target/TargetOptions.h" 103 #include "llvm/TargetParser/Triple.h" 104 #include "llvm/Transforms/Utils/Local.h" 105 #include <cstddef> 106 #include <limits> 107 #include <optional> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 SDValue InChain, 158 std::optional<CallingConv::ID> CC); 159 160 /// getCopyFromParts - Create a value that contains the specified legal parts 161 /// combined into the value they represent. If the parts combine to a type 162 /// larger than ValueVT then AssertOp can be used to specify whether the extra 163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 164 /// (ISD::AssertSext). 165 static SDValue 166 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 168 SDValue InChain, 169 std::optional<CallingConv::ID> CC = std::nullopt, 170 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 171 // Let the target assemble the parts if it wants to 172 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 174 PartVT, ValueVT, CC)) 175 return Val; 176 177 if (ValueVT.isVector()) 178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 179 InChain, CC); 180 181 assert(NumParts > 0 && "No parts to assemble!"); 182 SDValue Val = Parts[0]; 183 184 if (NumParts > 1) { 185 // Assemble the value from multiple parts. 186 if (ValueVT.isInteger()) { 187 unsigned PartBits = PartVT.getSizeInBits(); 188 unsigned ValueBits = ValueVT.getSizeInBits(); 189 190 // Assemble the power of 2 part. 191 unsigned RoundParts = llvm::bit_floor(NumParts); 192 unsigned RoundBits = PartBits * RoundParts; 193 EVT RoundVT = RoundBits == ValueBits ? 194 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 195 SDValue Lo, Hi; 196 197 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 198 199 if (RoundParts > 2) { 200 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 201 InChain); 202 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 203 PartVT, HalfVT, V, InChain); 204 } else { 205 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 206 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 207 } 208 209 if (DAG.getDataLayout().isBigEndian()) 210 std::swap(Lo, Hi); 211 212 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 213 214 if (RoundParts < NumParts) { 215 // Assemble the trailing non-power-of-2 part. 216 unsigned OddParts = NumParts - RoundParts; 217 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 218 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 219 OddVT, V, InChain, CC); 220 221 // Combine the round and odd parts. 222 Lo = Val; 223 if (DAG.getDataLayout().isBigEndian()) 224 std::swap(Lo, Hi); 225 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 226 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 227 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getShiftAmountTy( 230 TotalVT, DAG.getDataLayout()))); 231 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 232 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 233 } 234 } else if (PartVT.isFloatingPoint()) { 235 // FP split into multiple FP parts (for ppcf128) 236 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 237 "Unexpected split"); 238 SDValue Lo, Hi; 239 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 241 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 242 std::swap(Lo, Hi); 243 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 244 } else { 245 // FP split into integer parts (soft fp) 246 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 247 !PartVT.isVector() && "Unexpected split"); 248 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 249 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 250 InChain, CC); 251 } 252 } 253 254 // There is now one part, held in Val. Correct it to match ValueVT. 255 // PartEVT is the type of the register class that holds the value. 256 // ValueVT is the type of the inline asm operation. 257 EVT PartEVT = Val.getValueType(); 258 259 if (PartEVT == ValueVT) 260 return Val; 261 262 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 263 ValueVT.bitsLT(PartEVT)) { 264 // For an FP value in an integer part, we need to truncate to the right 265 // width first. 266 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 267 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 268 } 269 270 // Handle types that have the same size. 271 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 272 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 273 274 // Handle types with different sizes. 275 if (PartEVT.isInteger() && ValueVT.isInteger()) { 276 if (ValueVT.bitsLT(PartEVT)) { 277 // For a truncate, see if we have any information to 278 // indicate whether the truncated bits will always be 279 // zero or sign-extension. 280 if (AssertOp) 281 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 282 DAG.getValueType(ValueVT)); 283 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 284 } 285 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 286 } 287 288 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 289 // FP_ROUND's are always exact here. 290 if (ValueVT.bitsLT(Val.getValueType())) { 291 292 SDValue NoChange = 293 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 294 295 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 296 llvm::Attribute::StrictFP)) { 297 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 298 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 299 NoChange); 300 } 301 302 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 303 } 304 305 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 306 } 307 308 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 309 // then truncating. 310 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 311 ValueVT.bitsLT(PartEVT)) { 312 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 313 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 314 } 315 316 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 317 } 318 319 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 320 const Twine &ErrMsg) { 321 const Instruction *I = dyn_cast_or_null<Instruction>(V); 322 if (!V) 323 return Ctx.emitError(ErrMsg); 324 325 const char *AsmError = ", possible invalid constraint for vector type"; 326 if (const CallInst *CI = dyn_cast<CallInst>(I)) 327 if (CI->isInlineAsm()) 328 return Ctx.emitError(I, ErrMsg + AsmError); 329 330 return Ctx.emitError(I, ErrMsg); 331 } 332 333 /// getCopyFromPartsVector - Create a value that contains the specified legal 334 /// parts combined into the value they represent. If the parts combine to a 335 /// type larger than ValueVT then AssertOp can be used to specify whether the 336 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 337 /// ValueVT (ISD::AssertSext). 338 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 339 const SDValue *Parts, unsigned NumParts, 340 MVT PartVT, EVT ValueVT, const Value *V, 341 SDValue InChain, 342 std::optional<CallingConv::ID> CallConv) { 343 assert(ValueVT.isVector() && "Not a vector value"); 344 assert(NumParts > 0 && "No parts to assemble!"); 345 const bool IsABIRegCopy = CallConv.has_value(); 346 347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 348 SDValue Val = Parts[0]; 349 350 // Handle a multi-element vector. 351 if (NumParts > 1) { 352 EVT IntermediateVT; 353 MVT RegisterVT; 354 unsigned NumIntermediates; 355 unsigned NumRegs; 356 357 if (IsABIRegCopy) { 358 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 359 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 360 NumIntermediates, RegisterVT); 361 } else { 362 NumRegs = 363 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 364 NumIntermediates, RegisterVT); 365 } 366 367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 368 NumParts = NumRegs; // Silence a compiler warning. 369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 370 assert(RegisterVT.getSizeInBits() == 371 Parts[0].getSimpleValueType().getSizeInBits() && 372 "Part type sizes don't match!"); 373 374 // Assemble the parts into intermediate operands. 375 SmallVector<SDValue, 8> Ops(NumIntermediates); 376 if (NumIntermediates == NumParts) { 377 // If the register was not expanded, truncate or copy the value, 378 // as appropriate. 379 for (unsigned i = 0; i != NumParts; ++i) 380 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 381 V, InChain, CallConv); 382 } else if (NumParts > 0) { 383 // If the intermediate type was expanded, build the intermediate 384 // operands from the parts. 385 assert(NumParts % NumIntermediates == 0 && 386 "Must expand into a divisible number of parts!"); 387 unsigned Factor = NumParts / NumIntermediates; 388 for (unsigned i = 0; i != NumIntermediates; ++i) 389 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 390 IntermediateVT, V, InChain, CallConv); 391 } 392 393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 394 // intermediate operands. 395 EVT BuiltVectorTy = 396 IntermediateVT.isVector() 397 ? EVT::getVectorVT( 398 *DAG.getContext(), IntermediateVT.getScalarType(), 399 IntermediateVT.getVectorElementCount() * NumParts) 400 : EVT::getVectorVT(*DAG.getContext(), 401 IntermediateVT.getScalarType(), 402 NumIntermediates); 403 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 404 : ISD::BUILD_VECTOR, 405 DL, BuiltVectorTy, Ops); 406 } 407 408 // There is now one part, held in Val. Correct it to match ValueVT. 409 EVT PartEVT = Val.getValueType(); 410 411 if (PartEVT == ValueVT) 412 return Val; 413 414 if (PartEVT.isVector()) { 415 // Vector/Vector bitcast. 416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 417 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 418 419 // If the parts vector has more elements than the value vector, then we 420 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 421 // Extract the elements we want. 422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 423 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 424 ValueVT.getVectorElementCount().getKnownMinValue()) && 425 (PartEVT.getVectorElementCount().isScalable() == 426 ValueVT.getVectorElementCount().isScalable()) && 427 "Cannot narrow, it would be a lossy transformation"); 428 PartEVT = 429 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 430 ValueVT.getVectorElementCount()); 431 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 432 DAG.getVectorIdxConstant(0, DL)); 433 if (PartEVT == ValueVT) 434 return Val; 435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 440 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 441 } 442 443 // Promoted vector extract 444 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 445 } 446 447 // Trivial bitcast if the types are the same size and the destination 448 // vector type is legal. 449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 450 TLI.isTypeLegal(ValueVT)) 451 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 452 453 if (ValueVT.getVectorNumElements() != 1) { 454 // Certain ABIs require that vectors are passed as integers. For vectors 455 // are the same size, this is an obvious bitcast. 456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 458 } else if (ValueVT.bitsLT(PartEVT)) { 459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 461 // Drop the extra bits. 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 return DAG.getBitcast(ValueVT, Val); 464 } 465 466 diagnosePossiblyInvalidConstraint( 467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 468 return DAG.getUNDEF(ValueVT); 469 } 470 471 // Handle cases such as i8 -> <1 x i1> 472 EVT ValueSVT = ValueVT.getVectorElementType(); 473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 474 unsigned ValueSize = ValueSVT.getSizeInBits(); 475 if (ValueSize == PartEVT.getSizeInBits()) { 476 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 478 // It's possible a scalar floating point type gets softened to integer and 479 // then promoted to a larger integer. If PartEVT is the larger integer 480 // we need to truncate it and then bitcast to the FP type. 481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 482 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 483 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 484 Val = DAG.getBitcast(ValueSVT, Val); 485 } else { 486 Val = ValueVT.isFloatingPoint() 487 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 488 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 489 } 490 } 491 492 return DAG.getBuildVector(ValueVT, DL, Val); 493 } 494 495 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 496 SDValue Val, SDValue *Parts, unsigned NumParts, 497 MVT PartVT, const Value *V, 498 std::optional<CallingConv::ID> CallConv); 499 500 /// getCopyToParts - Create a series of nodes that contain the specified value 501 /// split into legal parts. If the parts contain more bits than Val, then, for 502 /// integers, ExtendKind can be used to specify how to generate the extra bits. 503 static void 504 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 505 unsigned NumParts, MVT PartVT, const Value *V, 506 std::optional<CallingConv::ID> CallConv = std::nullopt, 507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 508 // Let the target split the parts if it wants to 509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 511 CallConv)) 512 return; 513 EVT ValueVT = Val.getValueType(); 514 515 // Handle the vector case separately. 516 if (ValueVT.isVector()) 517 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 518 CallConv); 519 520 unsigned OrigNumParts = NumParts; 521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 522 "Copying to an illegal type!"); 523 524 if (NumParts == 0) 525 return; 526 527 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 528 EVT PartEVT = PartVT; 529 if (PartEVT == ValueVT) { 530 assert(NumParts == 1 && "No-op copy with multiple parts!"); 531 Parts[0] = Val; 532 return; 533 } 534 535 unsigned PartBits = PartVT.getSizeInBits(); 536 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 537 // If the parts cover more bits than the value has, promote the value. 538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 539 assert(NumParts == 1 && "Do not know what to promote to!"); 540 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 541 } else { 542 if (ValueVT.isFloatingPoint()) { 543 // FP values need to be bitcast, then extended if they are being put 544 // into a larger container. 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 546 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 547 } 548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 549 ValueVT.isInteger() && 550 "Unknown mismatch!"); 551 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 552 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 553 if (PartVT == MVT::x86mmx) 554 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 555 } 556 } else if (PartBits == ValueVT.getSizeInBits()) { 557 // Different types of the same size. 558 assert(NumParts == 1 && PartEVT != ValueVT); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 561 // If the parts cover less bits than value has, truncate the value. 562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 563 ValueVT.isInteger() && 564 "Unknown mismatch!"); 565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 566 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 567 if (PartVT == MVT::x86mmx) 568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 569 } 570 571 // The value may have changed - recompute ValueVT. 572 ValueVT = Val.getValueType(); 573 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 574 "Failed to tile the value with PartVT!"); 575 576 if (NumParts == 1) { 577 if (PartEVT != ValueVT) { 578 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 579 "scalar-to-vector conversion failed"); 580 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 581 } 582 583 Parts[0] = Val; 584 return; 585 } 586 587 // Expand the value into multiple parts. 588 if (NumParts & (NumParts - 1)) { 589 // The number of parts is not a power of 2. Split off and copy the tail. 590 assert(PartVT.isInteger() && ValueVT.isInteger() && 591 "Do not know what to expand to!"); 592 unsigned RoundParts = llvm::bit_floor(NumParts); 593 unsigned RoundBits = RoundParts * PartBits; 594 unsigned OddParts = NumParts - RoundParts; 595 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 596 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 597 598 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 599 CallConv); 600 601 if (DAG.getDataLayout().isBigEndian()) 602 // The odd parts were reversed by getCopyToParts - unreverse them. 603 std::reverse(Parts + RoundParts, Parts + NumParts); 604 605 NumParts = RoundParts; 606 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 608 } 609 610 // The number of parts is a power of 2. Repeatedly bisect the value using 611 // EXTRACT_ELEMENT. 612 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 613 EVT::getIntegerVT(*DAG.getContext(), 614 ValueVT.getSizeInBits()), 615 Val); 616 617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 618 for (unsigned i = 0; i < NumParts; i += StepSize) { 619 unsigned ThisBits = StepSize * PartBits / 2; 620 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 621 SDValue &Part0 = Parts[i]; 622 SDValue &Part1 = Parts[i+StepSize/2]; 623 624 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 625 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 626 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 627 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 628 629 if (ThisBits == PartBits && ThisVT != PartVT) { 630 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 631 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 632 } 633 } 634 } 635 636 if (DAG.getDataLayout().isBigEndian()) 637 std::reverse(Parts, Parts + OrigNumParts); 638 } 639 640 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 641 const SDLoc &DL, EVT PartVT) { 642 if (!PartVT.isVector()) 643 return SDValue(); 644 645 EVT ValueVT = Val.getValueType(); 646 EVT PartEVT = PartVT.getVectorElementType(); 647 EVT ValueEVT = ValueVT.getVectorElementType(); 648 ElementCount PartNumElts = PartVT.getVectorElementCount(); 649 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 650 651 // We only support widening vectors with equivalent element types and 652 // fixed/scalable properties. If a target needs to widen a fixed-length type 653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 654 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 655 PartNumElts.isScalable() != ValueNumElts.isScalable()) 656 return SDValue(); 657 658 // Have a try for bf16 because some targets share its ABI with fp16. 659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 660 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 661 "Cannot widen to illegal type"); 662 Val = DAG.getNode(ISD::BITCAST, DL, 663 ValueVT.changeVectorElementType(MVT::f16), Val); 664 } else if (PartEVT != ValueEVT) { 665 return SDValue(); 666 } 667 668 // Widening a scalable vector to another scalable vector is done by inserting 669 // the vector into a larger undef one. 670 if (PartNumElts.isScalable()) 671 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 672 Val, DAG.getVectorIdxConstant(0, DL)); 673 674 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 675 // undef elements. 676 SmallVector<SDValue, 16> Ops; 677 DAG.ExtractVectorElements(Val, Ops); 678 SDValue EltUndef = DAG.getUNDEF(PartEVT); 679 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 680 681 // FIXME: Use CONCAT for 2x -> 4x. 682 return DAG.getBuildVector(PartVT, DL, Ops); 683 } 684 685 /// getCopyToPartsVector - Create a series of nodes that contain the specified 686 /// value split into legal parts. 687 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 688 SDValue Val, SDValue *Parts, unsigned NumParts, 689 MVT PartVT, const Value *V, 690 std::optional<CallingConv::ID> CallConv) { 691 EVT ValueVT = Val.getValueType(); 692 assert(ValueVT.isVector() && "Not a vector"); 693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 694 const bool IsABIRegCopy = CallConv.has_value(); 695 696 if (NumParts == 1) { 697 EVT PartEVT = PartVT; 698 if (PartEVT == ValueVT) { 699 // Nothing to do. 700 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 701 // Bitconvert vector->vector case. 702 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 703 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 704 Val = Widened; 705 } else if (PartVT.isVector() && 706 PartEVT.getVectorElementType().bitsGE( 707 ValueVT.getVectorElementType()) && 708 PartEVT.getVectorElementCount() == 709 ValueVT.getVectorElementCount()) { 710 711 // Promoted vector extract 712 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 713 } else if (PartEVT.isVector() && 714 PartEVT.getVectorElementType() != 715 ValueVT.getVectorElementType() && 716 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 717 TargetLowering::TypeWidenVector) { 718 // Combination of widening and promotion. 719 EVT WidenVT = 720 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 721 PartVT.getVectorElementCount()); 722 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 723 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 724 } else { 725 // Don't extract an integer from a float vector. This can happen if the 726 // FP type gets softened to integer and then promoted. The promotion 727 // prevents it from being picked up by the earlier bitcast case. 728 if (ValueVT.getVectorElementCount().isScalar() && 729 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 730 // If we reach this condition and PartVT is FP, this means that 731 // ValueVT is also FP and both have a different size, otherwise we 732 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here 733 // would be invalid since that would mean the smaller FP type has to 734 // be extended to the larger one. 735 if (PartVT.isFloatingPoint()) { 736 Val = DAG.getBitcast(ValueVT.getScalarType(), Val); 737 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 738 } else 739 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 740 DAG.getVectorIdxConstant(0, DL)); 741 } else { 742 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 743 assert(PartVT.getFixedSizeInBits() > ValueSize && 744 "lossy conversion of vector to scalar type"); 745 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 746 Val = DAG.getBitcast(IntermediateType, Val); 747 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 748 } 749 } 750 751 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 752 Parts[0] = Val; 753 return; 754 } 755 756 // Handle a multi-element vector. 757 EVT IntermediateVT; 758 MVT RegisterVT; 759 unsigned NumIntermediates; 760 unsigned NumRegs; 761 if (IsABIRegCopy) { 762 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 763 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 764 RegisterVT); 765 } else { 766 NumRegs = 767 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 768 NumIntermediates, RegisterVT); 769 } 770 771 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 772 NumParts = NumRegs; // Silence a compiler warning. 773 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 774 775 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 776 "Mixing scalable and fixed vectors when copying in parts"); 777 778 std::optional<ElementCount> DestEltCnt; 779 780 if (IntermediateVT.isVector()) 781 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 782 else 783 DestEltCnt = ElementCount::getFixed(NumIntermediates); 784 785 EVT BuiltVectorTy = EVT::getVectorVT( 786 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 787 788 if (ValueVT == BuiltVectorTy) { 789 // Nothing to do. 790 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 791 // Bitconvert vector->vector case. 792 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 793 } else { 794 if (BuiltVectorTy.getVectorElementType().bitsGT( 795 ValueVT.getVectorElementType())) { 796 // Integer promotion. 797 ValueVT = EVT::getVectorVT(*DAG.getContext(), 798 BuiltVectorTy.getVectorElementType(), 799 ValueVT.getVectorElementCount()); 800 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 801 } 802 803 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 804 Val = Widened; 805 } 806 } 807 808 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 809 810 // Split the vector into intermediate operands. 811 SmallVector<SDValue, 8> Ops(NumIntermediates); 812 for (unsigned i = 0; i != NumIntermediates; ++i) { 813 if (IntermediateVT.isVector()) { 814 // This does something sensible for scalable vectors - see the 815 // definition of EXTRACT_SUBVECTOR for further details. 816 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 817 Ops[i] = 818 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 819 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 820 } else { 821 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 822 DAG.getVectorIdxConstant(i, DL)); 823 } 824 } 825 826 // Split the intermediate operands into legal parts. 827 if (NumParts == NumIntermediates) { 828 // If the register was not expanded, promote or copy the value, 829 // as appropriate. 830 for (unsigned i = 0; i != NumParts; ++i) 831 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 832 } else if (NumParts > 0) { 833 // If the intermediate type was expanded, split each the value into 834 // legal parts. 835 assert(NumIntermediates != 0 && "division by zero"); 836 assert(NumParts % NumIntermediates == 0 && 837 "Must expand into a divisible number of parts!"); 838 unsigned Factor = NumParts / NumIntermediates; 839 for (unsigned i = 0; i != NumIntermediates; ++i) 840 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 841 CallConv); 842 } 843 } 844 845 RegsForValue::RegsForValue(const SmallVector<Register, 4> ®s, MVT regvt, 846 EVT valuevt, std::optional<CallingConv::ID> CC) 847 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 848 RegCount(1, regs.size()), CallConv(CC) {} 849 850 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 851 const DataLayout &DL, Register Reg, Type *Ty, 852 std::optional<CallingConv::ID> CC) { 853 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 854 855 CallConv = CC; 856 857 for (EVT ValueVT : ValueVTs) { 858 unsigned NumRegs = 859 isABIMangled() 860 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 861 : TLI.getNumRegisters(Context, ValueVT); 862 MVT RegisterVT = 863 isABIMangled() 864 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 865 : TLI.getRegisterType(Context, ValueVT); 866 for (unsigned i = 0; i != NumRegs; ++i) 867 Regs.push_back(Reg + i); 868 RegVTs.push_back(RegisterVT); 869 RegCount.push_back(NumRegs); 870 Reg = Reg.id() + NumRegs; 871 } 872 } 873 874 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 875 FunctionLoweringInfo &FuncInfo, 876 const SDLoc &dl, SDValue &Chain, 877 SDValue *Glue, const Value *V) const { 878 // A Value with type {} or [0 x %t] needs no registers. 879 if (ValueVTs.empty()) 880 return SDValue(); 881 882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 883 884 // Assemble the legal parts into the final values. 885 SmallVector<SDValue, 4> Values(ValueVTs.size()); 886 SmallVector<SDValue, 8> Parts; 887 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 888 // Copy the legal parts from the registers. 889 EVT ValueVT = ValueVTs[Value]; 890 unsigned NumRegs = RegCount[Value]; 891 MVT RegisterVT = isABIMangled() 892 ? TLI.getRegisterTypeForCallingConv( 893 *DAG.getContext(), *CallConv, RegVTs[Value]) 894 : RegVTs[Value]; 895 896 Parts.resize(NumRegs); 897 for (unsigned i = 0; i != NumRegs; ++i) { 898 SDValue P; 899 if (!Glue) { 900 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 901 } else { 902 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 903 *Glue = P.getValue(2); 904 } 905 906 Chain = P.getValue(1); 907 Parts[i] = P; 908 909 // If the source register was virtual and if we know something about it, 910 // add an assert node. 911 if (!Register::isVirtualRegister(Regs[Part + i]) || 912 !RegisterVT.isInteger()) 913 continue; 914 915 const FunctionLoweringInfo::LiveOutInfo *LOI = 916 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 917 if (!LOI) 918 continue; 919 920 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 921 unsigned NumSignBits = LOI->NumSignBits; 922 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 923 924 if (NumZeroBits == RegSize) { 925 // The current value is a zero. 926 // Explicitly express that as it would be easier for 927 // optimizations to kick in. 928 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 929 continue; 930 } 931 932 // FIXME: We capture more information than the dag can represent. For 933 // now, just use the tightest assertzext/assertsext possible. 934 bool isSExt; 935 EVT FromVT(MVT::Other); 936 if (NumZeroBits) { 937 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 938 isSExt = false; 939 } else if (NumSignBits > 1) { 940 FromVT = 941 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 942 isSExt = true; 943 } else { 944 continue; 945 } 946 // Add an assertion node. 947 assert(FromVT != MVT::Other); 948 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 949 RegisterVT, P, DAG.getValueType(FromVT)); 950 } 951 952 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 953 RegisterVT, ValueVT, V, Chain, CallConv); 954 Part += NumRegs; 955 Parts.clear(); 956 } 957 958 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 959 } 960 961 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 962 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 963 const Value *V, 964 ISD::NodeType PreferredExtendType) const { 965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 966 ISD::NodeType ExtendKind = PreferredExtendType; 967 968 // Get the list of the values's legal parts. 969 unsigned NumRegs = Regs.size(); 970 SmallVector<SDValue, 8> Parts(NumRegs); 971 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 972 unsigned NumParts = RegCount[Value]; 973 974 MVT RegisterVT = isABIMangled() 975 ? TLI.getRegisterTypeForCallingConv( 976 *DAG.getContext(), *CallConv, RegVTs[Value]) 977 : RegVTs[Value]; 978 979 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 980 ExtendKind = ISD::ZERO_EXTEND; 981 982 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 983 NumParts, RegisterVT, V, CallConv, ExtendKind); 984 Part += NumParts; 985 } 986 987 // Copy the parts into the registers. 988 SmallVector<SDValue, 8> Chains(NumRegs); 989 for (unsigned i = 0; i != NumRegs; ++i) { 990 SDValue Part; 991 if (!Glue) { 992 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 993 } else { 994 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 995 *Glue = Part.getValue(1); 996 } 997 998 Chains[i] = Part.getValue(0); 999 } 1000 1001 if (NumRegs == 1 || Glue) 1002 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 1003 // flagged to it. That is the CopyToReg nodes and the user are considered 1004 // a single scheduling unit. If we create a TokenFactor and return it as 1005 // chain, then the TokenFactor is both a predecessor (operand) of the 1006 // user as well as a successor (the TF operands are flagged to the user). 1007 // c1, f1 = CopyToReg 1008 // c2, f2 = CopyToReg 1009 // c3 = TokenFactor c1, c2 1010 // ... 1011 // = op c3, ..., f2 1012 Chain = Chains[NumRegs-1]; 1013 else 1014 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1015 } 1016 1017 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1018 unsigned MatchingIdx, const SDLoc &dl, 1019 SelectionDAG &DAG, 1020 std::vector<SDValue> &Ops) const { 1021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1022 1023 InlineAsm::Flag Flag(Code, Regs.size()); 1024 if (HasMatching) 1025 Flag.setMatchingOp(MatchingIdx); 1026 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1027 // Put the register class of the virtual registers in the flag word. That 1028 // way, later passes can recompute register class constraints for inline 1029 // assembly as well as normal instructions. 1030 // Don't do this for tied operands that can use the regclass information 1031 // from the def. 1032 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1033 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1034 Flag.setRegClass(RC->getID()); 1035 } 1036 1037 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1038 Ops.push_back(Res); 1039 1040 if (Code == InlineAsm::Kind::Clobber) { 1041 // Clobbers should always have a 1:1 mapping with registers, and may 1042 // reference registers that have illegal (e.g. vector) types. Hence, we 1043 // shouldn't try to apply any sort of splitting logic to them. 1044 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1045 "No 1:1 mapping from clobbers to regs?"); 1046 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1047 (void)SP; 1048 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1049 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1050 assert( 1051 (Regs[I] != SP || 1052 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1053 "If we clobbered the stack pointer, MFI should know about it."); 1054 } 1055 return; 1056 } 1057 1058 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1059 MVT RegisterVT = RegVTs[Value]; 1060 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1061 RegisterVT); 1062 for (unsigned i = 0; i != NumRegs; ++i) { 1063 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1064 unsigned TheReg = Regs[Reg++]; 1065 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1066 } 1067 } 1068 } 1069 1070 SmallVector<std::pair<Register, TypeSize>, 4> 1071 RegsForValue::getRegsAndSizes() const { 1072 SmallVector<std::pair<Register, TypeSize>, 4> OutVec; 1073 unsigned I = 0; 1074 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1075 unsigned RegCount = std::get<0>(CountAndVT); 1076 MVT RegisterVT = std::get<1>(CountAndVT); 1077 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1078 for (unsigned E = I + RegCount; I != E; ++I) 1079 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1080 } 1081 return OutVec; 1082 } 1083 1084 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1085 AssumptionCache *ac, 1086 const TargetLibraryInfo *li) { 1087 AA = aa; 1088 AC = ac; 1089 GFI = gfi; 1090 LibInfo = li; 1091 Context = DAG.getContext(); 1092 LPadToCallSiteMap.clear(); 1093 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1094 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1095 *DAG.getMachineFunction().getFunction().getParent()); 1096 } 1097 1098 void SelectionDAGBuilder::clear() { 1099 NodeMap.clear(); 1100 UnusedArgNodeMap.clear(); 1101 PendingLoads.clear(); 1102 PendingExports.clear(); 1103 PendingConstrainedFP.clear(); 1104 PendingConstrainedFPStrict.clear(); 1105 CurInst = nullptr; 1106 HasTailCall = false; 1107 SDNodeOrder = LowestSDNodeOrder; 1108 StatepointLowering.clear(); 1109 } 1110 1111 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1112 DanglingDebugInfoMap.clear(); 1113 } 1114 1115 // Update DAG root to include dependencies on Pending chains. 1116 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1117 SDValue Root = DAG.getRoot(); 1118 1119 if (Pending.empty()) 1120 return Root; 1121 1122 // Add current root to PendingChains, unless we already indirectly 1123 // depend on it. 1124 if (Root.getOpcode() != ISD::EntryToken) { 1125 unsigned i = 0, e = Pending.size(); 1126 for (; i != e; ++i) { 1127 assert(Pending[i].getNode()->getNumOperands() > 1); 1128 if (Pending[i].getNode()->getOperand(0) == Root) 1129 break; // Don't add the root if we already indirectly depend on it. 1130 } 1131 1132 if (i == e) 1133 Pending.push_back(Root); 1134 } 1135 1136 if (Pending.size() == 1) 1137 Root = Pending[0]; 1138 else 1139 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1140 1141 DAG.setRoot(Root); 1142 Pending.clear(); 1143 return Root; 1144 } 1145 1146 SDValue SelectionDAGBuilder::getMemoryRoot() { 1147 return updateRoot(PendingLoads); 1148 } 1149 1150 SDValue SelectionDAGBuilder::getRoot() { 1151 // Chain up all pending constrained intrinsics together with all 1152 // pending loads, by simply appending them to PendingLoads and 1153 // then calling getMemoryRoot(). 1154 PendingLoads.reserve(PendingLoads.size() + 1155 PendingConstrainedFP.size() + 1156 PendingConstrainedFPStrict.size()); 1157 PendingLoads.append(PendingConstrainedFP.begin(), 1158 PendingConstrainedFP.end()); 1159 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1160 PendingConstrainedFPStrict.end()); 1161 PendingConstrainedFP.clear(); 1162 PendingConstrainedFPStrict.clear(); 1163 return getMemoryRoot(); 1164 } 1165 1166 SDValue SelectionDAGBuilder::getControlRoot() { 1167 // We need to emit pending fpexcept.strict constrained intrinsics, 1168 // so append them to the PendingExports list. 1169 PendingExports.append(PendingConstrainedFPStrict.begin(), 1170 PendingConstrainedFPStrict.end()); 1171 PendingConstrainedFPStrict.clear(); 1172 return updateRoot(PendingExports); 1173 } 1174 1175 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1176 DILocalVariable *Variable, 1177 DIExpression *Expression, 1178 DebugLoc DL) { 1179 assert(Variable && "Missing variable"); 1180 1181 // Check if address has undef value. 1182 if (!Address || isa<UndefValue>(Address) || 1183 (Address->use_empty() && !isa<Argument>(Address))) { 1184 LLVM_DEBUG( 1185 dbgs() 1186 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1187 return; 1188 } 1189 1190 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1191 1192 SDValue &N = NodeMap[Address]; 1193 if (!N.getNode() && isa<Argument>(Address)) 1194 // Check unused arguments map. 1195 N = UnusedArgNodeMap[Address]; 1196 SDDbgValue *SDV; 1197 if (N.getNode()) { 1198 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1199 Address = BCI->getOperand(0); 1200 // Parameters are handled specially. 1201 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1202 if (IsParameter && FINode) { 1203 // Byval parameter. We have a frame index at this point. 1204 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1205 /*IsIndirect*/ true, DL, SDNodeOrder); 1206 } else if (isa<Argument>(Address)) { 1207 // Address is an argument, so try to emit its dbg value using 1208 // virtual register info from the FuncInfo.ValueMap. 1209 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1210 FuncArgumentDbgValueKind::Declare, N); 1211 return; 1212 } else { 1213 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1214 true, DL, SDNodeOrder); 1215 } 1216 DAG.AddDbgValue(SDV, IsParameter); 1217 } else { 1218 // If Address is an argument then try to emit its dbg value using 1219 // virtual register info from the FuncInfo.ValueMap. 1220 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1221 FuncArgumentDbgValueKind::Declare, N)) { 1222 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1223 << " (could not emit func-arg dbg_value)\n"); 1224 } 1225 } 1226 return; 1227 } 1228 1229 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1230 // Add SDDbgValue nodes for any var locs here. Do so before updating 1231 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1232 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1233 // Add SDDbgValue nodes for any var locs here. Do so before updating 1234 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1235 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1236 It != End; ++It) { 1237 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1238 dropDanglingDebugInfo(Var, It->Expr); 1239 if (It->Values.isKillLocation(It->Expr)) { 1240 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1241 continue; 1242 } 1243 SmallVector<Value *> Values(It->Values.location_ops()); 1244 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1245 It->Values.hasArgList())) { 1246 SmallVector<Value *, 4> Vals(It->Values.location_ops()); 1247 addDanglingDebugInfo(Vals, 1248 FnVarLocs->getDILocalVariable(It->VariableID), 1249 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1250 } 1251 } 1252 } 1253 1254 // We must skip DbgVariableRecords if they've already been processed above as 1255 // we have just emitted the debug values resulting from assignment tracking 1256 // analysis, making any existing DbgVariableRecords redundant (and probably 1257 // less correct). We still need to process DbgLabelRecords. This does sink 1258 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1259 // be important as it does so deterministcally and ordering between 1260 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1261 // printing). 1262 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1263 // Is there is any debug-info attached to this instruction, in the form of 1264 // DbgRecord non-instruction debug-info records. 1265 for (DbgRecord &DR : I.getDbgRecordRange()) { 1266 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1267 assert(DLR->getLabel() && "Missing label"); 1268 SDDbgLabel *SDV = 1269 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1270 DAG.AddDbgLabel(SDV); 1271 continue; 1272 } 1273 1274 if (SkipDbgVariableRecords) 1275 continue; 1276 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1277 DILocalVariable *Variable = DVR.getVariable(); 1278 DIExpression *Expression = DVR.getExpression(); 1279 dropDanglingDebugInfo(Variable, Expression); 1280 1281 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1282 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1283 continue; 1284 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1285 << "\n"); 1286 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1287 DVR.getDebugLoc()); 1288 continue; 1289 } 1290 1291 // A DbgVariableRecord with no locations is a kill location. 1292 SmallVector<Value *, 4> Values(DVR.location_ops()); 1293 if (Values.empty()) { 1294 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1295 SDNodeOrder); 1296 continue; 1297 } 1298 1299 // A DbgVariableRecord with an undef or absent location is also a kill 1300 // location. 1301 if (llvm::any_of(Values, 1302 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1303 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1304 SDNodeOrder); 1305 continue; 1306 } 1307 1308 bool IsVariadic = DVR.hasArgList(); 1309 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1310 SDNodeOrder, IsVariadic)) { 1311 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1312 DVR.getDebugLoc(), SDNodeOrder); 1313 } 1314 } 1315 } 1316 1317 void SelectionDAGBuilder::visit(const Instruction &I) { 1318 visitDbgInfo(I); 1319 1320 // Set up outgoing PHI node register values before emitting the terminator. 1321 if (I.isTerminator()) { 1322 HandlePHINodesInSuccessorBlocks(I.getParent()); 1323 } 1324 1325 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1326 if (!isa<DbgInfoIntrinsic>(I)) 1327 ++SDNodeOrder; 1328 1329 CurInst = &I; 1330 1331 // Set inserted listener only if required. 1332 bool NodeInserted = false; 1333 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1334 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1335 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra); 1336 if (PCSectionsMD || MMRA) { 1337 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1338 DAG, [&](SDNode *) { NodeInserted = true; }); 1339 } 1340 1341 visit(I.getOpcode(), I); 1342 1343 if (!I.isTerminator() && !HasTailCall && 1344 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1345 CopyToExportRegsIfNeeded(&I); 1346 1347 // Handle metadata. 1348 if (PCSectionsMD || MMRA) { 1349 auto It = NodeMap.find(&I); 1350 if (It != NodeMap.end()) { 1351 if (PCSectionsMD) 1352 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1353 if (MMRA) 1354 DAG.addMMRAMetadata(It->second.getNode(), MMRA); 1355 } else if (NodeInserted) { 1356 // This should not happen; if it does, don't let it go unnoticed so we can 1357 // fix it. Relevant visit*() function is probably missing a setValue(). 1358 errs() << "warning: loosing !pcsections and/or !mmra metadata [" 1359 << I.getModule()->getName() << "]\n"; 1360 LLVM_DEBUG(I.dump()); 1361 assert(false); 1362 } 1363 } 1364 1365 CurInst = nullptr; 1366 } 1367 1368 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1369 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1370 } 1371 1372 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1373 // Note: this doesn't use InstVisitor, because it has to work with 1374 // ConstantExpr's in addition to instructions. 1375 switch (Opcode) { 1376 default: llvm_unreachable("Unknown instruction type encountered!"); 1377 // Build the switch statement using the Instruction.def file. 1378 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1379 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1380 #include "llvm/IR/Instruction.def" 1381 } 1382 } 1383 1384 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1385 DILocalVariable *Variable, 1386 DebugLoc DL, unsigned Order, 1387 SmallVectorImpl<Value *> &Values, 1388 DIExpression *Expression) { 1389 // For variadic dbg_values we will now insert an undef. 1390 // FIXME: We can potentially recover these! 1391 SmallVector<SDDbgOperand, 2> Locs; 1392 for (const Value *V : Values) { 1393 auto *Undef = UndefValue::get(V->getType()); 1394 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1395 } 1396 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1397 /*IsIndirect=*/false, DL, Order, 1398 /*IsVariadic=*/true); 1399 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1400 return true; 1401 } 1402 1403 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1404 DILocalVariable *Var, 1405 DIExpression *Expr, 1406 bool IsVariadic, DebugLoc DL, 1407 unsigned Order) { 1408 if (IsVariadic) { 1409 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1410 return; 1411 } 1412 // TODO: Dangling debug info will eventually either be resolved or produce 1413 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1414 // between the original dbg.value location and its resolved DBG_VALUE, 1415 // which we should ideally fill with an extra Undef DBG_VALUE. 1416 assert(Values.size() == 1); 1417 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1418 } 1419 1420 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1421 const DIExpression *Expr) { 1422 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1423 DIVariable *DanglingVariable = DDI.getVariable(); 1424 DIExpression *DanglingExpr = DDI.getExpression(); 1425 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1426 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1427 << printDDI(nullptr, DDI) << "\n"); 1428 return true; 1429 } 1430 return false; 1431 }; 1432 1433 for (auto &DDIMI : DanglingDebugInfoMap) { 1434 DanglingDebugInfoVector &DDIV = DDIMI.second; 1435 1436 // If debug info is to be dropped, run it through final checks to see 1437 // whether it can be salvaged. 1438 for (auto &DDI : DDIV) 1439 if (isMatchingDbgValue(DDI)) 1440 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1441 1442 erase_if(DDIV, isMatchingDbgValue); 1443 } 1444 } 1445 1446 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1447 // generate the debug data structures now that we've seen its definition. 1448 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1449 SDValue Val) { 1450 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1451 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1452 return; 1453 1454 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1455 for (auto &DDI : DDIV) { 1456 DebugLoc DL = DDI.getDebugLoc(); 1457 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1458 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1459 DILocalVariable *Variable = DDI.getVariable(); 1460 DIExpression *Expr = DDI.getExpression(); 1461 assert(Variable->isValidLocationForIntrinsic(DL) && 1462 "Expected inlined-at fields to agree"); 1463 SDDbgValue *SDV; 1464 if (Val.getNode()) { 1465 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1466 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1467 // we couldn't resolve it directly when examining the DbgValue intrinsic 1468 // in the first place we should not be more successful here). Unless we 1469 // have some test case that prove this to be correct we should avoid 1470 // calling EmitFuncArgumentDbgValue here. 1471 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1472 FuncArgumentDbgValueKind::Value, Val)) { 1473 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1474 << printDDI(V, DDI) << "\n"); 1475 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1476 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1477 // inserted after the definition of Val when emitting the instructions 1478 // after ISel. An alternative could be to teach 1479 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1480 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1481 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1482 << ValSDNodeOrder << "\n"); 1483 SDV = getDbgValue(Val, Variable, Expr, DL, 1484 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1485 DAG.AddDbgValue(SDV, false); 1486 } else 1487 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1488 << printDDI(V, DDI) 1489 << " in EmitFuncArgumentDbgValue\n"); 1490 } else { 1491 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1492 << "\n"); 1493 auto Undef = UndefValue::get(V->getType()); 1494 auto SDV = 1495 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1496 DAG.AddDbgValue(SDV, false); 1497 } 1498 } 1499 DDIV.clear(); 1500 } 1501 1502 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1503 DanglingDebugInfo &DDI) { 1504 // TODO: For the variadic implementation, instead of only checking the fail 1505 // state of `handleDebugValue`, we need know specifically which values were 1506 // invalid, so that we attempt to salvage only those values when processing 1507 // a DIArgList. 1508 const Value *OrigV = V; 1509 DILocalVariable *Var = DDI.getVariable(); 1510 DIExpression *Expr = DDI.getExpression(); 1511 DebugLoc DL = DDI.getDebugLoc(); 1512 unsigned SDOrder = DDI.getSDNodeOrder(); 1513 1514 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1515 // that DW_OP_stack_value is desired. 1516 bool StackValue = true; 1517 1518 // Can this Value can be encoded without any further work? 1519 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1520 return; 1521 1522 // Attempt to salvage back through as many instructions as possible. Bail if 1523 // a non-instruction is seen, such as a constant expression or global 1524 // variable. FIXME: Further work could recover those too. 1525 while (isa<Instruction>(V)) { 1526 const Instruction &VAsInst = *cast<const Instruction>(V); 1527 // Temporary "0", awaiting real implementation. 1528 SmallVector<uint64_t, 16> Ops; 1529 SmallVector<Value *, 4> AdditionalValues; 1530 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1531 Expr->getNumLocationOperands(), Ops, 1532 AdditionalValues); 1533 // If we cannot salvage any further, and haven't yet found a suitable debug 1534 // expression, bail out. 1535 if (!V) 1536 break; 1537 1538 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1539 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1540 // here for variadic dbg_values, remove that condition. 1541 if (!AdditionalValues.empty()) 1542 break; 1543 1544 // New value and expr now represent this debuginfo. 1545 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1546 1547 // Some kind of simplification occurred: check whether the operand of the 1548 // salvaged debug expression can be encoded in this DAG. 1549 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1550 LLVM_DEBUG( 1551 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1552 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1553 return; 1554 } 1555 } 1556 1557 // This was the final opportunity to salvage this debug information, and it 1558 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1559 // any earlier variable location. 1560 assert(OrigV && "V shouldn't be null"); 1561 auto *Undef = UndefValue::get(OrigV->getType()); 1562 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1563 DAG.AddDbgValue(SDV, false); 1564 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1565 << printDDI(OrigV, DDI) << "\n"); 1566 } 1567 1568 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1569 DIExpression *Expr, 1570 DebugLoc DbgLoc, 1571 unsigned Order) { 1572 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1573 DIExpression *NewExpr = 1574 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1575 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1576 /*IsVariadic*/ false); 1577 } 1578 1579 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1580 DILocalVariable *Var, 1581 DIExpression *Expr, DebugLoc DbgLoc, 1582 unsigned Order, bool IsVariadic) { 1583 if (Values.empty()) 1584 return true; 1585 1586 // Filter EntryValue locations out early. 1587 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1588 return true; 1589 1590 SmallVector<SDDbgOperand> LocationOps; 1591 SmallVector<SDNode *> Dependencies; 1592 for (const Value *V : Values) { 1593 // Constant value. 1594 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1595 isa<ConstantPointerNull>(V)) { 1596 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1597 continue; 1598 } 1599 1600 // Look through IntToPtr constants. 1601 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1602 if (CE->getOpcode() == Instruction::IntToPtr) { 1603 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1604 continue; 1605 } 1606 1607 // If the Value is a frame index, we can create a FrameIndex debug value 1608 // without relying on the DAG at all. 1609 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1610 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1611 if (SI != FuncInfo.StaticAllocaMap.end()) { 1612 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1613 continue; 1614 } 1615 } 1616 1617 // Do not use getValue() in here; we don't want to generate code at 1618 // this point if it hasn't been done yet. 1619 SDValue N = NodeMap[V]; 1620 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1621 N = UnusedArgNodeMap[V]; 1622 1623 if (N.getNode()) { 1624 // Only emit func arg dbg value for non-variadic dbg.values for now. 1625 if (!IsVariadic && 1626 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1627 FuncArgumentDbgValueKind::Value, N)) 1628 return true; 1629 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1630 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1631 // describe stack slot locations. 1632 // 1633 // Consider "int x = 0; int *px = &x;". There are two kinds of 1634 // interesting debug values here after optimization: 1635 // 1636 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1637 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1638 // 1639 // Both describe the direct values of their associated variables. 1640 Dependencies.push_back(N.getNode()); 1641 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1642 continue; 1643 } 1644 LocationOps.emplace_back( 1645 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1646 continue; 1647 } 1648 1649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1650 // Special rules apply for the first dbg.values of parameter variables in a 1651 // function. Identify them by the fact they reference Argument Values, that 1652 // they're parameters, and they are parameters of the current function. We 1653 // need to let them dangle until they get an SDNode. 1654 bool IsParamOfFunc = 1655 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1656 if (IsParamOfFunc) 1657 return false; 1658 1659 // The value is not used in this block yet (or it would have an SDNode). 1660 // We still want the value to appear for the user if possible -- if it has 1661 // an associated VReg, we can refer to that instead. 1662 auto VMI = FuncInfo.ValueMap.find(V); 1663 if (VMI != FuncInfo.ValueMap.end()) { 1664 unsigned Reg = VMI->second; 1665 // If this is a PHI node, it may be split up into several MI PHI nodes 1666 // (in FunctionLoweringInfo::set). 1667 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1668 V->getType(), std::nullopt); 1669 if (RFV.occupiesMultipleRegs()) { 1670 // FIXME: We could potentially support variadic dbg_values here. 1671 if (IsVariadic) 1672 return false; 1673 unsigned Offset = 0; 1674 unsigned BitsToDescribe = 0; 1675 if (auto VarSize = Var->getSizeInBits()) 1676 BitsToDescribe = *VarSize; 1677 if (auto Fragment = Expr->getFragmentInfo()) 1678 BitsToDescribe = Fragment->SizeInBits; 1679 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1680 // Bail out if all bits are described already. 1681 if (Offset >= BitsToDescribe) 1682 break; 1683 // TODO: handle scalable vectors. 1684 unsigned RegisterSize = RegAndSize.second; 1685 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1686 ? BitsToDescribe - Offset 1687 : RegisterSize; 1688 auto FragmentExpr = DIExpression::createFragmentExpression( 1689 Expr, Offset, FragmentSize); 1690 if (!FragmentExpr) 1691 continue; 1692 SDDbgValue *SDV = DAG.getVRegDbgValue( 1693 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order); 1694 DAG.AddDbgValue(SDV, false); 1695 Offset += RegisterSize; 1696 } 1697 return true; 1698 } 1699 // We can use simple vreg locations for variadic dbg_values as well. 1700 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1701 continue; 1702 } 1703 // We failed to create a SDDbgOperand for V. 1704 return false; 1705 } 1706 1707 // We have created a SDDbgOperand for each Value in Values. 1708 assert(!LocationOps.empty()); 1709 SDDbgValue *SDV = 1710 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1711 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic); 1712 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1713 return true; 1714 } 1715 1716 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1717 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1718 for (auto &Pair : DanglingDebugInfoMap) 1719 for (auto &DDI : Pair.second) 1720 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1721 clearDanglingDebugInfo(); 1722 } 1723 1724 /// getCopyFromRegs - If there was virtual register allocated for the value V 1725 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1726 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1727 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1728 SDValue Result; 1729 1730 if (It != FuncInfo.ValueMap.end()) { 1731 Register InReg = It->second; 1732 1733 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1734 DAG.getDataLayout(), InReg, Ty, 1735 std::nullopt); // This is not an ABI copy. 1736 SDValue Chain = DAG.getEntryNode(); 1737 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1738 V); 1739 resolveDanglingDebugInfo(V, Result); 1740 } 1741 1742 return Result; 1743 } 1744 1745 /// getValue - Return an SDValue for the given Value. 1746 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1747 // If we already have an SDValue for this value, use it. It's important 1748 // to do this first, so that we don't create a CopyFromReg if we already 1749 // have a regular SDValue. 1750 SDValue &N = NodeMap[V]; 1751 if (N.getNode()) return N; 1752 1753 // If there's a virtual register allocated and initialized for this 1754 // value, use it. 1755 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1756 return copyFromReg; 1757 1758 // Otherwise create a new SDValue and remember it. 1759 SDValue Val = getValueImpl(V); 1760 NodeMap[V] = Val; 1761 resolveDanglingDebugInfo(V, Val); 1762 return Val; 1763 } 1764 1765 /// getNonRegisterValue - Return an SDValue for the given Value, but 1766 /// don't look in FuncInfo.ValueMap for a virtual register. 1767 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1768 // If we already have an SDValue for this value, use it. 1769 SDValue &N = NodeMap[V]; 1770 if (N.getNode()) { 1771 if (isIntOrFPConstant(N)) { 1772 // Remove the debug location from the node as the node is about to be used 1773 // in a location which may differ from the original debug location. This 1774 // is relevant to Constant and ConstantFP nodes because they can appear 1775 // as constant expressions inside PHI nodes. 1776 N->setDebugLoc(DebugLoc()); 1777 } 1778 return N; 1779 } 1780 1781 // Otherwise create a new SDValue and remember it. 1782 SDValue Val = getValueImpl(V); 1783 NodeMap[V] = Val; 1784 resolveDanglingDebugInfo(V, Val); 1785 return Val; 1786 } 1787 1788 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1789 /// Create an SDValue for the given value. 1790 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1792 1793 if (const Constant *C = dyn_cast<Constant>(V)) { 1794 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1795 1796 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1797 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1798 1799 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1800 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1801 1802 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) { 1803 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT, 1804 getValue(CPA->getPointer()), getValue(CPA->getKey()), 1805 getValue(CPA->getAddrDiscriminator()), 1806 getValue(CPA->getDiscriminator())); 1807 } 1808 1809 if (isa<ConstantPointerNull>(C)) { 1810 unsigned AS = V->getType()->getPointerAddressSpace(); 1811 return DAG.getConstant(0, getCurSDLoc(), 1812 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1813 } 1814 1815 if (match(C, m_VScale())) 1816 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1817 1818 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1819 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1820 1821 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1822 return DAG.getUNDEF(VT); 1823 1824 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1825 visit(CE->getOpcode(), *CE); 1826 SDValue N1 = NodeMap[V]; 1827 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1828 return N1; 1829 } 1830 1831 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1832 SmallVector<SDValue, 4> Constants; 1833 for (const Use &U : C->operands()) { 1834 SDNode *Val = getValue(U).getNode(); 1835 // If the operand is an empty aggregate, there are no values. 1836 if (!Val) continue; 1837 // Add each leaf value from the operand to the Constants list 1838 // to form a flattened list of all the values. 1839 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1840 Constants.push_back(SDValue(Val, i)); 1841 } 1842 1843 return DAG.getMergeValues(Constants, getCurSDLoc()); 1844 } 1845 1846 if (const ConstantDataSequential *CDS = 1847 dyn_cast<ConstantDataSequential>(C)) { 1848 SmallVector<SDValue, 4> Ops; 1849 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1850 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1851 // Add each leaf value from the operand to the Constants list 1852 // to form a flattened list of all the values. 1853 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1854 Ops.push_back(SDValue(Val, i)); 1855 } 1856 1857 if (isa<ArrayType>(CDS->getType())) 1858 return DAG.getMergeValues(Ops, getCurSDLoc()); 1859 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1860 } 1861 1862 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1863 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1864 "Unknown struct or array constant!"); 1865 1866 SmallVector<EVT, 4> ValueVTs; 1867 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1868 unsigned NumElts = ValueVTs.size(); 1869 if (NumElts == 0) 1870 return SDValue(); // empty struct 1871 SmallVector<SDValue, 4> Constants(NumElts); 1872 for (unsigned i = 0; i != NumElts; ++i) { 1873 EVT EltVT = ValueVTs[i]; 1874 if (isa<UndefValue>(C)) 1875 Constants[i] = DAG.getUNDEF(EltVT); 1876 else if (EltVT.isFloatingPoint()) 1877 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1878 else 1879 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1880 } 1881 1882 return DAG.getMergeValues(Constants, getCurSDLoc()); 1883 } 1884 1885 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1886 return DAG.getBlockAddress(BA, VT); 1887 1888 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1889 return getValue(Equiv->getGlobalValue()); 1890 1891 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1892 return getValue(NC->getGlobalValue()); 1893 1894 if (VT == MVT::aarch64svcount) { 1895 assert(C->isNullValue() && "Can only zero this target type!"); 1896 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1897 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1898 } 1899 1900 VectorType *VecTy = cast<VectorType>(V->getType()); 1901 1902 // Now that we know the number and type of the elements, get that number of 1903 // elements into the Ops array based on what kind of constant it is. 1904 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1905 SmallVector<SDValue, 16> Ops; 1906 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1907 for (unsigned i = 0; i != NumElements; ++i) 1908 Ops.push_back(getValue(CV->getOperand(i))); 1909 1910 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1911 } 1912 1913 if (isa<ConstantAggregateZero>(C)) { 1914 EVT EltVT = 1915 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1916 1917 SDValue Op; 1918 if (EltVT.isFloatingPoint()) 1919 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1920 else 1921 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1922 1923 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1924 } 1925 1926 llvm_unreachable("Unknown vector constant"); 1927 } 1928 1929 // If this is a static alloca, generate it as the frameindex instead of 1930 // computation. 1931 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1932 DenseMap<const AllocaInst*, int>::iterator SI = 1933 FuncInfo.StaticAllocaMap.find(AI); 1934 if (SI != FuncInfo.StaticAllocaMap.end()) 1935 return DAG.getFrameIndex( 1936 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1937 } 1938 1939 // If this is an instruction which fast-isel has deferred, select it now. 1940 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1941 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1942 1943 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1944 Inst->getType(), std::nullopt); 1945 SDValue Chain = DAG.getEntryNode(); 1946 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1947 } 1948 1949 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1950 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1951 1952 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1953 return DAG.getBasicBlock(FuncInfo.getMBB(BB)); 1954 1955 llvm_unreachable("Can't get register for value!"); 1956 } 1957 1958 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1959 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1960 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1961 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1962 bool IsSEH = isAsynchronousEHPersonality(Pers); 1963 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1964 if (!IsSEH) 1965 CatchPadMBB->setIsEHScopeEntry(); 1966 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1967 if (IsMSVCCXX || IsCoreCLR) 1968 CatchPadMBB->setIsEHFuncletEntry(); 1969 } 1970 1971 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1972 // Update machine-CFG edge. 1973 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor()); 1974 FuncInfo.MBB->addSuccessor(TargetMBB); 1975 TargetMBB->setIsEHCatchretTarget(true); 1976 DAG.getMachineFunction().setHasEHCatchret(true); 1977 1978 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1979 bool IsSEH = isAsynchronousEHPersonality(Pers); 1980 if (IsSEH) { 1981 // If this is not a fall-through branch or optimizations are switched off, 1982 // emit the branch. 1983 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1984 TM.getOptLevel() == CodeGenOptLevel::None) 1985 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1986 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1987 return; 1988 } 1989 1990 // Figure out the funclet membership for the catchret's successor. 1991 // This will be used by the FuncletLayout pass to determine how to order the 1992 // BB's. 1993 // A 'catchret' returns to the outer scope's color. 1994 Value *ParentPad = I.getCatchSwitchParentPad(); 1995 const BasicBlock *SuccessorColor; 1996 if (isa<ConstantTokenNone>(ParentPad)) 1997 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1998 else 1999 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 2000 assert(SuccessorColor && "No parent funclet for catchret!"); 2001 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor); 2002 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 2003 2004 // Create the terminator node. 2005 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 2006 getControlRoot(), DAG.getBasicBlock(TargetMBB), 2007 DAG.getBasicBlock(SuccessorColorMBB)); 2008 DAG.setRoot(Ret); 2009 } 2010 2011 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 2012 // Don't emit any special code for the cleanuppad instruction. It just marks 2013 // the start of an EH scope/funclet. 2014 FuncInfo.MBB->setIsEHScopeEntry(); 2015 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2016 if (Pers != EHPersonality::Wasm_CXX) { 2017 FuncInfo.MBB->setIsEHFuncletEntry(); 2018 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2019 } 2020 } 2021 2022 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2023 // not match, it is OK to add only the first unwind destination catchpad to the 2024 // successors, because there will be at least one invoke instruction within the 2025 // catch scope that points to the next unwind destination, if one exists, so 2026 // CFGSort cannot mess up with BB sorting order. 2027 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2028 // call within them, and catchpads only consisting of 'catch (...)' have a 2029 // '__cxa_end_catch' call within them, both of which generate invokes in case 2030 // the next unwind destination exists, i.e., the next unwind destination is not 2031 // the caller.) 2032 // 2033 // Having at most one EH pad successor is also simpler and helps later 2034 // transformations. 2035 // 2036 // For example, 2037 // current: 2038 // invoke void @foo to ... unwind label %catch.dispatch 2039 // catch.dispatch: 2040 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2041 // catch.start: 2042 // ... 2043 // ... in this BB or some other child BB dominated by this BB there will be an 2044 // invoke that points to 'next' BB as an unwind destination 2045 // 2046 // next: ; We don't need to add this to 'current' BB's successor 2047 // ... 2048 static void findWasmUnwindDestinations( 2049 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2050 BranchProbability Prob, 2051 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2052 &UnwindDests) { 2053 while (EHPadBB) { 2054 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2055 if (isa<CleanupPadInst>(Pad)) { 2056 // Stop on cleanup pads. 2057 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2058 UnwindDests.back().first->setIsEHScopeEntry(); 2059 break; 2060 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2061 // Add the catchpad handlers to the possible destinations. We don't 2062 // continue to the unwind destination of the catchswitch for wasm. 2063 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2064 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2065 UnwindDests.back().first->setIsEHScopeEntry(); 2066 } 2067 break; 2068 } else { 2069 continue; 2070 } 2071 } 2072 } 2073 2074 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2075 /// many places it could ultimately go. In the IR, we have a single unwind 2076 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2077 /// This function skips over imaginary basic blocks that hold catchswitch 2078 /// instructions, and finds all the "real" machine 2079 /// basic block destinations. As those destinations may not be successors of 2080 /// EHPadBB, here we also calculate the edge probability to those destinations. 2081 /// The passed-in Prob is the edge probability to EHPadBB. 2082 static void findUnwindDestinations( 2083 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2084 BranchProbability Prob, 2085 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2086 &UnwindDests) { 2087 EHPersonality Personality = 2088 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2089 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2090 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2091 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2092 bool IsSEH = isAsynchronousEHPersonality(Personality); 2093 2094 if (IsWasmCXX) { 2095 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2096 assert(UnwindDests.size() <= 1 && 2097 "There should be at most one unwind destination for wasm"); 2098 return; 2099 } 2100 2101 while (EHPadBB) { 2102 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2103 BasicBlock *NewEHPadBB = nullptr; 2104 if (isa<LandingPadInst>(Pad)) { 2105 // Stop on landingpads. They are not funclets. 2106 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2107 break; 2108 } else if (isa<CleanupPadInst>(Pad)) { 2109 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2110 // personalities. 2111 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob); 2112 UnwindDests.back().first->setIsEHScopeEntry(); 2113 UnwindDests.back().first->setIsEHFuncletEntry(); 2114 break; 2115 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2116 // Add the catchpad handlers to the possible destinations. 2117 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2118 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob); 2119 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2120 if (IsMSVCCXX || IsCoreCLR) 2121 UnwindDests.back().first->setIsEHFuncletEntry(); 2122 if (!IsSEH) 2123 UnwindDests.back().first->setIsEHScopeEntry(); 2124 } 2125 NewEHPadBB = CatchSwitch->getUnwindDest(); 2126 } else { 2127 continue; 2128 } 2129 2130 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2131 if (BPI && NewEHPadBB) 2132 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2133 EHPadBB = NewEHPadBB; 2134 } 2135 } 2136 2137 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2138 // Update successor info. 2139 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2140 auto UnwindDest = I.getUnwindDest(); 2141 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2142 BranchProbability UnwindDestProb = 2143 (BPI && UnwindDest) 2144 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2145 : BranchProbability::getZero(); 2146 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2147 for (auto &UnwindDest : UnwindDests) { 2148 UnwindDest.first->setIsEHPad(); 2149 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2150 } 2151 FuncInfo.MBB->normalizeSuccProbs(); 2152 2153 // Create the terminator node. 2154 SDValue Ret = 2155 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2156 DAG.setRoot(Ret); 2157 } 2158 2159 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2160 report_fatal_error("visitCatchSwitch not yet implemented!"); 2161 } 2162 2163 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2165 auto &DL = DAG.getDataLayout(); 2166 SDValue Chain = getControlRoot(); 2167 SmallVector<ISD::OutputArg, 8> Outs; 2168 SmallVector<SDValue, 8> OutVals; 2169 2170 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2171 // lower 2172 // 2173 // %val = call <ty> @llvm.experimental.deoptimize() 2174 // ret <ty> %val 2175 // 2176 // differently. 2177 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2178 LowerDeoptimizingReturn(); 2179 return; 2180 } 2181 2182 if (!FuncInfo.CanLowerReturn) { 2183 Register DemoteReg = FuncInfo.DemoteRegister; 2184 const Function *F = I.getParent()->getParent(); 2185 2186 // Emit a store of the return value through the virtual register. 2187 // Leave Outs empty so that LowerReturn won't try to load return 2188 // registers the usual way. 2189 SmallVector<EVT, 1> PtrValueVTs; 2190 ComputeValueVTs(TLI, DL, 2191 PointerType::get(F->getContext(), 2192 DAG.getDataLayout().getAllocaAddrSpace()), 2193 PtrValueVTs); 2194 2195 SDValue RetPtr = 2196 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2197 SDValue RetOp = getValue(I.getOperand(0)); 2198 2199 SmallVector<EVT, 4> ValueVTs, MemVTs; 2200 SmallVector<uint64_t, 4> Offsets; 2201 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2202 &Offsets, 0); 2203 unsigned NumValues = ValueVTs.size(); 2204 2205 SmallVector<SDValue, 4> Chains(NumValues); 2206 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2207 for (unsigned i = 0; i != NumValues; ++i) { 2208 // An aggregate return value cannot wrap around the address space, so 2209 // offsets to its parts don't wrap either. 2210 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2211 TypeSize::getFixed(Offsets[i])); 2212 2213 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2214 if (MemVTs[i] != ValueVTs[i]) 2215 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2216 Chains[i] = DAG.getStore( 2217 Chain, getCurSDLoc(), Val, 2218 // FIXME: better loc info would be nice. 2219 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2220 commonAlignment(BaseAlign, Offsets[i])); 2221 } 2222 2223 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2224 MVT::Other, Chains); 2225 } else if (I.getNumOperands() != 0) { 2226 SmallVector<EVT, 4> ValueVTs; 2227 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2228 unsigned NumValues = ValueVTs.size(); 2229 if (NumValues) { 2230 SDValue RetOp = getValue(I.getOperand(0)); 2231 2232 const Function *F = I.getParent()->getParent(); 2233 2234 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2235 I.getOperand(0)->getType(), F->getCallingConv(), 2236 /*IsVarArg*/ false, DL); 2237 2238 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2239 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2240 ExtendKind = ISD::SIGN_EXTEND; 2241 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2242 ExtendKind = ISD::ZERO_EXTEND; 2243 2244 LLVMContext &Context = F->getContext(); 2245 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2246 2247 for (unsigned j = 0; j != NumValues; ++j) { 2248 EVT VT = ValueVTs[j]; 2249 2250 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2251 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2252 2253 CallingConv::ID CC = F->getCallingConv(); 2254 2255 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2256 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2257 SmallVector<SDValue, 4> Parts(NumParts); 2258 getCopyToParts(DAG, getCurSDLoc(), 2259 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2260 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2261 2262 // 'inreg' on function refers to return value 2263 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2264 if (RetInReg) 2265 Flags.setInReg(); 2266 2267 if (I.getOperand(0)->getType()->isPointerTy()) { 2268 Flags.setPointer(); 2269 Flags.setPointerAddrSpace( 2270 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2271 } 2272 2273 if (NeedsRegBlock) { 2274 Flags.setInConsecutiveRegs(); 2275 if (j == NumValues - 1) 2276 Flags.setInConsecutiveRegsLast(); 2277 } 2278 2279 // Propagate extension type if any 2280 if (ExtendKind == ISD::SIGN_EXTEND) 2281 Flags.setSExt(); 2282 else if (ExtendKind == ISD::ZERO_EXTEND) 2283 Flags.setZExt(); 2284 else if (F->getAttributes().hasRetAttr(Attribute::NoExt)) 2285 Flags.setNoExt(); 2286 2287 for (unsigned i = 0; i < NumParts; ++i) { 2288 Outs.push_back(ISD::OutputArg(Flags, 2289 Parts[i].getValueType().getSimpleVT(), 2290 VT, /*isfixed=*/true, 0, 0)); 2291 OutVals.push_back(Parts[i]); 2292 } 2293 } 2294 } 2295 } 2296 2297 // Push in swifterror virtual register as the last element of Outs. This makes 2298 // sure swifterror virtual register will be returned in the swifterror 2299 // physical register. 2300 const Function *F = I.getParent()->getParent(); 2301 if (TLI.supportSwiftError() && 2302 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2303 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2304 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2305 Flags.setSwiftError(); 2306 Outs.push_back(ISD::OutputArg( 2307 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2308 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2309 // Create SDNode for the swifterror virtual register. 2310 OutVals.push_back( 2311 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2312 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2313 EVT(TLI.getPointerTy(DL)))); 2314 } 2315 2316 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2317 CallingConv::ID CallConv = 2318 DAG.getMachineFunction().getFunction().getCallingConv(); 2319 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2320 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2321 2322 // Verify that the target's LowerReturn behaved as expected. 2323 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2324 "LowerReturn didn't return a valid chain!"); 2325 2326 // Update the DAG with the new chain value resulting from return lowering. 2327 DAG.setRoot(Chain); 2328 } 2329 2330 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2331 /// created for it, emit nodes to copy the value into the virtual 2332 /// registers. 2333 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2334 // Skip empty types 2335 if (V->getType()->isEmptyTy()) 2336 return; 2337 2338 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2339 if (VMI != FuncInfo.ValueMap.end()) { 2340 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2341 "Unused value assigned virtual registers!"); 2342 CopyValueToVirtualRegister(V, VMI->second); 2343 } 2344 } 2345 2346 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2347 /// the current basic block, add it to ValueMap now so that we'll get a 2348 /// CopyTo/FromReg. 2349 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2350 // No need to export constants. 2351 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2352 2353 // Already exported? 2354 if (FuncInfo.isExportedInst(V)) return; 2355 2356 Register Reg = FuncInfo.InitializeRegForValue(V); 2357 CopyValueToVirtualRegister(V, Reg); 2358 } 2359 2360 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2361 const BasicBlock *FromBB) { 2362 // The operands of the setcc have to be in this block. We don't know 2363 // how to export them from some other block. 2364 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2365 // Can export from current BB. 2366 if (VI->getParent() == FromBB) 2367 return true; 2368 2369 // Is already exported, noop. 2370 return FuncInfo.isExportedInst(V); 2371 } 2372 2373 // If this is an argument, we can export it if the BB is the entry block or 2374 // if it is already exported. 2375 if (isa<Argument>(V)) { 2376 if (FromBB->isEntryBlock()) 2377 return true; 2378 2379 // Otherwise, can only export this if it is already exported. 2380 return FuncInfo.isExportedInst(V); 2381 } 2382 2383 // Otherwise, constants can always be exported. 2384 return true; 2385 } 2386 2387 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2388 BranchProbability 2389 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2390 const MachineBasicBlock *Dst) const { 2391 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2392 const BasicBlock *SrcBB = Src->getBasicBlock(); 2393 const BasicBlock *DstBB = Dst->getBasicBlock(); 2394 if (!BPI) { 2395 // If BPI is not available, set the default probability as 1 / N, where N is 2396 // the number of successors. 2397 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2398 return BranchProbability(1, SuccSize); 2399 } 2400 return BPI->getEdgeProbability(SrcBB, DstBB); 2401 } 2402 2403 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2404 MachineBasicBlock *Dst, 2405 BranchProbability Prob) { 2406 if (!FuncInfo.BPI) 2407 Src->addSuccessorWithoutProb(Dst); 2408 else { 2409 if (Prob.isUnknown()) 2410 Prob = getEdgeProbability(Src, Dst); 2411 Src->addSuccessor(Dst, Prob); 2412 } 2413 } 2414 2415 static bool InBlock(const Value *V, const BasicBlock *BB) { 2416 if (const Instruction *I = dyn_cast<Instruction>(V)) 2417 return I->getParent() == BB; 2418 return true; 2419 } 2420 2421 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2422 /// This function emits a branch and is used at the leaves of an OR or an 2423 /// AND operator tree. 2424 void 2425 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2426 MachineBasicBlock *TBB, 2427 MachineBasicBlock *FBB, 2428 MachineBasicBlock *CurBB, 2429 MachineBasicBlock *SwitchBB, 2430 BranchProbability TProb, 2431 BranchProbability FProb, 2432 bool InvertCond) { 2433 const BasicBlock *BB = CurBB->getBasicBlock(); 2434 2435 // If the leaf of the tree is a comparison, merge the condition into 2436 // the caseblock. 2437 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2438 // The operands of the cmp have to be in this block. We don't know 2439 // how to export them from some other block. If this is the first block 2440 // of the sequence, no exporting is needed. 2441 if (CurBB == SwitchBB || 2442 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2443 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2444 ISD::CondCode Condition; 2445 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2446 ICmpInst::Predicate Pred = 2447 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2448 Condition = getICmpCondCode(Pred); 2449 } else { 2450 const FCmpInst *FC = cast<FCmpInst>(Cond); 2451 FCmpInst::Predicate Pred = 2452 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2453 Condition = getFCmpCondCode(Pred); 2454 if (TM.Options.NoNaNsFPMath) 2455 Condition = getFCmpCodeWithoutNaN(Condition); 2456 } 2457 2458 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2459 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2460 SL->SwitchCases.push_back(CB); 2461 return; 2462 } 2463 } 2464 2465 // Create a CaseBlock record representing this branch. 2466 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2467 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2468 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2469 SL->SwitchCases.push_back(CB); 2470 } 2471 2472 // Collect dependencies on V recursively. This is used for the cost analysis in 2473 // `shouldKeepJumpConditionsTogether`. 2474 static bool collectInstructionDeps( 2475 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2476 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2477 unsigned Depth = 0) { 2478 // Return false if we have an incomplete count. 2479 if (Depth >= SelectionDAG::MaxRecursionDepth) 2480 return false; 2481 2482 auto *I = dyn_cast<Instruction>(V); 2483 if (I == nullptr) 2484 return true; 2485 2486 if (Necessary != nullptr) { 2487 // This instruction is necessary for the other side of the condition so 2488 // don't count it. 2489 if (Necessary->contains(I)) 2490 return true; 2491 } 2492 2493 // Already added this dep. 2494 if (!Deps->try_emplace(I, false).second) 2495 return true; 2496 2497 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2498 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2499 Depth + 1)) 2500 return false; 2501 return true; 2502 } 2503 2504 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2505 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2506 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2507 TargetLoweringBase::CondMergingParams Params) const { 2508 if (I.getNumSuccessors() != 2) 2509 return false; 2510 2511 if (!I.isConditional()) 2512 return false; 2513 2514 if (Params.BaseCost < 0) 2515 return false; 2516 2517 // Baseline cost. 2518 InstructionCost CostThresh = Params.BaseCost; 2519 2520 BranchProbabilityInfo *BPI = nullptr; 2521 if (Params.LikelyBias || Params.UnlikelyBias) 2522 BPI = FuncInfo.BPI; 2523 if (BPI != nullptr) { 2524 // See if we are either likely to get an early out or compute both lhs/rhs 2525 // of the condition. 2526 BasicBlock *IfFalse = I.getSuccessor(0); 2527 BasicBlock *IfTrue = I.getSuccessor(1); 2528 2529 std::optional<bool> Likely; 2530 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2531 Likely = true; 2532 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2533 Likely = false; 2534 2535 if (Likely) { 2536 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2537 // Its likely we will have to compute both lhs and rhs of condition 2538 CostThresh += Params.LikelyBias; 2539 else { 2540 if (Params.UnlikelyBias < 0) 2541 return false; 2542 // Its likely we will get an early out. 2543 CostThresh -= Params.UnlikelyBias; 2544 } 2545 } 2546 } 2547 2548 if (CostThresh <= 0) 2549 return false; 2550 2551 // Collect "all" instructions that lhs condition is dependent on. 2552 // Use map for stable iteration (to avoid non-determanism of iteration of 2553 // SmallPtrSet). The `bool` value is just a dummy. 2554 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2555 collectInstructionDeps(&LhsDeps, Lhs); 2556 // Collect "all" instructions that rhs condition is dependent on AND are 2557 // dependencies of lhs. This gives us an estimate on which instructions we 2558 // stand to save by splitting the condition. 2559 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2560 return false; 2561 // Add the compare instruction itself unless its a dependency on the LHS. 2562 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2563 if (!LhsDeps.contains(RhsI)) 2564 RhsDeps.try_emplace(RhsI, false); 2565 2566 const auto &TLI = DAG.getTargetLoweringInfo(); 2567 const auto &TTI = 2568 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2569 2570 InstructionCost CostOfIncluding = 0; 2571 // See if this instruction will need to computed independently of whether RHS 2572 // is. 2573 Value *BrCond = I.getCondition(); 2574 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2575 for (const auto *U : Ins->users()) { 2576 // If user is independent of RHS calculation we don't need to count it. 2577 if (auto *UIns = dyn_cast<Instruction>(U)) 2578 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2579 return false; 2580 } 2581 return true; 2582 }; 2583 2584 // Prune instructions from RHS Deps that are dependencies of unrelated 2585 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2586 // arbitrary and just meant to cap the how much time we spend in the pruning 2587 // loop. Its highly unlikely to come into affect. 2588 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2589 // Stop after a certain point. No incorrectness from including too many 2590 // instructions. 2591 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2592 const Instruction *ToDrop = nullptr; 2593 for (const auto &InsPair : RhsDeps) { 2594 if (!ShouldCountInsn(InsPair.first)) { 2595 ToDrop = InsPair.first; 2596 break; 2597 } 2598 } 2599 if (ToDrop == nullptr) 2600 break; 2601 RhsDeps.erase(ToDrop); 2602 } 2603 2604 for (const auto &InsPair : RhsDeps) { 2605 // Finally accumulate latency that we can only attribute to computing the 2606 // RHS condition. Use latency because we are essentially trying to calculate 2607 // the cost of the dependency chain. 2608 // Possible TODO: We could try to estimate ILP and make this more precise. 2609 CostOfIncluding += 2610 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2611 2612 if (CostOfIncluding > CostThresh) 2613 return false; 2614 } 2615 return true; 2616 } 2617 2618 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2619 MachineBasicBlock *TBB, 2620 MachineBasicBlock *FBB, 2621 MachineBasicBlock *CurBB, 2622 MachineBasicBlock *SwitchBB, 2623 Instruction::BinaryOps Opc, 2624 BranchProbability TProb, 2625 BranchProbability FProb, 2626 bool InvertCond) { 2627 // Skip over not part of the tree and remember to invert op and operands at 2628 // next level. 2629 Value *NotCond; 2630 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2631 InBlock(NotCond, CurBB->getBasicBlock())) { 2632 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2633 !InvertCond); 2634 return; 2635 } 2636 2637 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2638 const Value *BOpOp0, *BOpOp1; 2639 // Compute the effective opcode for Cond, taking into account whether it needs 2640 // to be inverted, e.g. 2641 // and (not (or A, B)), C 2642 // gets lowered as 2643 // and (and (not A, not B), C) 2644 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2645 if (BOp) { 2646 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2647 ? Instruction::And 2648 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2649 ? Instruction::Or 2650 : (Instruction::BinaryOps)0); 2651 if (InvertCond) { 2652 if (BOpc == Instruction::And) 2653 BOpc = Instruction::Or; 2654 else if (BOpc == Instruction::Or) 2655 BOpc = Instruction::And; 2656 } 2657 } 2658 2659 // If this node is not part of the or/and tree, emit it as a branch. 2660 // Note that all nodes in the tree should have same opcode. 2661 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2662 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2663 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2664 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2665 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2666 TProb, FProb, InvertCond); 2667 return; 2668 } 2669 2670 // Create TmpBB after CurBB. 2671 MachineFunction::iterator BBI(CurBB); 2672 MachineFunction &MF = DAG.getMachineFunction(); 2673 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2674 CurBB->getParent()->insert(++BBI, TmpBB); 2675 2676 if (Opc == Instruction::Or) { 2677 // Codegen X | Y as: 2678 // BB1: 2679 // jmp_if_X TBB 2680 // jmp TmpBB 2681 // TmpBB: 2682 // jmp_if_Y TBB 2683 // jmp FBB 2684 // 2685 2686 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2687 // The requirement is that 2688 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2689 // = TrueProb for original BB. 2690 // Assuming the original probabilities are A and B, one choice is to set 2691 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2692 // A/(1+B) and 2B/(1+B). This choice assumes that 2693 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2694 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2695 // TmpBB, but the math is more complicated. 2696 2697 auto NewTrueProb = TProb / 2; 2698 auto NewFalseProb = TProb / 2 + FProb; 2699 // Emit the LHS condition. 2700 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2701 NewFalseProb, InvertCond); 2702 2703 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2704 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2705 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2706 // Emit the RHS condition into TmpBB. 2707 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2708 Probs[1], InvertCond); 2709 } else { 2710 assert(Opc == Instruction::And && "Unknown merge op!"); 2711 // Codegen X & Y as: 2712 // BB1: 2713 // jmp_if_X TmpBB 2714 // jmp FBB 2715 // TmpBB: 2716 // jmp_if_Y TBB 2717 // jmp FBB 2718 // 2719 // This requires creation of TmpBB after CurBB. 2720 2721 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2722 // The requirement is that 2723 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2724 // = FalseProb for original BB. 2725 // Assuming the original probabilities are A and B, one choice is to set 2726 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2727 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2728 // TrueProb for BB1 * FalseProb for TmpBB. 2729 2730 auto NewTrueProb = TProb + FProb / 2; 2731 auto NewFalseProb = FProb / 2; 2732 // Emit the LHS condition. 2733 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2734 NewFalseProb, InvertCond); 2735 2736 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2737 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2738 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2739 // Emit the RHS condition into TmpBB. 2740 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2741 Probs[1], InvertCond); 2742 } 2743 } 2744 2745 /// If the set of cases should be emitted as a series of branches, return true. 2746 /// If we should emit this as a bunch of and/or'd together conditions, return 2747 /// false. 2748 bool 2749 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2750 if (Cases.size() != 2) return true; 2751 2752 // If this is two comparisons of the same values or'd or and'd together, they 2753 // will get folded into a single comparison, so don't emit two blocks. 2754 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2755 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2756 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2757 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2758 return false; 2759 } 2760 2761 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2762 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2763 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2764 Cases[0].CC == Cases[1].CC && 2765 isa<Constant>(Cases[0].CmpRHS) && 2766 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2767 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2768 return false; 2769 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2770 return false; 2771 } 2772 2773 return true; 2774 } 2775 2776 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2777 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2778 2779 // Update machine-CFG edges. 2780 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0)); 2781 2782 if (I.isUnconditional()) { 2783 // Update machine-CFG edges. 2784 BrMBB->addSuccessor(Succ0MBB); 2785 2786 // If this is not a fall-through branch or optimizations are switched off, 2787 // emit the branch. 2788 if (Succ0MBB != NextBlock(BrMBB) || 2789 TM.getOptLevel() == CodeGenOptLevel::None) { 2790 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2791 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2792 setValue(&I, Br); 2793 DAG.setRoot(Br); 2794 } 2795 2796 return; 2797 } 2798 2799 // If this condition is one of the special cases we handle, do special stuff 2800 // now. 2801 const Value *CondVal = I.getCondition(); 2802 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1)); 2803 2804 // If this is a series of conditions that are or'd or and'd together, emit 2805 // this as a sequence of branches instead of setcc's with and/or operations. 2806 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2807 // unpredictable branches, and vector extracts because those jumps are likely 2808 // expensive for any target), this should improve performance. 2809 // For example, instead of something like: 2810 // cmp A, B 2811 // C = seteq 2812 // cmp D, E 2813 // F = setle 2814 // or C, F 2815 // jnz foo 2816 // Emit: 2817 // cmp A, B 2818 // je foo 2819 // cmp D, E 2820 // jle foo 2821 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable); 2822 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2823 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2824 BOp->hasOneUse() && !IsUnpredictable) { 2825 Value *Vec; 2826 const Value *BOp0, *BOp1; 2827 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2828 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2829 Opcode = Instruction::And; 2830 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2831 Opcode = Instruction::Or; 2832 2833 if (Opcode && 2834 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2835 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2836 !shouldKeepJumpConditionsTogether( 2837 FuncInfo, I, Opcode, BOp0, BOp1, 2838 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2839 Opcode, BOp0, BOp1))) { 2840 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2841 getEdgeProbability(BrMBB, Succ0MBB), 2842 getEdgeProbability(BrMBB, Succ1MBB), 2843 /*InvertCond=*/false); 2844 // If the compares in later blocks need to use values not currently 2845 // exported from this block, export them now. This block should always 2846 // be the first entry. 2847 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2848 2849 // Allow some cases to be rejected. 2850 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2851 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2852 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2853 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2854 } 2855 2856 // Emit the branch for this block. 2857 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2858 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2859 return; 2860 } 2861 2862 // Okay, we decided not to do this, remove any inserted MBB's and clear 2863 // SwitchCases. 2864 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2865 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2866 2867 SL->SwitchCases.clear(); 2868 } 2869 } 2870 2871 // Create a CaseBlock record representing this branch. 2872 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2873 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(), 2874 BranchProbability::getUnknown(), BranchProbability::getUnknown(), 2875 IsUnpredictable); 2876 2877 // Use visitSwitchCase to actually insert the fast branch sequence for this 2878 // cond branch. 2879 visitSwitchCase(CB, BrMBB); 2880 } 2881 2882 /// visitSwitchCase - Emits the necessary code to represent a single node in 2883 /// the binary search tree resulting from lowering a switch instruction. 2884 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2885 MachineBasicBlock *SwitchBB) { 2886 SDValue Cond; 2887 SDValue CondLHS = getValue(CB.CmpLHS); 2888 SDLoc dl = CB.DL; 2889 2890 if (CB.CC == ISD::SETTRUE) { 2891 // Branch or fall through to TrueBB. 2892 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2893 SwitchBB->normalizeSuccProbs(); 2894 if (CB.TrueBB != NextBlock(SwitchBB)) { 2895 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2896 DAG.getBasicBlock(CB.TrueBB))); 2897 } 2898 return; 2899 } 2900 2901 auto &TLI = DAG.getTargetLoweringInfo(); 2902 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2903 2904 // Build the setcc now. 2905 if (!CB.CmpMHS) { 2906 // Fold "(X == true)" to X and "(X == false)" to !X to 2907 // handle common cases produced by branch lowering. 2908 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2909 CB.CC == ISD::SETEQ) 2910 Cond = CondLHS; 2911 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2912 CB.CC == ISD::SETEQ) { 2913 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2914 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2915 } else { 2916 SDValue CondRHS = getValue(CB.CmpRHS); 2917 2918 // If a pointer's DAG type is larger than its memory type then the DAG 2919 // values are zero-extended. This breaks signed comparisons so truncate 2920 // back to the underlying type before doing the compare. 2921 if (CondLHS.getValueType() != MemVT) { 2922 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2923 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2924 } 2925 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2926 } 2927 } else { 2928 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2929 2930 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2931 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2932 2933 SDValue CmpOp = getValue(CB.CmpMHS); 2934 EVT VT = CmpOp.getValueType(); 2935 2936 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2937 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2938 ISD::SETLE); 2939 } else { 2940 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2941 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2942 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2943 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2944 } 2945 } 2946 2947 // Update successor info 2948 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2949 // TrueBB and FalseBB are always different unless the incoming IR is 2950 // degenerate. This only happens when running llc on weird IR. 2951 if (CB.TrueBB != CB.FalseBB) 2952 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2953 SwitchBB->normalizeSuccProbs(); 2954 2955 // If the lhs block is the next block, invert the condition so that we can 2956 // fall through to the lhs instead of the rhs block. 2957 if (CB.TrueBB == NextBlock(SwitchBB)) { 2958 std::swap(CB.TrueBB, CB.FalseBB); 2959 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2960 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2961 } 2962 2963 SDNodeFlags Flags; 2964 Flags.setUnpredictable(CB.IsUnpredictable); 2965 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(), 2966 Cond, DAG.getBasicBlock(CB.TrueBB), Flags); 2967 2968 setValue(CurInst, BrCond); 2969 2970 // Insert the false branch. Do this even if it's a fall through branch, 2971 // this makes it easier to do DAG optimizations which require inverting 2972 // the branch condition. 2973 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2974 DAG.getBasicBlock(CB.FalseBB)); 2975 2976 DAG.setRoot(BrCond); 2977 } 2978 2979 /// visitJumpTable - Emit JumpTable node in the current MBB 2980 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2981 // Emit the code for the jump table 2982 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2983 assert(JT.Reg && "Should lower JT Header first!"); 2984 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout()); 2985 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2986 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2987 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2988 Index.getValue(1), Table, Index); 2989 DAG.setRoot(BrJumpTable); 2990 } 2991 2992 /// visitJumpTableHeader - This function emits necessary code to produce index 2993 /// in the JumpTable from switch case. 2994 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2995 JumpTableHeader &JTH, 2996 MachineBasicBlock *SwitchBB) { 2997 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2998 const SDLoc &dl = *JT.SL; 2999 3000 // Subtract the lowest switch case value from the value being switched on. 3001 SDValue SwitchOp = getValue(JTH.SValue); 3002 EVT VT = SwitchOp.getValueType(); 3003 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 3004 DAG.getConstant(JTH.First, dl, VT)); 3005 3006 // The SDNode we just created, which holds the value being switched on minus 3007 // the smallest case value, needs to be copied to a virtual register so it 3008 // can be used as an index into the jump table in a subsequent basic block. 3009 // This value may be smaller or larger than the target's pointer type, and 3010 // therefore require extension or truncating. 3011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3012 SwitchOp = 3013 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout())); 3014 3015 Register JumpTableReg = 3016 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout())); 3017 SDValue CopyTo = 3018 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp); 3019 JT.Reg = JumpTableReg; 3020 3021 if (!JTH.FallthroughUnreachable) { 3022 // Emit the range check for the jump table, and branch to the default block 3023 // for the switch statement if the value being switched on exceeds the 3024 // largest case in the switch. 3025 SDValue CMP = DAG.getSetCC( 3026 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3027 Sub.getValueType()), 3028 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3029 3030 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3031 MVT::Other, CopyTo, CMP, 3032 DAG.getBasicBlock(JT.Default)); 3033 3034 // Avoid emitting unnecessary branches to the next block. 3035 if (JT.MBB != NextBlock(SwitchBB)) 3036 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3037 DAG.getBasicBlock(JT.MBB)); 3038 3039 DAG.setRoot(BrCond); 3040 } else { 3041 // Avoid emitting unnecessary branches to the next block. 3042 if (JT.MBB != NextBlock(SwitchBB)) 3043 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3044 DAG.getBasicBlock(JT.MBB))); 3045 else 3046 DAG.setRoot(CopyTo); 3047 } 3048 } 3049 3050 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3051 /// variable if there exists one. 3052 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3053 SDValue &Chain) { 3054 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3055 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3056 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3057 MachineFunction &MF = DAG.getMachineFunction(); 3058 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3059 MachineSDNode *Node = 3060 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3061 if (Global) { 3062 MachinePointerInfo MPInfo(Global); 3063 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3064 MachineMemOperand::MODereferenceable; 3065 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3066 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3067 DAG.getEVTAlign(PtrTy)); 3068 DAG.setNodeMemRefs(Node, {MemRef}); 3069 } 3070 if (PtrTy != PtrMemTy) 3071 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3072 return SDValue(Node, 0); 3073 } 3074 3075 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3076 /// tail spliced into a stack protector check success bb. 3077 /// 3078 /// For a high level explanation of how this fits into the stack protector 3079 /// generation see the comment on the declaration of class 3080 /// StackProtectorDescriptor. 3081 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3082 MachineBasicBlock *ParentBB) { 3083 3084 // First create the loads to the guard/stack slot for the comparison. 3085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3086 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3087 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3088 3089 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3090 int FI = MFI.getStackProtectorIndex(); 3091 3092 SDValue Guard; 3093 SDLoc dl = getCurSDLoc(); 3094 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3095 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3096 Align Align = 3097 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3098 3099 // Generate code to load the content of the guard slot. 3100 SDValue GuardVal = DAG.getLoad( 3101 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3102 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3103 MachineMemOperand::MOVolatile); 3104 3105 if (TLI.useStackGuardXorFP()) 3106 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3107 3108 // Retrieve guard check function, nullptr if instrumentation is inlined. 3109 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3110 // The target provides a guard check function to validate the guard value. 3111 // Generate a call to that function with the content of the guard slot as 3112 // argument. 3113 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3114 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3115 3116 TargetLowering::ArgListTy Args; 3117 TargetLowering::ArgListEntry Entry; 3118 Entry.Node = GuardVal; 3119 Entry.Ty = FnTy->getParamType(0); 3120 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3121 Entry.IsInReg = true; 3122 Args.push_back(Entry); 3123 3124 TargetLowering::CallLoweringInfo CLI(DAG); 3125 CLI.setDebugLoc(getCurSDLoc()) 3126 .setChain(DAG.getEntryNode()) 3127 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3128 getValue(GuardCheckFn), std::move(Args)); 3129 3130 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3131 DAG.setRoot(Result.second); 3132 return; 3133 } 3134 3135 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3136 // Otherwise, emit a volatile load to retrieve the stack guard value. 3137 SDValue Chain = DAG.getEntryNode(); 3138 if (TLI.useLoadStackGuardNode(M)) { 3139 Guard = getLoadStackGuard(DAG, dl, Chain); 3140 } else { 3141 const Value *IRGuard = TLI.getSDagStackGuard(M); 3142 SDValue GuardPtr = getValue(IRGuard); 3143 3144 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3145 MachinePointerInfo(IRGuard, 0), Align, 3146 MachineMemOperand::MOVolatile); 3147 } 3148 3149 // Perform the comparison via a getsetcc. 3150 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3151 *DAG.getContext(), 3152 Guard.getValueType()), 3153 Guard, GuardVal, ISD::SETNE); 3154 3155 // If the guard/stackslot do not equal, branch to failure MBB. 3156 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3157 MVT::Other, GuardVal.getOperand(0), 3158 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3159 // Otherwise branch to success MBB. 3160 SDValue Br = DAG.getNode(ISD::BR, dl, 3161 MVT::Other, BrCond, 3162 DAG.getBasicBlock(SPD.getSuccessMBB())); 3163 3164 DAG.setRoot(Br); 3165 } 3166 3167 /// Codegen the failure basic block for a stack protector check. 3168 /// 3169 /// A failure stack protector machine basic block consists simply of a call to 3170 /// __stack_chk_fail(). 3171 /// 3172 /// For a high level explanation of how this fits into the stack protector 3173 /// generation see the comment on the declaration of class 3174 /// StackProtectorDescriptor. 3175 void 3176 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3178 TargetLowering::MakeLibCallOptions CallOptions; 3179 CallOptions.setDiscardResult(true); 3180 SDValue Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, 3181 MVT::isVoid, {}, CallOptions, getCurSDLoc()) 3182 .second; 3183 3184 // Emit a trap instruction if we are required to do so. 3185 const TargetOptions &TargetOpts = DAG.getTarget().Options; 3186 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn) 3187 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3188 3189 DAG.setRoot(Chain); 3190 } 3191 3192 /// visitBitTestHeader - This function emits necessary code to produce value 3193 /// suitable for "bit tests" 3194 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3195 MachineBasicBlock *SwitchBB) { 3196 SDLoc dl = getCurSDLoc(); 3197 3198 // Subtract the minimum value. 3199 SDValue SwitchOp = getValue(B.SValue); 3200 EVT VT = SwitchOp.getValueType(); 3201 SDValue RangeSub = 3202 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3203 3204 // Determine the type of the test operands. 3205 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3206 bool UsePtrType = false; 3207 if (!TLI.isTypeLegal(VT)) { 3208 UsePtrType = true; 3209 } else { 3210 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3211 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3212 // Switch table case range are encoded into series of masks. 3213 // Just use pointer type, it's guaranteed to fit. 3214 UsePtrType = true; 3215 break; 3216 } 3217 } 3218 SDValue Sub = RangeSub; 3219 if (UsePtrType) { 3220 VT = TLI.getPointerTy(DAG.getDataLayout()); 3221 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3222 } 3223 3224 B.RegVT = VT.getSimpleVT(); 3225 B.Reg = FuncInfo.CreateReg(B.RegVT); 3226 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3227 3228 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3229 3230 if (!B.FallthroughUnreachable) 3231 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3232 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3233 SwitchBB->normalizeSuccProbs(); 3234 3235 SDValue Root = CopyTo; 3236 if (!B.FallthroughUnreachable) { 3237 // Conditional branch to the default block. 3238 SDValue RangeCmp = DAG.getSetCC(dl, 3239 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3240 RangeSub.getValueType()), 3241 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3242 ISD::SETUGT); 3243 3244 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3245 DAG.getBasicBlock(B.Default)); 3246 } 3247 3248 // Avoid emitting unnecessary branches to the next block. 3249 if (MBB != NextBlock(SwitchBB)) 3250 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3251 3252 DAG.setRoot(Root); 3253 } 3254 3255 /// visitBitTestCase - this function produces one "bit test" 3256 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3257 MachineBasicBlock *NextMBB, 3258 BranchProbability BranchProbToNext, 3259 Register Reg, BitTestCase &B, 3260 MachineBasicBlock *SwitchBB) { 3261 SDLoc dl = getCurSDLoc(); 3262 MVT VT = BB.RegVT; 3263 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3264 SDValue Cmp; 3265 unsigned PopCount = llvm::popcount(B.Mask); 3266 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3267 if (PopCount == 1) { 3268 // Testing for a single bit; just compare the shift count with what it 3269 // would need to be to shift a 1 bit in that position. 3270 Cmp = DAG.getSetCC( 3271 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3272 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3273 ISD::SETEQ); 3274 } else if (PopCount == BB.Range) { 3275 // There is only one zero bit in the range, test for it directly. 3276 Cmp = DAG.getSetCC( 3277 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3278 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3279 } else { 3280 // Make desired shift 3281 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3282 DAG.getConstant(1, dl, VT), ShiftOp); 3283 3284 // Emit bit tests and jumps 3285 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3286 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3287 Cmp = DAG.getSetCC( 3288 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3289 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3290 } 3291 3292 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3293 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3294 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3295 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3296 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3297 // one as they are relative probabilities (and thus work more like weights), 3298 // and hence we need to normalize them to let the sum of them become one. 3299 SwitchBB->normalizeSuccProbs(); 3300 3301 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3302 MVT::Other, getControlRoot(), 3303 Cmp, DAG.getBasicBlock(B.TargetBB)); 3304 3305 // Avoid emitting unnecessary branches to the next block. 3306 if (NextMBB != NextBlock(SwitchBB)) 3307 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3308 DAG.getBasicBlock(NextMBB)); 3309 3310 DAG.setRoot(BrAnd); 3311 } 3312 3313 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3314 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3315 3316 // Retrieve successors. Look through artificial IR level blocks like 3317 // catchswitch for successors. 3318 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0)); 3319 const BasicBlock *EHPadBB = I.getSuccessor(1); 3320 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB); 3321 3322 // Deopt and ptrauth bundles are lowered in helper functions, and we don't 3323 // have to do anything here to lower funclet bundles. 3324 assert(!I.hasOperandBundlesOtherThan( 3325 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3326 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3327 LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth, 3328 LLVMContext::OB_clang_arc_attachedcall}) && 3329 "Cannot lower invokes with arbitrary operand bundles yet!"); 3330 3331 const Value *Callee(I.getCalledOperand()); 3332 const Function *Fn = dyn_cast<Function>(Callee); 3333 if (isa<InlineAsm>(Callee)) 3334 visitInlineAsm(I, EHPadBB); 3335 else if (Fn && Fn->isIntrinsic()) { 3336 switch (Fn->getIntrinsicID()) { 3337 default: 3338 llvm_unreachable("Cannot invoke this intrinsic"); 3339 case Intrinsic::donothing: 3340 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3341 case Intrinsic::seh_try_begin: 3342 case Intrinsic::seh_scope_begin: 3343 case Intrinsic::seh_try_end: 3344 case Intrinsic::seh_scope_end: 3345 if (EHPadMBB) 3346 // a block referenced by EH table 3347 // so dtor-funclet not removed by opts 3348 EHPadMBB->setMachineBlockAddressTaken(); 3349 break; 3350 case Intrinsic::experimental_patchpoint_void: 3351 case Intrinsic::experimental_patchpoint: 3352 visitPatchpoint(I, EHPadBB); 3353 break; 3354 case Intrinsic::experimental_gc_statepoint: 3355 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3356 break; 3357 case Intrinsic::wasm_rethrow: { 3358 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3359 // special because it can be invoked, so we manually lower it to a DAG 3360 // node here. 3361 SmallVector<SDValue, 8> Ops; 3362 Ops.push_back(getControlRoot()); // inchain for the terminator node 3363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3364 Ops.push_back( 3365 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3366 TLI.getPointerTy(DAG.getDataLayout()))); 3367 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3368 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3369 break; 3370 } 3371 } 3372 } else if (I.hasDeoptState()) { 3373 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3374 // Eventually we will support lowering the @llvm.experimental.deoptimize 3375 // intrinsic, and right now there are no plans to support other intrinsics 3376 // with deopt state. 3377 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3378 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 3379 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB); 3380 } else { 3381 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3382 } 3383 3384 // If the value of the invoke is used outside of its defining block, make it 3385 // available as a virtual register. 3386 // We already took care of the exported value for the statepoint instruction 3387 // during call to the LowerStatepoint. 3388 if (!isa<GCStatepointInst>(I)) { 3389 CopyToExportRegsIfNeeded(&I); 3390 } 3391 3392 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3393 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3394 BranchProbability EHPadBBProb = 3395 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3396 : BranchProbability::getZero(); 3397 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3398 3399 // Update successor info. 3400 addSuccessorWithProb(InvokeMBB, Return); 3401 for (auto &UnwindDest : UnwindDests) { 3402 UnwindDest.first->setIsEHPad(); 3403 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3404 } 3405 InvokeMBB->normalizeSuccProbs(); 3406 3407 // Drop into normal successor. 3408 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3409 DAG.getBasicBlock(Return))); 3410 } 3411 3412 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3413 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3414 3415 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3416 // have to do anything here to lower funclet bundles. 3417 assert(!I.hasOperandBundlesOtherThan( 3418 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3419 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3420 3421 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3422 visitInlineAsm(I); 3423 CopyToExportRegsIfNeeded(&I); 3424 3425 // Retrieve successors. 3426 SmallPtrSet<BasicBlock *, 8> Dests; 3427 Dests.insert(I.getDefaultDest()); 3428 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest()); 3429 3430 // Update successor info. 3431 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3432 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3433 BasicBlock *Dest = I.getIndirectDest(i); 3434 MachineBasicBlock *Target = FuncInfo.getMBB(Dest); 3435 Target->setIsInlineAsmBrIndirectTarget(); 3436 Target->setMachineBlockAddressTaken(); 3437 Target->setLabelMustBeEmitted(); 3438 // Don't add duplicate machine successors. 3439 if (Dests.insert(Dest).second) 3440 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3441 } 3442 CallBrMBB->normalizeSuccProbs(); 3443 3444 // Drop into default successor. 3445 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3446 MVT::Other, getControlRoot(), 3447 DAG.getBasicBlock(Return))); 3448 } 3449 3450 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3451 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3452 } 3453 3454 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3455 assert(FuncInfo.MBB->isEHPad() && 3456 "Call to landingpad not in landing pad!"); 3457 3458 // If there aren't registers to copy the values into (e.g., during SjLj 3459 // exceptions), then don't bother to create these DAG nodes. 3460 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3461 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3462 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3463 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3464 return; 3465 3466 // If landingpad's return type is token type, we don't create DAG nodes 3467 // for its exception pointer and selector value. The extraction of exception 3468 // pointer or selector value from token type landingpads is not currently 3469 // supported. 3470 if (LP.getType()->isTokenTy()) 3471 return; 3472 3473 SmallVector<EVT, 2> ValueVTs; 3474 SDLoc dl = getCurSDLoc(); 3475 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3476 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3477 3478 // Get the two live-in registers as SDValues. The physregs have already been 3479 // copied into virtual registers. 3480 SDValue Ops[2]; 3481 if (FuncInfo.ExceptionPointerVirtReg) { 3482 Ops[0] = DAG.getZExtOrTrunc( 3483 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3484 FuncInfo.ExceptionPointerVirtReg, 3485 TLI.getPointerTy(DAG.getDataLayout())), 3486 dl, ValueVTs[0]); 3487 } else { 3488 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3489 } 3490 Ops[1] = DAG.getZExtOrTrunc( 3491 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3492 FuncInfo.ExceptionSelectorVirtReg, 3493 TLI.getPointerTy(DAG.getDataLayout())), 3494 dl, ValueVTs[1]); 3495 3496 // Merge into one. 3497 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3498 DAG.getVTList(ValueVTs), Ops); 3499 setValue(&LP, Res); 3500 } 3501 3502 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3503 MachineBasicBlock *Last) { 3504 // Update JTCases. 3505 for (JumpTableBlock &JTB : SL->JTCases) 3506 if (JTB.first.HeaderBB == First) 3507 JTB.first.HeaderBB = Last; 3508 3509 // Update BitTestCases. 3510 for (BitTestBlock &BTB : SL->BitTestCases) 3511 if (BTB.Parent == First) 3512 BTB.Parent = Last; 3513 } 3514 3515 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3516 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3517 3518 // Update machine-CFG edges with unique successors. 3519 SmallSet<BasicBlock*, 32> Done; 3520 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3521 BasicBlock *BB = I.getSuccessor(i); 3522 bool Inserted = Done.insert(BB).second; 3523 if (!Inserted) 3524 continue; 3525 3526 MachineBasicBlock *Succ = FuncInfo.getMBB(BB); 3527 addSuccessorWithProb(IndirectBrMBB, Succ); 3528 } 3529 IndirectBrMBB->normalizeSuccProbs(); 3530 3531 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3532 MVT::Other, getControlRoot(), 3533 getValue(I.getAddress()))); 3534 } 3535 3536 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3537 if (!DAG.getTarget().Options.TrapUnreachable) 3538 return; 3539 3540 // We may be able to ignore unreachable behind a noreturn call. 3541 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode()); 3542 Call && Call->doesNotReturn()) { 3543 if (DAG.getTarget().Options.NoTrapAfterNoreturn) 3544 return; 3545 // Do not emit an additional trap instruction. 3546 if (Call->isNonContinuableTrap()) 3547 return; 3548 } 3549 3550 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3551 } 3552 3553 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3554 SDNodeFlags Flags; 3555 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3556 Flags.copyFMF(*FPOp); 3557 3558 SDValue Op = getValue(I.getOperand(0)); 3559 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3560 Op, Flags); 3561 setValue(&I, UnNodeValue); 3562 } 3563 3564 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3565 SDNodeFlags Flags; 3566 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3567 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3568 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3569 } 3570 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3571 Flags.setExact(ExactOp->isExact()); 3572 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3573 Flags.setDisjoint(DisjointOp->isDisjoint()); 3574 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3575 Flags.copyFMF(*FPOp); 3576 3577 SDValue Op1 = getValue(I.getOperand(0)); 3578 SDValue Op2 = getValue(I.getOperand(1)); 3579 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3580 Op1, Op2, Flags); 3581 setValue(&I, BinNodeValue); 3582 } 3583 3584 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3585 SDValue Op1 = getValue(I.getOperand(0)); 3586 SDValue Op2 = getValue(I.getOperand(1)); 3587 3588 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3589 Op1.getValueType(), DAG.getDataLayout()); 3590 3591 // Coerce the shift amount to the right type if we can. This exposes the 3592 // truncate or zext to optimization early. 3593 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3594 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3595 "Unexpected shift type"); 3596 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3597 } 3598 3599 bool nuw = false; 3600 bool nsw = false; 3601 bool exact = false; 3602 3603 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3604 3605 if (const OverflowingBinaryOperator *OFBinOp = 3606 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3607 nuw = OFBinOp->hasNoUnsignedWrap(); 3608 nsw = OFBinOp->hasNoSignedWrap(); 3609 } 3610 if (const PossiblyExactOperator *ExactOp = 3611 dyn_cast<const PossiblyExactOperator>(&I)) 3612 exact = ExactOp->isExact(); 3613 } 3614 SDNodeFlags Flags; 3615 Flags.setExact(exact); 3616 Flags.setNoSignedWrap(nsw); 3617 Flags.setNoUnsignedWrap(nuw); 3618 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3619 Flags); 3620 setValue(&I, Res); 3621 } 3622 3623 void SelectionDAGBuilder::visitSDiv(const User &I) { 3624 SDValue Op1 = getValue(I.getOperand(0)); 3625 SDValue Op2 = getValue(I.getOperand(1)); 3626 3627 SDNodeFlags Flags; 3628 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3629 cast<PossiblyExactOperator>(&I)->isExact()); 3630 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3631 Op2, Flags)); 3632 } 3633 3634 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) { 3635 ICmpInst::Predicate predicate = I.getPredicate(); 3636 SDValue Op1 = getValue(I.getOperand(0)); 3637 SDValue Op2 = getValue(I.getOperand(1)); 3638 ISD::CondCode Opcode = getICmpCondCode(predicate); 3639 3640 auto &TLI = DAG.getTargetLoweringInfo(); 3641 EVT MemVT = 3642 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3643 3644 // If a pointer's DAG type is larger than its memory type then the DAG values 3645 // are zero-extended. This breaks signed comparisons so truncate back to the 3646 // underlying type before doing the compare. 3647 if (Op1.getValueType() != MemVT) { 3648 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3649 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3650 } 3651 3652 SDNodeFlags Flags; 3653 Flags.setSameSign(I.hasSameSign()); 3654 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3655 3656 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3657 I.getType()); 3658 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3659 } 3660 3661 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) { 3662 FCmpInst::Predicate predicate = I.getPredicate(); 3663 SDValue Op1 = getValue(I.getOperand(0)); 3664 SDValue Op2 = getValue(I.getOperand(1)); 3665 3666 ISD::CondCode Condition = getFCmpCondCode(predicate); 3667 auto *FPMO = cast<FPMathOperator>(&I); 3668 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3669 Condition = getFCmpCodeWithoutNaN(Condition); 3670 3671 SDNodeFlags Flags; 3672 Flags.copyFMF(*FPMO); 3673 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3674 3675 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3676 I.getType()); 3677 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3678 } 3679 3680 // Check if the condition of the select has one use or two users that are both 3681 // selects with the same condition. 3682 static bool hasOnlySelectUsers(const Value *Cond) { 3683 return llvm::all_of(Cond->users(), [](const Value *V) { 3684 return isa<SelectInst>(V); 3685 }); 3686 } 3687 3688 void SelectionDAGBuilder::visitSelect(const User &I) { 3689 SmallVector<EVT, 4> ValueVTs; 3690 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3691 ValueVTs); 3692 unsigned NumValues = ValueVTs.size(); 3693 if (NumValues == 0) return; 3694 3695 SmallVector<SDValue, 4> Values(NumValues); 3696 SDValue Cond = getValue(I.getOperand(0)); 3697 SDValue LHSVal = getValue(I.getOperand(1)); 3698 SDValue RHSVal = getValue(I.getOperand(2)); 3699 SmallVector<SDValue, 1> BaseOps(1, Cond); 3700 ISD::NodeType OpCode = 3701 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3702 3703 bool IsUnaryAbs = false; 3704 bool Negate = false; 3705 3706 SDNodeFlags Flags; 3707 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3708 Flags.copyFMF(*FPOp); 3709 3710 Flags.setUnpredictable( 3711 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3712 3713 // Min/max matching is only viable if all output VTs are the same. 3714 if (all_equal(ValueVTs)) { 3715 EVT VT = ValueVTs[0]; 3716 LLVMContext &Ctx = *DAG.getContext(); 3717 auto &TLI = DAG.getTargetLoweringInfo(); 3718 3719 // We care about the legality of the operation after it has been type 3720 // legalized. 3721 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3722 VT = TLI.getTypeToTransformTo(Ctx, VT); 3723 3724 // If the vselect is legal, assume we want to leave this as a vector setcc + 3725 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3726 // min/max is legal on the scalar type. 3727 bool UseScalarMinMax = VT.isVector() && 3728 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3729 3730 // ValueTracking's select pattern matching does not account for -0.0, 3731 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3732 // -0.0 is less than +0.0. 3733 const Value *LHS, *RHS; 3734 auto SPR = matchSelectPattern(&I, LHS, RHS); 3735 ISD::NodeType Opc = ISD::DELETED_NODE; 3736 switch (SPR.Flavor) { 3737 case SPF_UMAX: Opc = ISD::UMAX; break; 3738 case SPF_UMIN: Opc = ISD::UMIN; break; 3739 case SPF_SMAX: Opc = ISD::SMAX; break; 3740 case SPF_SMIN: Opc = ISD::SMIN; break; 3741 case SPF_FMINNUM: 3742 switch (SPR.NaNBehavior) { 3743 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3744 case SPNB_RETURNS_NAN: break; 3745 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3746 case SPNB_RETURNS_ANY: 3747 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3748 (UseScalarMinMax && 3749 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3750 Opc = ISD::FMINNUM; 3751 break; 3752 } 3753 break; 3754 case SPF_FMAXNUM: 3755 switch (SPR.NaNBehavior) { 3756 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3757 case SPNB_RETURNS_NAN: break; 3758 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3759 case SPNB_RETURNS_ANY: 3760 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3761 (UseScalarMinMax && 3762 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3763 Opc = ISD::FMAXNUM; 3764 break; 3765 } 3766 break; 3767 case SPF_NABS: 3768 Negate = true; 3769 [[fallthrough]]; 3770 case SPF_ABS: 3771 IsUnaryAbs = true; 3772 Opc = ISD::ABS; 3773 break; 3774 default: break; 3775 } 3776 3777 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3778 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3779 (UseScalarMinMax && 3780 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3781 // If the underlying comparison instruction is used by any other 3782 // instruction, the consumed instructions won't be destroyed, so it is 3783 // not profitable to convert to a min/max. 3784 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3785 OpCode = Opc; 3786 LHSVal = getValue(LHS); 3787 RHSVal = getValue(RHS); 3788 BaseOps.clear(); 3789 } 3790 3791 if (IsUnaryAbs) { 3792 OpCode = Opc; 3793 LHSVal = getValue(LHS); 3794 BaseOps.clear(); 3795 } 3796 } 3797 3798 if (IsUnaryAbs) { 3799 for (unsigned i = 0; i != NumValues; ++i) { 3800 SDLoc dl = getCurSDLoc(); 3801 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3802 Values[i] = 3803 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3804 if (Negate) 3805 Values[i] = DAG.getNegative(Values[i], dl, VT); 3806 } 3807 } else { 3808 for (unsigned i = 0; i != NumValues; ++i) { 3809 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3810 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3811 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3812 Values[i] = DAG.getNode( 3813 OpCode, getCurSDLoc(), 3814 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3815 } 3816 } 3817 3818 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3819 DAG.getVTList(ValueVTs), Values)); 3820 } 3821 3822 void SelectionDAGBuilder::visitTrunc(const User &I) { 3823 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3824 SDValue N = getValue(I.getOperand(0)); 3825 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3826 I.getType()); 3827 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3828 } 3829 3830 void SelectionDAGBuilder::visitZExt(const User &I) { 3831 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3832 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3833 SDValue N = getValue(I.getOperand(0)); 3834 auto &TLI = DAG.getTargetLoweringInfo(); 3835 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3836 3837 SDNodeFlags Flags; 3838 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3839 Flags.setNonNeg(PNI->hasNonNeg()); 3840 3841 // Eagerly use nonneg information to canonicalize towards sign_extend if 3842 // that is the target's preference. 3843 // TODO: Let the target do this later. 3844 if (Flags.hasNonNeg() && 3845 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3846 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3847 return; 3848 } 3849 3850 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3851 } 3852 3853 void SelectionDAGBuilder::visitSExt(const User &I) { 3854 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3855 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3856 SDValue N = getValue(I.getOperand(0)); 3857 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3858 I.getType()); 3859 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3860 } 3861 3862 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3863 // FPTrunc is never a no-op cast, no need to check 3864 SDValue N = getValue(I.getOperand(0)); 3865 SDLoc dl = getCurSDLoc(); 3866 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3867 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3868 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3869 DAG.getTargetConstant( 3870 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3871 } 3872 3873 void SelectionDAGBuilder::visitFPExt(const User &I) { 3874 // FPExt is never a no-op cast, no need to check 3875 SDValue N = getValue(I.getOperand(0)); 3876 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3877 I.getType()); 3878 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3879 } 3880 3881 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3882 // FPToUI is never a no-op cast, no need to check 3883 SDValue N = getValue(I.getOperand(0)); 3884 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3885 I.getType()); 3886 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3887 } 3888 3889 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3890 // FPToSI is never a no-op cast, no need to check 3891 SDValue N = getValue(I.getOperand(0)); 3892 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3893 I.getType()); 3894 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3895 } 3896 3897 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3898 // UIToFP is never a no-op cast, no need to check 3899 SDValue N = getValue(I.getOperand(0)); 3900 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3901 I.getType()); 3902 SDNodeFlags Flags; 3903 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3904 Flags.setNonNeg(PNI->hasNonNeg()); 3905 3906 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3907 } 3908 3909 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3910 // SIToFP is never a no-op cast, no need to check 3911 SDValue N = getValue(I.getOperand(0)); 3912 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3913 I.getType()); 3914 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3915 } 3916 3917 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3918 // What to do depends on the size of the integer and the size of the pointer. 3919 // We can either truncate, zero extend, or no-op, accordingly. 3920 SDValue N = getValue(I.getOperand(0)); 3921 auto &TLI = DAG.getTargetLoweringInfo(); 3922 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3923 I.getType()); 3924 EVT PtrMemVT = 3925 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3926 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3927 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3928 setValue(&I, N); 3929 } 3930 3931 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3932 // What to do depends on the size of the integer and the size of the pointer. 3933 // We can either truncate, zero extend, or no-op, accordingly. 3934 SDValue N = getValue(I.getOperand(0)); 3935 auto &TLI = DAG.getTargetLoweringInfo(); 3936 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3937 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3938 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3939 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3940 setValue(&I, N); 3941 } 3942 3943 void SelectionDAGBuilder::visitBitCast(const User &I) { 3944 SDValue N = getValue(I.getOperand(0)); 3945 SDLoc dl = getCurSDLoc(); 3946 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3947 I.getType()); 3948 3949 // BitCast assures us that source and destination are the same size so this is 3950 // either a BITCAST or a no-op. 3951 if (DestVT != N.getValueType()) 3952 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3953 DestVT, N)); // convert types. 3954 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3955 // might fold any kind of constant expression to an integer constant and that 3956 // is not what we are looking for. Only recognize a bitcast of a genuine 3957 // constant integer as an opaque constant. 3958 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3959 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3960 /*isOpaque*/true)); 3961 else 3962 setValue(&I, N); // noop cast. 3963 } 3964 3965 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3966 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3967 const Value *SV = I.getOperand(0); 3968 SDValue N = getValue(SV); 3969 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3970 3971 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3972 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3973 3974 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3975 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3976 3977 setValue(&I, N); 3978 } 3979 3980 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3982 SDValue InVec = getValue(I.getOperand(0)); 3983 SDValue InVal = getValue(I.getOperand(1)); 3984 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3985 TLI.getVectorIdxTy(DAG.getDataLayout())); 3986 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3987 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3988 InVec, InVal, InIdx)); 3989 } 3990 3991 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3992 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3993 SDValue InVec = getValue(I.getOperand(0)); 3994 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3995 TLI.getVectorIdxTy(DAG.getDataLayout())); 3996 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3997 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3998 InVec, InIdx)); 3999 } 4000 4001 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 4002 SDValue Src1 = getValue(I.getOperand(0)); 4003 SDValue Src2 = getValue(I.getOperand(1)); 4004 ArrayRef<int> Mask; 4005 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 4006 Mask = SVI->getShuffleMask(); 4007 else 4008 Mask = cast<ConstantExpr>(I).getShuffleMask(); 4009 SDLoc DL = getCurSDLoc(); 4010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4011 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4012 EVT SrcVT = Src1.getValueType(); 4013 4014 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 4015 VT.isScalableVector()) { 4016 // Canonical splat form of first element of first input vector. 4017 SDValue FirstElt = 4018 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4019 DAG.getVectorIdxConstant(0, DL)); 4020 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4021 return; 4022 } 4023 4024 // For now, we only handle splats for scalable vectors. 4025 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4026 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4027 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4028 4029 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4030 unsigned MaskNumElts = Mask.size(); 4031 4032 if (SrcNumElts == MaskNumElts) { 4033 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4034 return; 4035 } 4036 4037 // Normalize the shuffle vector since mask and vector length don't match. 4038 if (SrcNumElts < MaskNumElts) { 4039 // Mask is longer than the source vectors. We can use concatenate vector to 4040 // make the mask and vectors lengths match. 4041 4042 if (MaskNumElts % SrcNumElts == 0) { 4043 // Mask length is a multiple of the source vector length. 4044 // Check if the shuffle is some kind of concatenation of the input 4045 // vectors. 4046 unsigned NumConcat = MaskNumElts / SrcNumElts; 4047 bool IsConcat = true; 4048 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4049 for (unsigned i = 0; i != MaskNumElts; ++i) { 4050 int Idx = Mask[i]; 4051 if (Idx < 0) 4052 continue; 4053 // Ensure the indices in each SrcVT sized piece are sequential and that 4054 // the same source is used for the whole piece. 4055 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4056 (ConcatSrcs[i / SrcNumElts] >= 0 && 4057 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4058 IsConcat = false; 4059 break; 4060 } 4061 // Remember which source this index came from. 4062 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4063 } 4064 4065 // The shuffle is concatenating multiple vectors together. Just emit 4066 // a CONCAT_VECTORS operation. 4067 if (IsConcat) { 4068 SmallVector<SDValue, 8> ConcatOps; 4069 for (auto Src : ConcatSrcs) { 4070 if (Src < 0) 4071 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4072 else if (Src == 0) 4073 ConcatOps.push_back(Src1); 4074 else 4075 ConcatOps.push_back(Src2); 4076 } 4077 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4078 return; 4079 } 4080 } 4081 4082 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4083 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4084 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4085 PaddedMaskNumElts); 4086 4087 // Pad both vectors with undefs to make them the same length as the mask. 4088 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4089 4090 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4091 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4092 MOps1[0] = Src1; 4093 MOps2[0] = Src2; 4094 4095 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4096 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4097 4098 // Readjust mask for new input vector length. 4099 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4100 for (unsigned i = 0; i != MaskNumElts; ++i) { 4101 int Idx = Mask[i]; 4102 if (Idx >= (int)SrcNumElts) 4103 Idx -= SrcNumElts - PaddedMaskNumElts; 4104 MappedOps[i] = Idx; 4105 } 4106 4107 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4108 4109 // If the concatenated vector was padded, extract a subvector with the 4110 // correct number of elements. 4111 if (MaskNumElts != PaddedMaskNumElts) 4112 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4113 DAG.getVectorIdxConstant(0, DL)); 4114 4115 setValue(&I, Result); 4116 return; 4117 } 4118 4119 assert(SrcNumElts > MaskNumElts); 4120 4121 // Analyze the access pattern of the vector to see if we can extract 4122 // two subvectors and do the shuffle. 4123 int StartIdx[2] = {-1, -1}; // StartIdx to extract from 4124 bool CanExtract = true; 4125 for (int Idx : Mask) { 4126 unsigned Input = 0; 4127 if (Idx < 0) 4128 continue; 4129 4130 if (Idx >= (int)SrcNumElts) { 4131 Input = 1; 4132 Idx -= SrcNumElts; 4133 } 4134 4135 // If all the indices come from the same MaskNumElts sized portion of 4136 // the sources we can use extract. Also make sure the extract wouldn't 4137 // extract past the end of the source. 4138 int NewStartIdx = alignDown(Idx, MaskNumElts); 4139 if (NewStartIdx + MaskNumElts > SrcNumElts || 4140 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4141 CanExtract = false; 4142 // Make sure we always update StartIdx as we use it to track if all 4143 // elements are undef. 4144 StartIdx[Input] = NewStartIdx; 4145 } 4146 4147 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4148 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4149 return; 4150 } 4151 if (CanExtract) { 4152 // Extract appropriate subvector and generate a vector shuffle 4153 for (unsigned Input = 0; Input < 2; ++Input) { 4154 SDValue &Src = Input == 0 ? Src1 : Src2; 4155 if (StartIdx[Input] < 0) 4156 Src = DAG.getUNDEF(VT); 4157 else { 4158 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4159 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4160 } 4161 } 4162 4163 // Calculate new mask. 4164 SmallVector<int, 8> MappedOps(Mask); 4165 for (int &Idx : MappedOps) { 4166 if (Idx >= (int)SrcNumElts) 4167 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4168 else if (Idx >= 0) 4169 Idx -= StartIdx[0]; 4170 } 4171 4172 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4173 return; 4174 } 4175 4176 // We can't use either concat vectors or extract subvectors so fall back to 4177 // replacing the shuffle with extract and build vector. 4178 // to insert and build vector. 4179 EVT EltVT = VT.getVectorElementType(); 4180 SmallVector<SDValue,8> Ops; 4181 for (int Idx : Mask) { 4182 SDValue Res; 4183 4184 if (Idx < 0) { 4185 Res = DAG.getUNDEF(EltVT); 4186 } else { 4187 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4188 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4189 4190 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4191 DAG.getVectorIdxConstant(Idx, DL)); 4192 } 4193 4194 Ops.push_back(Res); 4195 } 4196 4197 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4198 } 4199 4200 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4201 ArrayRef<unsigned> Indices = I.getIndices(); 4202 const Value *Op0 = I.getOperand(0); 4203 const Value *Op1 = I.getOperand(1); 4204 Type *AggTy = I.getType(); 4205 Type *ValTy = Op1->getType(); 4206 bool IntoUndef = isa<UndefValue>(Op0); 4207 bool FromUndef = isa<UndefValue>(Op1); 4208 4209 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4210 4211 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4212 SmallVector<EVT, 4> AggValueVTs; 4213 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4214 SmallVector<EVT, 4> ValValueVTs; 4215 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4216 4217 unsigned NumAggValues = AggValueVTs.size(); 4218 unsigned NumValValues = ValValueVTs.size(); 4219 SmallVector<SDValue, 4> Values(NumAggValues); 4220 4221 // Ignore an insertvalue that produces an empty object 4222 if (!NumAggValues) { 4223 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4224 return; 4225 } 4226 4227 SDValue Agg = getValue(Op0); 4228 unsigned i = 0; 4229 // Copy the beginning value(s) from the original aggregate. 4230 for (; i != LinearIndex; ++i) 4231 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4232 SDValue(Agg.getNode(), Agg.getResNo() + i); 4233 // Copy values from the inserted value(s). 4234 if (NumValValues) { 4235 SDValue Val = getValue(Op1); 4236 for (; i != LinearIndex + NumValValues; ++i) 4237 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4238 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4239 } 4240 // Copy remaining value(s) from the original aggregate. 4241 for (; i != NumAggValues; ++i) 4242 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4243 SDValue(Agg.getNode(), Agg.getResNo() + i); 4244 4245 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4246 DAG.getVTList(AggValueVTs), Values)); 4247 } 4248 4249 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4250 ArrayRef<unsigned> Indices = I.getIndices(); 4251 const Value *Op0 = I.getOperand(0); 4252 Type *AggTy = Op0->getType(); 4253 Type *ValTy = I.getType(); 4254 bool OutOfUndef = isa<UndefValue>(Op0); 4255 4256 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4257 4258 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4259 SmallVector<EVT, 4> ValValueVTs; 4260 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4261 4262 unsigned NumValValues = ValValueVTs.size(); 4263 4264 // Ignore a extractvalue that produces an empty object 4265 if (!NumValValues) { 4266 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4267 return; 4268 } 4269 4270 SmallVector<SDValue, 4> Values(NumValValues); 4271 4272 SDValue Agg = getValue(Op0); 4273 // Copy out the selected value(s). 4274 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4275 Values[i - LinearIndex] = 4276 OutOfUndef ? 4277 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4278 SDValue(Agg.getNode(), Agg.getResNo() + i); 4279 4280 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4281 DAG.getVTList(ValValueVTs), Values)); 4282 } 4283 4284 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4285 Value *Op0 = I.getOperand(0); 4286 // Note that the pointer operand may be a vector of pointers. Take the scalar 4287 // element which holds a pointer. 4288 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4289 SDValue N = getValue(Op0); 4290 SDLoc dl = getCurSDLoc(); 4291 auto &TLI = DAG.getTargetLoweringInfo(); 4292 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags(); 4293 4294 // Normalize Vector GEP - all scalar operands should be converted to the 4295 // splat vector. 4296 bool IsVectorGEP = I.getType()->isVectorTy(); 4297 ElementCount VectorElementCount = 4298 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4299 : ElementCount::getFixed(0); 4300 4301 if (IsVectorGEP && !N.getValueType().isVector()) { 4302 LLVMContext &Context = *DAG.getContext(); 4303 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4304 N = DAG.getSplat(VT, dl, N); 4305 } 4306 4307 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4308 GTI != E; ++GTI) { 4309 const Value *Idx = GTI.getOperand(); 4310 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4311 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4312 if (Field) { 4313 // N = N + Offset 4314 uint64_t Offset = 4315 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4316 4317 // In an inbounds GEP with an offset that is nonnegative even when 4318 // interpreted as signed, assume there is no unsigned overflow. 4319 SDNodeFlags Flags; 4320 if (NW.hasNoUnsignedWrap() || 4321 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap())) 4322 Flags |= SDNodeFlags::NoUnsignedWrap; 4323 4324 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4325 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4326 } 4327 } else { 4328 // IdxSize is the width of the arithmetic according to IR semantics. 4329 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4330 // (and fix up the result later). 4331 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4332 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4333 TypeSize ElementSize = 4334 GTI.getSequentialElementStride(DAG.getDataLayout()); 4335 // We intentionally mask away the high bits here; ElementSize may not 4336 // fit in IdxTy. 4337 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(), 4338 /*isSigned=*/false, /*implicitTrunc=*/true); 4339 bool ElementScalable = ElementSize.isScalable(); 4340 4341 // If this is a scalar constant or a splat vector of constants, 4342 // handle it quickly. 4343 const auto *C = dyn_cast<Constant>(Idx); 4344 if (C && isa<VectorType>(C->getType())) 4345 C = C->getSplatValue(); 4346 4347 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4348 if (CI && CI->isZero()) 4349 continue; 4350 if (CI && !ElementScalable) { 4351 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4352 LLVMContext &Context = *DAG.getContext(); 4353 SDValue OffsVal; 4354 if (IsVectorGEP) 4355 OffsVal = DAG.getConstant( 4356 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4357 else 4358 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4359 4360 // In an inbounds GEP with an offset that is nonnegative even when 4361 // interpreted as signed, assume there is no unsigned overflow. 4362 SDNodeFlags Flags; 4363 if (NW.hasNoUnsignedWrap() || 4364 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap())) 4365 Flags.setNoUnsignedWrap(true); 4366 4367 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4368 4369 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4370 continue; 4371 } 4372 4373 // N = N + Idx * ElementMul; 4374 SDValue IdxN = getValue(Idx); 4375 4376 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4377 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4378 VectorElementCount); 4379 IdxN = DAG.getSplat(VT, dl, IdxN); 4380 } 4381 4382 // If the index is smaller or larger than intptr_t, truncate or extend 4383 // it. 4384 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4385 4386 SDNodeFlags ScaleFlags; 4387 // The multiplication of an index by the type size does not wrap the 4388 // pointer index type in a signed sense (mul nsw). 4389 ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap()); 4390 4391 // The multiplication of an index by the type size does not wrap the 4392 // pointer index type in an unsigned sense (mul nuw). 4393 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap()); 4394 4395 if (ElementScalable) { 4396 EVT VScaleTy = N.getValueType().getScalarType(); 4397 SDValue VScale = DAG.getNode( 4398 ISD::VSCALE, dl, VScaleTy, 4399 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4400 if (IsVectorGEP) 4401 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4402 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale, 4403 ScaleFlags); 4404 } else { 4405 // If this is a multiply by a power of two, turn it into a shl 4406 // immediately. This is a very common case. 4407 if (ElementMul != 1) { 4408 if (ElementMul.isPowerOf2()) { 4409 unsigned Amt = ElementMul.logBase2(); 4410 IdxN = DAG.getNode(ISD::SHL, dl, N.getValueType(), IdxN, 4411 DAG.getConstant(Amt, dl, IdxN.getValueType()), 4412 ScaleFlags); 4413 } else { 4414 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4415 IdxN.getValueType()); 4416 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale, 4417 ScaleFlags); 4418 } 4419 } 4420 } 4421 4422 // The successive addition of the current address, truncated to the 4423 // pointer index type and interpreted as an unsigned number, and each 4424 // offset, also interpreted as an unsigned number, does not wrap the 4425 // pointer index type (add nuw). 4426 SDNodeFlags AddFlags; 4427 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap()); 4428 4429 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, IdxN, AddFlags); 4430 } 4431 } 4432 4433 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4434 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4435 if (IsVectorGEP) { 4436 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4437 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4438 } 4439 4440 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4441 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4442 4443 setValue(&I, N); 4444 } 4445 4446 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4447 // If this is a fixed sized alloca in the entry block of the function, 4448 // allocate it statically on the stack. 4449 if (FuncInfo.StaticAllocaMap.count(&I)) 4450 return; // getValue will auto-populate this. 4451 4452 SDLoc dl = getCurSDLoc(); 4453 Type *Ty = I.getAllocatedType(); 4454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4455 auto &DL = DAG.getDataLayout(); 4456 TypeSize TySize = DL.getTypeAllocSize(Ty); 4457 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4458 4459 SDValue AllocSize = getValue(I.getArraySize()); 4460 4461 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4462 if (AllocSize.getValueType() != IntPtr) 4463 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4464 4465 if (TySize.isScalable()) 4466 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4467 DAG.getVScale(dl, IntPtr, 4468 APInt(IntPtr.getScalarSizeInBits(), 4469 TySize.getKnownMinValue()))); 4470 else { 4471 SDValue TySizeValue = 4472 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4473 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4474 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4475 } 4476 4477 // Handle alignment. If the requested alignment is less than or equal to 4478 // the stack alignment, ignore it. If the size is greater than or equal to 4479 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4480 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4481 if (*Alignment <= StackAlign) 4482 Alignment = std::nullopt; 4483 4484 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4485 // Round the size of the allocation up to the stack alignment size 4486 // by add SA-1 to the size. This doesn't overflow because we're computing 4487 // an address inside an alloca. 4488 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4489 DAG.getConstant(StackAlignMask, dl, IntPtr), 4490 SDNodeFlags::NoUnsignedWrap); 4491 4492 // Mask out the low bits for alignment purposes. 4493 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4494 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr)); 4495 4496 SDValue Ops[] = { 4497 getRoot(), AllocSize, 4498 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4499 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4500 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4501 setValue(&I, DSA); 4502 DAG.setRoot(DSA.getValue(1)); 4503 4504 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4505 } 4506 4507 static const MDNode *getRangeMetadata(const Instruction &I) { 4508 // If !noundef is not present, then !range violation results in a poison 4509 // value rather than immediate undefined behavior. In theory, transferring 4510 // these annotations to SDAG is fine, but in practice there are key SDAG 4511 // transforms that are known not to be poison-safe, such as folding logical 4512 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4513 // also present. 4514 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4515 return nullptr; 4516 return I.getMetadata(LLVMContext::MD_range); 4517 } 4518 4519 static std::optional<ConstantRange> getRange(const Instruction &I) { 4520 if (const auto *CB = dyn_cast<CallBase>(&I)) { 4521 // see comment in getRangeMetadata about this check 4522 if (CB->hasRetAttr(Attribute::NoUndef)) 4523 return CB->getRange(); 4524 } 4525 if (const MDNode *Range = getRangeMetadata(I)) 4526 return getConstantRangeFromMetadata(*Range); 4527 return std::nullopt; 4528 } 4529 4530 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4531 if (I.isAtomic()) 4532 return visitAtomicLoad(I); 4533 4534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4535 const Value *SV = I.getOperand(0); 4536 if (TLI.supportSwiftError()) { 4537 // Swifterror values can come from either a function parameter with 4538 // swifterror attribute or an alloca with swifterror attribute. 4539 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4540 if (Arg->hasSwiftErrorAttr()) 4541 return visitLoadFromSwiftError(I); 4542 } 4543 4544 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4545 if (Alloca->isSwiftError()) 4546 return visitLoadFromSwiftError(I); 4547 } 4548 } 4549 4550 SDValue Ptr = getValue(SV); 4551 4552 Type *Ty = I.getType(); 4553 SmallVector<EVT, 4> ValueVTs, MemVTs; 4554 SmallVector<TypeSize, 4> Offsets; 4555 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4556 unsigned NumValues = ValueVTs.size(); 4557 if (NumValues == 0) 4558 return; 4559 4560 Align Alignment = I.getAlign(); 4561 AAMDNodes AAInfo = I.getAAMetadata(); 4562 const MDNode *Ranges = getRangeMetadata(I); 4563 bool isVolatile = I.isVolatile(); 4564 MachineMemOperand::Flags MMOFlags = 4565 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4566 4567 SDValue Root; 4568 bool ConstantMemory = false; 4569 if (isVolatile) 4570 // Serialize volatile loads with other side effects. 4571 Root = getRoot(); 4572 else if (NumValues > MaxParallelChains) 4573 Root = getMemoryRoot(); 4574 else if (AA && 4575 AA->pointsToConstantMemory(MemoryLocation( 4576 SV, 4577 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4578 AAInfo))) { 4579 // Do not serialize (non-volatile) loads of constant memory with anything. 4580 Root = DAG.getEntryNode(); 4581 ConstantMemory = true; 4582 MMOFlags |= MachineMemOperand::MOInvariant; 4583 } else { 4584 // Do not serialize non-volatile loads against each other. 4585 Root = DAG.getRoot(); 4586 } 4587 4588 SDLoc dl = getCurSDLoc(); 4589 4590 if (isVolatile) 4591 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4592 4593 SmallVector<SDValue, 4> Values(NumValues); 4594 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4595 4596 unsigned ChainI = 0; 4597 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4598 // Serializing loads here may result in excessive register pressure, and 4599 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4600 // could recover a bit by hoisting nodes upward in the chain by recognizing 4601 // they are side-effect free or do not alias. The optimizer should really 4602 // avoid this case by converting large object/array copies to llvm.memcpy 4603 // (MaxParallelChains should always remain as failsafe). 4604 if (ChainI == MaxParallelChains) { 4605 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4606 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4607 ArrayRef(Chains.data(), ChainI)); 4608 Root = Chain; 4609 ChainI = 0; 4610 } 4611 4612 // TODO: MachinePointerInfo only supports a fixed length offset. 4613 MachinePointerInfo PtrInfo = 4614 !Offsets[i].isScalable() || Offsets[i].isZero() 4615 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4616 : MachinePointerInfo(); 4617 4618 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4619 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4620 MMOFlags, AAInfo, Ranges); 4621 Chains[ChainI] = L.getValue(1); 4622 4623 if (MemVTs[i] != ValueVTs[i]) 4624 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4625 4626 Values[i] = L; 4627 } 4628 4629 if (!ConstantMemory) { 4630 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4631 ArrayRef(Chains.data(), ChainI)); 4632 if (isVolatile) 4633 DAG.setRoot(Chain); 4634 else 4635 PendingLoads.push_back(Chain); 4636 } 4637 4638 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4639 DAG.getVTList(ValueVTs), Values)); 4640 } 4641 4642 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4643 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4644 "call visitStoreToSwiftError when backend supports swifterror"); 4645 4646 SmallVector<EVT, 4> ValueVTs; 4647 SmallVector<uint64_t, 4> Offsets; 4648 const Value *SrcV = I.getOperand(0); 4649 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4650 SrcV->getType(), ValueVTs, &Offsets, 0); 4651 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4652 "expect a single EVT for swifterror"); 4653 4654 SDValue Src = getValue(SrcV); 4655 // Create a virtual register, then update the virtual register. 4656 Register VReg = 4657 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4658 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4659 // Chain can be getRoot or getControlRoot. 4660 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4661 SDValue(Src.getNode(), Src.getResNo())); 4662 DAG.setRoot(CopyNode); 4663 } 4664 4665 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4666 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4667 "call visitLoadFromSwiftError when backend supports swifterror"); 4668 4669 assert(!I.isVolatile() && 4670 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4671 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4672 "Support volatile, non temporal, invariant for load_from_swift_error"); 4673 4674 const Value *SV = I.getOperand(0); 4675 Type *Ty = I.getType(); 4676 assert( 4677 (!AA || 4678 !AA->pointsToConstantMemory(MemoryLocation( 4679 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4680 I.getAAMetadata()))) && 4681 "load_from_swift_error should not be constant memory"); 4682 4683 SmallVector<EVT, 4> ValueVTs; 4684 SmallVector<uint64_t, 4> Offsets; 4685 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4686 ValueVTs, &Offsets, 0); 4687 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4688 "expect a single EVT for swifterror"); 4689 4690 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4691 SDValue L = DAG.getCopyFromReg( 4692 getRoot(), getCurSDLoc(), 4693 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4694 4695 setValue(&I, L); 4696 } 4697 4698 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4699 if (I.isAtomic()) 4700 return visitAtomicStore(I); 4701 4702 const Value *SrcV = I.getOperand(0); 4703 const Value *PtrV = I.getOperand(1); 4704 4705 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4706 if (TLI.supportSwiftError()) { 4707 // Swifterror values can come from either a function parameter with 4708 // swifterror attribute or an alloca with swifterror attribute. 4709 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4710 if (Arg->hasSwiftErrorAttr()) 4711 return visitStoreToSwiftError(I); 4712 } 4713 4714 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4715 if (Alloca->isSwiftError()) 4716 return visitStoreToSwiftError(I); 4717 } 4718 } 4719 4720 SmallVector<EVT, 4> ValueVTs, MemVTs; 4721 SmallVector<TypeSize, 4> Offsets; 4722 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4723 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4724 unsigned NumValues = ValueVTs.size(); 4725 if (NumValues == 0) 4726 return; 4727 4728 // Get the lowered operands. Note that we do this after 4729 // checking if NumResults is zero, because with zero results 4730 // the operands won't have values in the map. 4731 SDValue Src = getValue(SrcV); 4732 SDValue Ptr = getValue(PtrV); 4733 4734 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4735 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4736 SDLoc dl = getCurSDLoc(); 4737 Align Alignment = I.getAlign(); 4738 AAMDNodes AAInfo = I.getAAMetadata(); 4739 4740 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4741 4742 unsigned ChainI = 0; 4743 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4744 // See visitLoad comments. 4745 if (ChainI == MaxParallelChains) { 4746 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4747 ArrayRef(Chains.data(), ChainI)); 4748 Root = Chain; 4749 ChainI = 0; 4750 } 4751 4752 // TODO: MachinePointerInfo only supports a fixed length offset. 4753 MachinePointerInfo PtrInfo = 4754 !Offsets[i].isScalable() || Offsets[i].isZero() 4755 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4756 : MachinePointerInfo(); 4757 4758 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4759 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4760 if (MemVTs[i] != ValueVTs[i]) 4761 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4762 SDValue St = 4763 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4764 Chains[ChainI] = St; 4765 } 4766 4767 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4768 ArrayRef(Chains.data(), ChainI)); 4769 setValue(&I, StoreNode); 4770 DAG.setRoot(StoreNode); 4771 } 4772 4773 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4774 bool IsCompressing) { 4775 SDLoc sdl = getCurSDLoc(); 4776 4777 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4778 Align &Alignment) { 4779 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4780 Src0 = I.getArgOperand(0); 4781 Ptr = I.getArgOperand(1); 4782 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4783 Mask = I.getArgOperand(3); 4784 }; 4785 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4786 Align &Alignment) { 4787 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4788 Src0 = I.getArgOperand(0); 4789 Ptr = I.getArgOperand(1); 4790 Mask = I.getArgOperand(2); 4791 Alignment = I.getParamAlign(1).valueOrOne(); 4792 }; 4793 4794 Value *PtrOperand, *MaskOperand, *Src0Operand; 4795 Align Alignment; 4796 if (IsCompressing) 4797 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4798 else 4799 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4800 4801 SDValue Ptr = getValue(PtrOperand); 4802 SDValue Src0 = getValue(Src0Operand); 4803 SDValue Mask = getValue(MaskOperand); 4804 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4805 4806 EVT VT = Src0.getValueType(); 4807 4808 auto MMOFlags = MachineMemOperand::MOStore; 4809 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4810 MMOFlags |= MachineMemOperand::MONonTemporal; 4811 4812 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4813 MachinePointerInfo(PtrOperand), MMOFlags, 4814 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4815 4816 const auto &TLI = DAG.getTargetLoweringInfo(); 4817 const auto &TTI = 4818 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 4819 SDValue StoreNode = 4820 !IsCompressing && 4821 TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType()) 4822 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0, 4823 Mask) 4824 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, 4825 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false, 4826 IsCompressing); 4827 DAG.setRoot(StoreNode); 4828 setValue(&I, StoreNode); 4829 } 4830 4831 // Get a uniform base for the Gather/Scatter intrinsic. 4832 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4833 // We try to represent it as a base pointer + vector of indices. 4834 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4835 // The first operand of the GEP may be a single pointer or a vector of pointers 4836 // Example: 4837 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4838 // or 4839 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4840 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4841 // 4842 // When the first GEP operand is a single pointer - it is the uniform base we 4843 // are looking for. If first operand of the GEP is a splat vector - we 4844 // extract the splat value and use it as a uniform base. 4845 // In all other cases the function returns 'false'. 4846 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4847 ISD::MemIndexType &IndexType, SDValue &Scale, 4848 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4849 uint64_t ElemSize) { 4850 SelectionDAG& DAG = SDB->DAG; 4851 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4852 const DataLayout &DL = DAG.getDataLayout(); 4853 4854 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4855 4856 // Handle splat constant pointer. 4857 if (auto *C = dyn_cast<Constant>(Ptr)) { 4858 C = C->getSplatValue(); 4859 if (!C) 4860 return false; 4861 4862 Base = SDB->getValue(C); 4863 4864 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4865 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4866 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4867 IndexType = ISD::SIGNED_SCALED; 4868 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4869 return true; 4870 } 4871 4872 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4873 if (!GEP || GEP->getParent() != CurBB) 4874 return false; 4875 4876 if (GEP->getNumOperands() != 2) 4877 return false; 4878 4879 const Value *BasePtr = GEP->getPointerOperand(); 4880 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4881 4882 // Make sure the base is scalar and the index is a vector. 4883 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4884 return false; 4885 4886 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4887 if (ScaleVal.isScalable()) 4888 return false; 4889 4890 // Target may not support the required addressing mode. 4891 if (ScaleVal != 1 && 4892 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4893 return false; 4894 4895 Base = SDB->getValue(BasePtr); 4896 Index = SDB->getValue(IndexVal); 4897 IndexType = ISD::SIGNED_SCALED; 4898 4899 Scale = 4900 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4901 return true; 4902 } 4903 4904 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4905 SDLoc sdl = getCurSDLoc(); 4906 4907 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4908 const Value *Ptr = I.getArgOperand(1); 4909 SDValue Src0 = getValue(I.getArgOperand(0)); 4910 SDValue Mask = getValue(I.getArgOperand(3)); 4911 EVT VT = Src0.getValueType(); 4912 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4913 ->getMaybeAlignValue() 4914 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4916 4917 SDValue Base; 4918 SDValue Index; 4919 ISD::MemIndexType IndexType; 4920 SDValue Scale; 4921 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4922 I.getParent(), VT.getScalarStoreSize()); 4923 4924 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4925 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4926 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4927 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4928 if (!UniformBase) { 4929 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4930 Index = getValue(Ptr); 4931 IndexType = ISD::SIGNED_SCALED; 4932 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4933 } 4934 4935 EVT IdxVT = Index.getValueType(); 4936 EVT EltTy = IdxVT.getVectorElementType(); 4937 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4938 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4939 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4940 } 4941 4942 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4943 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4944 Ops, MMO, IndexType, false); 4945 DAG.setRoot(Scatter); 4946 setValue(&I, Scatter); 4947 } 4948 4949 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4950 SDLoc sdl = getCurSDLoc(); 4951 4952 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4953 Align &Alignment) { 4954 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4955 Ptr = I.getArgOperand(0); 4956 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4957 Mask = I.getArgOperand(2); 4958 Src0 = I.getArgOperand(3); 4959 }; 4960 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4961 Align &Alignment) { 4962 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4963 Ptr = I.getArgOperand(0); 4964 Alignment = I.getParamAlign(0).valueOrOne(); 4965 Mask = I.getArgOperand(1); 4966 Src0 = I.getArgOperand(2); 4967 }; 4968 4969 Value *PtrOperand, *MaskOperand, *Src0Operand; 4970 Align Alignment; 4971 if (IsExpanding) 4972 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4973 else 4974 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4975 4976 SDValue Ptr = getValue(PtrOperand); 4977 SDValue Src0 = getValue(Src0Operand); 4978 SDValue Mask = getValue(MaskOperand); 4979 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4980 4981 EVT VT = Src0.getValueType(); 4982 AAMDNodes AAInfo = I.getAAMetadata(); 4983 const MDNode *Ranges = getRangeMetadata(I); 4984 4985 // Do not serialize masked loads of constant memory with anything. 4986 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4987 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4988 4989 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4990 4991 auto MMOFlags = MachineMemOperand::MOLoad; 4992 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4993 MMOFlags |= MachineMemOperand::MONonTemporal; 4994 4995 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4996 MachinePointerInfo(PtrOperand), MMOFlags, 4997 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 4998 4999 const auto &TLI = DAG.getTargetLoweringInfo(); 5000 const auto &TTI = 5001 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 5002 // The Load/Res may point to different values and both of them are output 5003 // variables. 5004 SDValue Load; 5005 SDValue Res; 5006 if (!IsExpanding && 5007 TTI.hasConditionalLoadStoreForType(Src0Operand->getType())) 5008 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask); 5009 else 5010 Res = Load = 5011 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 5012 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 5013 if (AddToChain) 5014 PendingLoads.push_back(Load.getValue(1)); 5015 setValue(&I, Res); 5016 } 5017 5018 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 5019 SDLoc sdl = getCurSDLoc(); 5020 5021 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 5022 const Value *Ptr = I.getArgOperand(0); 5023 SDValue Src0 = getValue(I.getArgOperand(3)); 5024 SDValue Mask = getValue(I.getArgOperand(2)); 5025 5026 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5027 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5028 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 5029 ->getMaybeAlignValue() 5030 .value_or(DAG.getEVTAlign(VT.getScalarType())); 5031 5032 const MDNode *Ranges = getRangeMetadata(I); 5033 5034 SDValue Root = DAG.getRoot(); 5035 SDValue Base; 5036 SDValue Index; 5037 ISD::MemIndexType IndexType; 5038 SDValue Scale; 5039 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 5040 I.getParent(), VT.getScalarStoreSize()); 5041 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 5042 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5043 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 5044 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 5045 Ranges); 5046 5047 if (!UniformBase) { 5048 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5049 Index = getValue(Ptr); 5050 IndexType = ISD::SIGNED_SCALED; 5051 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 5052 } 5053 5054 EVT IdxVT = Index.getValueType(); 5055 EVT EltTy = IdxVT.getVectorElementType(); 5056 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 5057 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 5058 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 5059 } 5060 5061 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 5062 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 5063 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 5064 5065 PendingLoads.push_back(Gather.getValue(1)); 5066 setValue(&I, Gather); 5067 } 5068 5069 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5070 SDLoc dl = getCurSDLoc(); 5071 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5072 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5073 SyncScope::ID SSID = I.getSyncScopeID(); 5074 5075 SDValue InChain = getRoot(); 5076 5077 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5078 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5079 5080 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5081 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5082 5083 MachineFunction &MF = DAG.getMachineFunction(); 5084 MachineMemOperand *MMO = MF.getMachineMemOperand( 5085 MachinePointerInfo(I.getPointerOperand()), Flags, 5086 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5087 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5088 5089 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5090 dl, MemVT, VTs, InChain, 5091 getValue(I.getPointerOperand()), 5092 getValue(I.getCompareOperand()), 5093 getValue(I.getNewValOperand()), MMO); 5094 5095 SDValue OutChain = L.getValue(2); 5096 5097 setValue(&I, L); 5098 DAG.setRoot(OutChain); 5099 } 5100 5101 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5102 SDLoc dl = getCurSDLoc(); 5103 ISD::NodeType NT; 5104 switch (I.getOperation()) { 5105 default: llvm_unreachable("Unknown atomicrmw operation"); 5106 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5107 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5108 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5109 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5110 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5111 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5112 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5113 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5114 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5115 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5116 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5117 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5118 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5119 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5120 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5121 case AtomicRMWInst::UIncWrap: 5122 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5123 break; 5124 case AtomicRMWInst::UDecWrap: 5125 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5126 break; 5127 case AtomicRMWInst::USubCond: 5128 NT = ISD::ATOMIC_LOAD_USUB_COND; 5129 break; 5130 case AtomicRMWInst::USubSat: 5131 NT = ISD::ATOMIC_LOAD_USUB_SAT; 5132 break; 5133 } 5134 AtomicOrdering Ordering = I.getOrdering(); 5135 SyncScope::ID SSID = I.getSyncScopeID(); 5136 5137 SDValue InChain = getRoot(); 5138 5139 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5141 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5142 5143 MachineFunction &MF = DAG.getMachineFunction(); 5144 MachineMemOperand *MMO = MF.getMachineMemOperand( 5145 MachinePointerInfo(I.getPointerOperand()), Flags, 5146 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5147 AAMDNodes(), nullptr, SSID, Ordering); 5148 5149 SDValue L = 5150 DAG.getAtomic(NT, dl, MemVT, InChain, 5151 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5152 MMO); 5153 5154 SDValue OutChain = L.getValue(1); 5155 5156 setValue(&I, L); 5157 DAG.setRoot(OutChain); 5158 } 5159 5160 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5161 SDLoc dl = getCurSDLoc(); 5162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5163 SDValue Ops[3]; 5164 Ops[0] = getRoot(); 5165 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5166 TLI.getFenceOperandTy(DAG.getDataLayout())); 5167 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5168 TLI.getFenceOperandTy(DAG.getDataLayout())); 5169 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5170 setValue(&I, N); 5171 DAG.setRoot(N); 5172 } 5173 5174 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5175 SDLoc dl = getCurSDLoc(); 5176 AtomicOrdering Order = I.getOrdering(); 5177 SyncScope::ID SSID = I.getSyncScopeID(); 5178 5179 SDValue InChain = getRoot(); 5180 5181 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5182 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5183 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5184 5185 if (!TLI.supportsUnalignedAtomics() && 5186 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5187 report_fatal_error("Cannot generate unaligned atomic load"); 5188 5189 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5190 5191 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5192 MachinePointerInfo(I.getPointerOperand()), Flags, 5193 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5194 nullptr, SSID, Order); 5195 5196 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5197 5198 SDValue Ptr = getValue(I.getPointerOperand()); 5199 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5200 Ptr, MMO); 5201 5202 SDValue OutChain = L.getValue(1); 5203 if (MemVT != VT) 5204 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5205 5206 setValue(&I, L); 5207 DAG.setRoot(OutChain); 5208 } 5209 5210 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5211 SDLoc dl = getCurSDLoc(); 5212 5213 AtomicOrdering Ordering = I.getOrdering(); 5214 SyncScope::ID SSID = I.getSyncScopeID(); 5215 5216 SDValue InChain = getRoot(); 5217 5218 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5219 EVT MemVT = 5220 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5221 5222 if (!TLI.supportsUnalignedAtomics() && 5223 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5224 report_fatal_error("Cannot generate unaligned atomic store"); 5225 5226 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5227 5228 MachineFunction &MF = DAG.getMachineFunction(); 5229 MachineMemOperand *MMO = MF.getMachineMemOperand( 5230 MachinePointerInfo(I.getPointerOperand()), Flags, 5231 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5232 nullptr, SSID, Ordering); 5233 5234 SDValue Val = getValue(I.getValueOperand()); 5235 if (Val.getValueType() != MemVT) 5236 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5237 SDValue Ptr = getValue(I.getPointerOperand()); 5238 5239 SDValue OutChain = 5240 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5241 5242 setValue(&I, OutChain); 5243 DAG.setRoot(OutChain); 5244 } 5245 5246 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5247 /// node. 5248 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5249 unsigned Intrinsic) { 5250 // Ignore the callsite's attributes. A specific call site may be marked with 5251 // readnone, but the lowering code will expect the chain based on the 5252 // definition. 5253 const Function *F = I.getCalledFunction(); 5254 bool HasChain = !F->doesNotAccessMemory(); 5255 bool OnlyLoad = 5256 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow(); 5257 5258 // Build the operand list. 5259 SmallVector<SDValue, 8> Ops; 5260 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5261 if (OnlyLoad) { 5262 // We don't need to serialize loads against other loads. 5263 Ops.push_back(DAG.getRoot()); 5264 } else { 5265 Ops.push_back(getRoot()); 5266 } 5267 } 5268 5269 // Info is set by getTgtMemIntrinsic 5270 TargetLowering::IntrinsicInfo Info; 5271 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5272 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5273 DAG.getMachineFunction(), 5274 Intrinsic); 5275 5276 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5277 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5278 Info.opc == ISD::INTRINSIC_W_CHAIN) 5279 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5280 TLI.getPointerTy(DAG.getDataLayout()))); 5281 5282 // Add all operands of the call to the operand list. 5283 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5284 const Value *Arg = I.getArgOperand(i); 5285 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5286 Ops.push_back(getValue(Arg)); 5287 continue; 5288 } 5289 5290 // Use TargetConstant instead of a regular constant for immarg. 5291 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5292 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5293 assert(CI->getBitWidth() <= 64 && 5294 "large intrinsic immediates not handled"); 5295 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5296 } else { 5297 Ops.push_back( 5298 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5299 } 5300 } 5301 5302 SmallVector<EVT, 4> ValueVTs; 5303 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5304 5305 if (HasChain) 5306 ValueVTs.push_back(MVT::Other); 5307 5308 SDVTList VTs = DAG.getVTList(ValueVTs); 5309 5310 // Propagate fast-math-flags from IR to node(s). 5311 SDNodeFlags Flags; 5312 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5313 Flags.copyFMF(*FPMO); 5314 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5315 5316 // Create the node. 5317 SDValue Result; 5318 5319 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5320 auto *Token = Bundle->Inputs[0].get(); 5321 SDValue ConvControlToken = getValue(Token); 5322 assert(Ops.back().getValueType() != MVT::Glue && 5323 "Did not expected another glue node here."); 5324 ConvControlToken = 5325 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5326 Ops.push_back(ConvControlToken); 5327 } 5328 5329 // In some cases, custom collection of operands from CallInst I may be needed. 5330 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5331 if (IsTgtIntrinsic) { 5332 // This is target intrinsic that touches memory 5333 // 5334 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5335 // didn't yield anything useful. 5336 MachinePointerInfo MPI; 5337 if (Info.ptrVal) 5338 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5339 else if (Info.fallbackAddressSpace) 5340 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5341 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5342 Info.memVT, MPI, Info.align, Info.flags, 5343 Info.size, I.getAAMetadata()); 5344 } else if (!HasChain) { 5345 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5346 } else if (!I.getType()->isVoidTy()) { 5347 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5348 } else { 5349 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5350 } 5351 5352 if (HasChain) { 5353 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5354 if (OnlyLoad) 5355 PendingLoads.push_back(Chain); 5356 else 5357 DAG.setRoot(Chain); 5358 } 5359 5360 if (!I.getType()->isVoidTy()) { 5361 if (!isa<VectorType>(I.getType())) 5362 Result = lowerRangeToAssertZExt(DAG, I, Result); 5363 5364 MaybeAlign Alignment = I.getRetAlign(); 5365 5366 // Insert `assertalign` node if there's an alignment. 5367 if (InsertAssertAlign && Alignment) { 5368 Result = 5369 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5370 } 5371 } 5372 5373 setValue(&I, Result); 5374 } 5375 5376 /// GetSignificand - Get the significand and build it into a floating-point 5377 /// number with exponent of 1: 5378 /// 5379 /// Op = (Op & 0x007fffff) | 0x3f800000; 5380 /// 5381 /// where Op is the hexadecimal representation of floating point value. 5382 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5383 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5384 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5385 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5386 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5387 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5388 } 5389 5390 /// GetExponent - Get the exponent: 5391 /// 5392 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5393 /// 5394 /// where Op is the hexadecimal representation of floating point value. 5395 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5396 const TargetLowering &TLI, const SDLoc &dl) { 5397 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5398 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5399 SDValue t1 = DAG.getNode( 5400 ISD::SRL, dl, MVT::i32, t0, 5401 DAG.getConstant(23, dl, 5402 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5403 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5404 DAG.getConstant(127, dl, MVT::i32)); 5405 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5406 } 5407 5408 /// getF32Constant - Get 32-bit floating point constant. 5409 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5410 const SDLoc &dl) { 5411 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5412 MVT::f32); 5413 } 5414 5415 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5416 SelectionDAG &DAG) { 5417 // TODO: What fast-math-flags should be set on the floating-point nodes? 5418 5419 // IntegerPartOfX = ((int32_t)(t0); 5420 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5421 5422 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5423 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5424 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5425 5426 // IntegerPartOfX <<= 23; 5427 IntegerPartOfX = 5428 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5429 DAG.getConstant(23, dl, 5430 DAG.getTargetLoweringInfo().getShiftAmountTy( 5431 MVT::i32, DAG.getDataLayout()))); 5432 5433 SDValue TwoToFractionalPartOfX; 5434 if (LimitFloatPrecision <= 6) { 5435 // For floating-point precision of 6: 5436 // 5437 // TwoToFractionalPartOfX = 5438 // 0.997535578f + 5439 // (0.735607626f + 0.252464424f * x) * x; 5440 // 5441 // error 0.0144103317, which is 6 bits 5442 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5443 getF32Constant(DAG, 0x3e814304, dl)); 5444 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5445 getF32Constant(DAG, 0x3f3c50c8, dl)); 5446 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5447 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5448 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5449 } else if (LimitFloatPrecision <= 12) { 5450 // For floating-point precision of 12: 5451 // 5452 // TwoToFractionalPartOfX = 5453 // 0.999892986f + 5454 // (0.696457318f + 5455 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5456 // 5457 // error 0.000107046256, which is 13 to 14 bits 5458 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5459 getF32Constant(DAG, 0x3da235e3, dl)); 5460 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5461 getF32Constant(DAG, 0x3e65b8f3, dl)); 5462 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5463 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5464 getF32Constant(DAG, 0x3f324b07, dl)); 5465 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5466 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5467 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5468 } else { // LimitFloatPrecision <= 18 5469 // For floating-point precision of 18: 5470 // 5471 // TwoToFractionalPartOfX = 5472 // 0.999999982f + 5473 // (0.693148872f + 5474 // (0.240227044f + 5475 // (0.554906021e-1f + 5476 // (0.961591928e-2f + 5477 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5478 // error 2.47208000*10^(-7), which is better than 18 bits 5479 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5480 getF32Constant(DAG, 0x3924b03e, dl)); 5481 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5482 getF32Constant(DAG, 0x3ab24b87, dl)); 5483 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5484 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5485 getF32Constant(DAG, 0x3c1d8c17, dl)); 5486 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5487 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5488 getF32Constant(DAG, 0x3d634a1d, dl)); 5489 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5490 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5491 getF32Constant(DAG, 0x3e75fe14, dl)); 5492 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5493 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5494 getF32Constant(DAG, 0x3f317234, dl)); 5495 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5496 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5497 getF32Constant(DAG, 0x3f800000, dl)); 5498 } 5499 5500 // Add the exponent into the result in integer domain. 5501 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5502 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5503 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5504 } 5505 5506 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5507 /// limited-precision mode. 5508 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5509 const TargetLowering &TLI, SDNodeFlags Flags) { 5510 if (Op.getValueType() == MVT::f32 && 5511 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5512 5513 // Put the exponent in the right bit position for later addition to the 5514 // final result: 5515 // 5516 // t0 = Op * log2(e) 5517 5518 // TODO: What fast-math-flags should be set here? 5519 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5520 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5521 return getLimitedPrecisionExp2(t0, dl, DAG); 5522 } 5523 5524 // No special expansion. 5525 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5526 } 5527 5528 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5529 /// limited-precision mode. 5530 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5531 const TargetLowering &TLI, SDNodeFlags Flags) { 5532 // TODO: What fast-math-flags should be set on the floating-point nodes? 5533 5534 if (Op.getValueType() == MVT::f32 && 5535 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5536 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5537 5538 // Scale the exponent by log(2). 5539 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5540 SDValue LogOfExponent = 5541 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5542 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5543 5544 // Get the significand and build it into a floating-point number with 5545 // exponent of 1. 5546 SDValue X = GetSignificand(DAG, Op1, dl); 5547 5548 SDValue LogOfMantissa; 5549 if (LimitFloatPrecision <= 6) { 5550 // For floating-point precision of 6: 5551 // 5552 // LogofMantissa = 5553 // -1.1609546f + 5554 // (1.4034025f - 0.23903021f * x) * x; 5555 // 5556 // error 0.0034276066, which is better than 8 bits 5557 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5558 getF32Constant(DAG, 0xbe74c456, dl)); 5559 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5560 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5561 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5562 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5563 getF32Constant(DAG, 0x3f949a29, dl)); 5564 } else if (LimitFloatPrecision <= 12) { 5565 // For floating-point precision of 12: 5566 // 5567 // LogOfMantissa = 5568 // -1.7417939f + 5569 // (2.8212026f + 5570 // (-1.4699568f + 5571 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5572 // 5573 // error 0.000061011436, which is 14 bits 5574 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5575 getF32Constant(DAG, 0xbd67b6d6, dl)); 5576 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5577 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5578 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5579 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5580 getF32Constant(DAG, 0x3fbc278b, dl)); 5581 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5582 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5583 getF32Constant(DAG, 0x40348e95, dl)); 5584 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5585 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5586 getF32Constant(DAG, 0x3fdef31a, dl)); 5587 } else { // LimitFloatPrecision <= 18 5588 // For floating-point precision of 18: 5589 // 5590 // LogOfMantissa = 5591 // -2.1072184f + 5592 // (4.2372794f + 5593 // (-3.7029485f + 5594 // (2.2781945f + 5595 // (-0.87823314f + 5596 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5597 // 5598 // error 0.0000023660568, which is better than 18 bits 5599 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5600 getF32Constant(DAG, 0xbc91e5ac, dl)); 5601 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5602 getF32Constant(DAG, 0x3e4350aa, dl)); 5603 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5604 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5605 getF32Constant(DAG, 0x3f60d3e3, dl)); 5606 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5607 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5608 getF32Constant(DAG, 0x4011cdf0, dl)); 5609 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5610 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5611 getF32Constant(DAG, 0x406cfd1c, dl)); 5612 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5613 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5614 getF32Constant(DAG, 0x408797cb, dl)); 5615 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5616 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5617 getF32Constant(DAG, 0x4006dcab, dl)); 5618 } 5619 5620 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5621 } 5622 5623 // No special expansion. 5624 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5625 } 5626 5627 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5628 /// limited-precision mode. 5629 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5630 const TargetLowering &TLI, SDNodeFlags Flags) { 5631 // TODO: What fast-math-flags should be set on the floating-point nodes? 5632 5633 if (Op.getValueType() == MVT::f32 && 5634 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5635 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5636 5637 // Get the exponent. 5638 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5639 5640 // Get the significand and build it into a floating-point number with 5641 // exponent of 1. 5642 SDValue X = GetSignificand(DAG, Op1, dl); 5643 5644 // Different possible minimax approximations of significand in 5645 // floating-point for various degrees of accuracy over [1,2]. 5646 SDValue Log2ofMantissa; 5647 if (LimitFloatPrecision <= 6) { 5648 // For floating-point precision of 6: 5649 // 5650 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5651 // 5652 // error 0.0049451742, which is more than 7 bits 5653 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5654 getF32Constant(DAG, 0xbeb08fe0, dl)); 5655 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5656 getF32Constant(DAG, 0x40019463, dl)); 5657 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5658 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5659 getF32Constant(DAG, 0x3fd6633d, dl)); 5660 } else if (LimitFloatPrecision <= 12) { 5661 // For floating-point precision of 12: 5662 // 5663 // Log2ofMantissa = 5664 // -2.51285454f + 5665 // (4.07009056f + 5666 // (-2.12067489f + 5667 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5668 // 5669 // error 0.0000876136000, which is better than 13 bits 5670 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5671 getF32Constant(DAG, 0xbda7262e, dl)); 5672 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5673 getF32Constant(DAG, 0x3f25280b, dl)); 5674 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5675 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5676 getF32Constant(DAG, 0x4007b923, dl)); 5677 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5678 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5679 getF32Constant(DAG, 0x40823e2f, dl)); 5680 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5681 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5682 getF32Constant(DAG, 0x4020d29c, dl)); 5683 } else { // LimitFloatPrecision <= 18 5684 // For floating-point precision of 18: 5685 // 5686 // Log2ofMantissa = 5687 // -3.0400495f + 5688 // (6.1129976f + 5689 // (-5.3420409f + 5690 // (3.2865683f + 5691 // (-1.2669343f + 5692 // (0.27515199f - 5693 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5694 // 5695 // error 0.0000018516, which is better than 18 bits 5696 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5697 getF32Constant(DAG, 0xbcd2769e, dl)); 5698 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5699 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5700 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5701 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5702 getF32Constant(DAG, 0x3fa22ae7, dl)); 5703 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5704 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5705 getF32Constant(DAG, 0x40525723, dl)); 5706 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5707 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5708 getF32Constant(DAG, 0x40aaf200, dl)); 5709 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5710 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5711 getF32Constant(DAG, 0x40c39dad, dl)); 5712 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5713 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5714 getF32Constant(DAG, 0x4042902c, dl)); 5715 } 5716 5717 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5718 } 5719 5720 // No special expansion. 5721 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5722 } 5723 5724 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5725 /// limited-precision mode. 5726 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5727 const TargetLowering &TLI, SDNodeFlags Flags) { 5728 // TODO: What fast-math-flags should be set on the floating-point nodes? 5729 5730 if (Op.getValueType() == MVT::f32 && 5731 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5732 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5733 5734 // Scale the exponent by log10(2) [0.30102999f]. 5735 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5736 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5737 getF32Constant(DAG, 0x3e9a209a, dl)); 5738 5739 // Get the significand and build it into a floating-point number with 5740 // exponent of 1. 5741 SDValue X = GetSignificand(DAG, Op1, dl); 5742 5743 SDValue Log10ofMantissa; 5744 if (LimitFloatPrecision <= 6) { 5745 // For floating-point precision of 6: 5746 // 5747 // Log10ofMantissa = 5748 // -0.50419619f + 5749 // (0.60948995f - 0.10380950f * x) * x; 5750 // 5751 // error 0.0014886165, which is 6 bits 5752 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5753 getF32Constant(DAG, 0xbdd49a13, dl)); 5754 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5755 getF32Constant(DAG, 0x3f1c0789, dl)); 5756 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5757 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5758 getF32Constant(DAG, 0x3f011300, dl)); 5759 } else if (LimitFloatPrecision <= 12) { 5760 // For floating-point precision of 12: 5761 // 5762 // Log10ofMantissa = 5763 // -0.64831180f + 5764 // (0.91751397f + 5765 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5766 // 5767 // error 0.00019228036, which is better than 12 bits 5768 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5769 getF32Constant(DAG, 0x3d431f31, dl)); 5770 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5771 getF32Constant(DAG, 0x3ea21fb2, dl)); 5772 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5773 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5774 getF32Constant(DAG, 0x3f6ae232, dl)); 5775 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5776 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5777 getF32Constant(DAG, 0x3f25f7c3, dl)); 5778 } else { // LimitFloatPrecision <= 18 5779 // For floating-point precision of 18: 5780 // 5781 // Log10ofMantissa = 5782 // -0.84299375f + 5783 // (1.5327582f + 5784 // (-1.0688956f + 5785 // (0.49102474f + 5786 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5787 // 5788 // error 0.0000037995730, which is better than 18 bits 5789 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5790 getF32Constant(DAG, 0x3c5d51ce, dl)); 5791 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5792 getF32Constant(DAG, 0x3e00685a, dl)); 5793 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5794 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5795 getF32Constant(DAG, 0x3efb6798, dl)); 5796 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5797 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5798 getF32Constant(DAG, 0x3f88d192, dl)); 5799 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5800 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5801 getF32Constant(DAG, 0x3fc4316c, dl)); 5802 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5803 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5804 getF32Constant(DAG, 0x3f57ce70, dl)); 5805 } 5806 5807 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5808 } 5809 5810 // No special expansion. 5811 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5812 } 5813 5814 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5815 /// limited-precision mode. 5816 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5817 const TargetLowering &TLI, SDNodeFlags Flags) { 5818 if (Op.getValueType() == MVT::f32 && 5819 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5820 return getLimitedPrecisionExp2(Op, dl, DAG); 5821 5822 // No special expansion. 5823 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5824 } 5825 5826 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5827 /// limited-precision mode with x == 10.0f. 5828 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5829 SelectionDAG &DAG, const TargetLowering &TLI, 5830 SDNodeFlags Flags) { 5831 bool IsExp10 = false; 5832 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5833 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5834 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5835 APFloat Ten(10.0f); 5836 IsExp10 = LHSC->isExactlyValue(Ten); 5837 } 5838 } 5839 5840 // TODO: What fast-math-flags should be set on the FMUL node? 5841 if (IsExp10) { 5842 // Put the exponent in the right bit position for later addition to the 5843 // final result: 5844 // 5845 // #define LOG2OF10 3.3219281f 5846 // t0 = Op * LOG2OF10; 5847 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5848 getF32Constant(DAG, 0x40549a78, dl)); 5849 return getLimitedPrecisionExp2(t0, dl, DAG); 5850 } 5851 5852 // No special expansion. 5853 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5854 } 5855 5856 /// ExpandPowI - Expand a llvm.powi intrinsic. 5857 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5858 SelectionDAG &DAG) { 5859 // If RHS is a constant, we can expand this out to a multiplication tree if 5860 // it's beneficial on the target, otherwise we end up lowering to a call to 5861 // __powidf2 (for example). 5862 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5863 unsigned Val = RHSC->getSExtValue(); 5864 5865 // powi(x, 0) -> 1.0 5866 if (Val == 0) 5867 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5868 5869 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5870 Val, DAG.shouldOptForSize())) { 5871 // Get the exponent as a positive value. 5872 if ((int)Val < 0) 5873 Val = -Val; 5874 // We use the simple binary decomposition method to generate the multiply 5875 // sequence. There are more optimal ways to do this (for example, 5876 // powi(x,15) generates one more multiply than it should), but this has 5877 // the benefit of being both really simple and much better than a libcall. 5878 SDValue Res; // Logically starts equal to 1.0 5879 SDValue CurSquare = LHS; 5880 // TODO: Intrinsics should have fast-math-flags that propagate to these 5881 // nodes. 5882 while (Val) { 5883 if (Val & 1) { 5884 if (Res.getNode()) 5885 Res = 5886 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5887 else 5888 Res = CurSquare; // 1.0*CurSquare. 5889 } 5890 5891 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5892 CurSquare, CurSquare); 5893 Val >>= 1; 5894 } 5895 5896 // If the original was negative, invert the result, producing 1/(x*x*x). 5897 if (RHSC->getSExtValue() < 0) 5898 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5899 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5900 return Res; 5901 } 5902 } 5903 5904 // Otherwise, expand to a libcall. 5905 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5906 } 5907 5908 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5909 SDValue LHS, SDValue RHS, SDValue Scale, 5910 SelectionDAG &DAG, const TargetLowering &TLI) { 5911 EVT VT = LHS.getValueType(); 5912 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5913 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5914 LLVMContext &Ctx = *DAG.getContext(); 5915 5916 // If the type is legal but the operation isn't, this node might survive all 5917 // the way to operation legalization. If we end up there and we do not have 5918 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5919 // node. 5920 5921 // Coax the legalizer into expanding the node during type legalization instead 5922 // by bumping the size by one bit. This will force it to Promote, enabling the 5923 // early expansion and avoiding the need to expand later. 5924 5925 // We don't have to do this if Scale is 0; that can always be expanded, unless 5926 // it's a saturating signed operation. Those can experience true integer 5927 // division overflow, a case which we must avoid. 5928 5929 // FIXME: We wouldn't have to do this (or any of the early 5930 // expansion/promotion) if it was possible to expand a libcall of an 5931 // illegal type during operation legalization. But it's not, so things 5932 // get a bit hacky. 5933 unsigned ScaleInt = Scale->getAsZExtVal(); 5934 if ((ScaleInt > 0 || (Saturating && Signed)) && 5935 (TLI.isTypeLegal(VT) || 5936 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5937 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5938 Opcode, VT, ScaleInt); 5939 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5940 EVT PromVT; 5941 if (VT.isScalarInteger()) 5942 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5943 else if (VT.isVector()) { 5944 PromVT = VT.getVectorElementType(); 5945 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5946 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5947 } else 5948 llvm_unreachable("Wrong VT for DIVFIX?"); 5949 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5950 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5951 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5952 // For saturating operations, we need to shift up the LHS to get the 5953 // proper saturation width, and then shift down again afterwards. 5954 if (Saturating) 5955 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5956 DAG.getConstant(1, DL, ShiftTy)); 5957 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5958 if (Saturating) 5959 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5960 DAG.getConstant(1, DL, ShiftTy)); 5961 return DAG.getZExtOrTrunc(Res, DL, VT); 5962 } 5963 } 5964 5965 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5966 } 5967 5968 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5969 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5970 static void 5971 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs, 5972 const SDValue &N) { 5973 switch (N.getOpcode()) { 5974 case ISD::CopyFromReg: { 5975 SDValue Op = N.getOperand(1); 5976 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5977 Op.getValueType().getSizeInBits()); 5978 return; 5979 } 5980 case ISD::BITCAST: 5981 case ISD::AssertZext: 5982 case ISD::AssertSext: 5983 case ISD::TRUNCATE: 5984 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5985 return; 5986 case ISD::BUILD_PAIR: 5987 case ISD::BUILD_VECTOR: 5988 case ISD::CONCAT_VECTORS: 5989 for (SDValue Op : N->op_values()) 5990 getUnderlyingArgRegs(Regs, Op); 5991 return; 5992 default: 5993 return; 5994 } 5995 } 5996 5997 /// If the DbgValueInst is a dbg_value of a function argument, create the 5998 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5999 /// instruction selection, they will be inserted to the entry BB. 6000 /// We don't currently support this for variadic dbg_values, as they shouldn't 6001 /// appear for function arguments or in the prologue. 6002 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 6003 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 6004 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 6005 const Argument *Arg = dyn_cast<Argument>(V); 6006 if (!Arg) 6007 return false; 6008 6009 MachineFunction &MF = DAG.getMachineFunction(); 6010 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6011 6012 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 6013 // we've been asked to pursue. 6014 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 6015 bool Indirect) { 6016 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 6017 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 6018 // pointing at the VReg, which will be patched up later. 6019 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 6020 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 6021 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 6022 /* isKill */ false, /* isDead */ false, 6023 /* isUndef */ false, /* isEarlyClobber */ false, 6024 /* SubReg */ 0, /* isDebug */ true)}); 6025 6026 auto *NewDIExpr = FragExpr; 6027 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 6028 // the DIExpression. 6029 if (Indirect) 6030 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 6031 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 6032 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 6033 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 6034 } else { 6035 // Create a completely standard DBG_VALUE. 6036 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 6037 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 6038 } 6039 }; 6040 6041 if (Kind == FuncArgumentDbgValueKind::Value) { 6042 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6043 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 6044 // the entry block. 6045 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 6046 if (!IsInEntryBlock) 6047 return false; 6048 6049 // ArgDbgValues are hoisted to the beginning of the entry block. So we 6050 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 6051 // variable that also is a param. 6052 // 6053 // Although, if we are at the top of the entry block already, we can still 6054 // emit using ArgDbgValue. This might catch some situations when the 6055 // dbg.value refers to an argument that isn't used in the entry block, so 6056 // any CopyToReg node would be optimized out and the only way to express 6057 // this DBG_VALUE is by using the physical reg (or FI) as done in this 6058 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 6059 // we should only emit as ArgDbgValue if the Variable is an argument to the 6060 // current function, and the dbg.value intrinsic is found in the entry 6061 // block. 6062 bool VariableIsFunctionInputArg = Variable->isParameter() && 6063 !DL->getInlinedAt(); 6064 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 6065 if (!IsInPrologue && !VariableIsFunctionInputArg) 6066 return false; 6067 6068 // Here we assume that a function argument on IR level only can be used to 6069 // describe one input parameter on source level. If we for example have 6070 // source code like this 6071 // 6072 // struct A { long x, y; }; 6073 // void foo(struct A a, long b) { 6074 // ... 6075 // b = a.x; 6076 // ... 6077 // } 6078 // 6079 // and IR like this 6080 // 6081 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6082 // entry: 6083 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6084 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6085 // call void @llvm.dbg.value(metadata i32 %b, "b", 6086 // ... 6087 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6088 // ... 6089 // 6090 // then the last dbg.value is describing a parameter "b" using a value that 6091 // is an argument. But since we already has used %a1 to describe a parameter 6092 // we should not handle that last dbg.value here (that would result in an 6093 // incorrect hoisting of the DBG_VALUE to the function entry). 6094 // Notice that we allow one dbg.value per IR level argument, to accommodate 6095 // for the situation with fragments above. 6096 // If there is no node for the value being handled, we return true to skip 6097 // the normal generation of debug info, as it would kill existing debug 6098 // info for the parameter in case of duplicates. 6099 if (VariableIsFunctionInputArg) { 6100 unsigned ArgNo = Arg->getArgNo(); 6101 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6102 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6103 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6104 return !NodeMap[V].getNode(); 6105 FuncInfo.DescribedArgs.set(ArgNo); 6106 } 6107 } 6108 6109 bool IsIndirect = false; 6110 std::optional<MachineOperand> Op; 6111 // Some arguments' frame index is recorded during argument lowering. 6112 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6113 if (FI != std::numeric_limits<int>::max()) 6114 Op = MachineOperand::CreateFI(FI); 6115 6116 SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes; 6117 if (!Op && N.getNode()) { 6118 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6119 Register Reg; 6120 if (ArgRegsAndSizes.size() == 1) 6121 Reg = ArgRegsAndSizes.front().first; 6122 6123 if (Reg && Reg.isVirtual()) { 6124 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6125 Register PR = RegInfo.getLiveInPhysReg(Reg); 6126 if (PR) 6127 Reg = PR; 6128 } 6129 if (Reg) { 6130 Op = MachineOperand::CreateReg(Reg, false); 6131 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6132 } 6133 } 6134 6135 if (!Op && N.getNode()) { 6136 // Check if frame index is available. 6137 SDValue LCandidate = peekThroughBitcasts(N); 6138 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6139 if (FrameIndexSDNode *FINode = 6140 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6141 Op = MachineOperand::CreateFI(FINode->getIndex()); 6142 } 6143 6144 if (!Op) { 6145 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6146 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>> 6147 SplitRegs) { 6148 unsigned Offset = 0; 6149 for (const auto &RegAndSize : SplitRegs) { 6150 // If the expression is already a fragment, the current register 6151 // offset+size might extend beyond the fragment. In this case, only 6152 // the register bits that are inside the fragment are relevant. 6153 int RegFragmentSizeInBits = RegAndSize.second; 6154 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6155 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6156 // The register is entirely outside the expression fragment, 6157 // so is irrelevant for debug info. 6158 if (Offset >= ExprFragmentSizeInBits) 6159 break; 6160 // The register is partially outside the expression fragment, only 6161 // the low bits within the fragment are relevant for debug info. 6162 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6163 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6164 } 6165 } 6166 6167 auto FragmentExpr = DIExpression::createFragmentExpression( 6168 Expr, Offset, RegFragmentSizeInBits); 6169 Offset += RegAndSize.second; 6170 // If a valid fragment expression cannot be created, the variable's 6171 // correct value cannot be determined and so it is set as Undef. 6172 if (!FragmentExpr) { 6173 SDDbgValue *SDV = DAG.getConstantDbgValue( 6174 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6175 DAG.AddDbgValue(SDV, false); 6176 continue; 6177 } 6178 MachineInstr *NewMI = 6179 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6180 Kind != FuncArgumentDbgValueKind::Value); 6181 FuncInfo.ArgDbgValues.push_back(NewMI); 6182 } 6183 }; 6184 6185 // Check if ValueMap has reg number. 6186 DenseMap<const Value *, Register>::const_iterator 6187 VMI = FuncInfo.ValueMap.find(V); 6188 if (VMI != FuncInfo.ValueMap.end()) { 6189 const auto &TLI = DAG.getTargetLoweringInfo(); 6190 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6191 V->getType(), std::nullopt); 6192 if (RFV.occupiesMultipleRegs()) { 6193 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6194 return true; 6195 } 6196 6197 Op = MachineOperand::CreateReg(VMI->second, false); 6198 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6199 } else if (ArgRegsAndSizes.size() > 1) { 6200 // This was split due to the calling convention, and no virtual register 6201 // mapping exists for the value. 6202 splitMultiRegDbgValue(ArgRegsAndSizes); 6203 return true; 6204 } 6205 } 6206 6207 if (!Op) 6208 return false; 6209 6210 assert(Variable->isValidLocationForIntrinsic(DL) && 6211 "Expected inlined-at fields to agree"); 6212 MachineInstr *NewMI = nullptr; 6213 6214 if (Op->isReg()) 6215 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6216 else 6217 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6218 Variable, Expr); 6219 6220 // Otherwise, use ArgDbgValues. 6221 FuncInfo.ArgDbgValues.push_back(NewMI); 6222 return true; 6223 } 6224 6225 /// Return the appropriate SDDbgValue based on N. 6226 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6227 DILocalVariable *Variable, 6228 DIExpression *Expr, 6229 const DebugLoc &dl, 6230 unsigned DbgSDNodeOrder) { 6231 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6232 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6233 // stack slot locations. 6234 // 6235 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6236 // debug values here after optimization: 6237 // 6238 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6239 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6240 // 6241 // Both describe the direct values of their associated variables. 6242 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6243 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6244 } 6245 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6246 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6247 } 6248 6249 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6250 switch (Intrinsic) { 6251 case Intrinsic::smul_fix: 6252 return ISD::SMULFIX; 6253 case Intrinsic::umul_fix: 6254 return ISD::UMULFIX; 6255 case Intrinsic::smul_fix_sat: 6256 return ISD::SMULFIXSAT; 6257 case Intrinsic::umul_fix_sat: 6258 return ISD::UMULFIXSAT; 6259 case Intrinsic::sdiv_fix: 6260 return ISD::SDIVFIX; 6261 case Intrinsic::udiv_fix: 6262 return ISD::UDIVFIX; 6263 case Intrinsic::sdiv_fix_sat: 6264 return ISD::SDIVFIXSAT; 6265 case Intrinsic::udiv_fix_sat: 6266 return ISD::UDIVFIXSAT; 6267 default: 6268 llvm_unreachable("Unhandled fixed point intrinsic"); 6269 } 6270 } 6271 6272 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6273 const char *FunctionName) { 6274 assert(FunctionName && "FunctionName must not be nullptr"); 6275 SDValue Callee = DAG.getExternalSymbol( 6276 FunctionName, 6277 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6278 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6279 } 6280 6281 /// Given a @llvm.call.preallocated.setup, return the corresponding 6282 /// preallocated call. 6283 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6284 assert(cast<CallBase>(PreallocatedSetup) 6285 ->getCalledFunction() 6286 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6287 "expected call_preallocated_setup Value"); 6288 for (const auto *U : PreallocatedSetup->users()) { 6289 auto *UseCall = cast<CallBase>(U); 6290 const Function *Fn = UseCall->getCalledFunction(); 6291 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6292 return UseCall; 6293 } 6294 } 6295 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6296 } 6297 6298 /// If DI is a debug value with an EntryValue expression, lower it using the 6299 /// corresponding physical register of the associated Argument value 6300 /// (guaranteed to exist by the verifier). 6301 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6302 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6303 DIExpression *Expr, DebugLoc DbgLoc) { 6304 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6305 return false; 6306 6307 // These properties are guaranteed by the verifier. 6308 const Argument *Arg = cast<Argument>(Values[0]); 6309 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6310 6311 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6312 if (ArgIt == FuncInfo.ValueMap.end()) { 6313 LLVM_DEBUG( 6314 dbgs() << "Dropping dbg.value: expression is entry_value but " 6315 "couldn't find an associated register for the Argument\n"); 6316 return true; 6317 } 6318 Register ArgVReg = ArgIt->getSecond(); 6319 6320 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6321 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6322 SDDbgValue *SDV = DAG.getVRegDbgValue( 6323 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6324 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6325 return true; 6326 } 6327 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6328 "couldn't find a physical register\n"); 6329 return true; 6330 } 6331 6332 /// Lower the call to the specified intrinsic function. 6333 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6334 unsigned Intrinsic) { 6335 SDLoc sdl = getCurSDLoc(); 6336 switch (Intrinsic) { 6337 case Intrinsic::experimental_convergence_anchor: 6338 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6339 break; 6340 case Intrinsic::experimental_convergence_entry: 6341 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6342 break; 6343 case Intrinsic::experimental_convergence_loop: { 6344 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6345 auto *Token = Bundle->Inputs[0].get(); 6346 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6347 getValue(Token))); 6348 break; 6349 } 6350 } 6351 } 6352 6353 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6354 unsigned IntrinsicID) { 6355 // For now, we're only lowering an 'add' histogram. 6356 // We can add others later, e.g. saturating adds, min/max. 6357 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6358 "Tried to lower unsupported histogram type"); 6359 SDLoc sdl = getCurSDLoc(); 6360 Value *Ptr = I.getOperand(0); 6361 SDValue Inc = getValue(I.getOperand(1)); 6362 SDValue Mask = getValue(I.getOperand(2)); 6363 6364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6365 DataLayout TargetDL = DAG.getDataLayout(); 6366 EVT VT = Inc.getValueType(); 6367 Align Alignment = DAG.getEVTAlign(VT); 6368 6369 const MDNode *Ranges = getRangeMetadata(I); 6370 6371 SDValue Root = DAG.getRoot(); 6372 SDValue Base; 6373 SDValue Index; 6374 ISD::MemIndexType IndexType; 6375 SDValue Scale; 6376 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6377 I.getParent(), VT.getScalarStoreSize()); 6378 6379 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6380 6381 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6382 MachinePointerInfo(AS), 6383 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6384 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6385 6386 if (!UniformBase) { 6387 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6388 Index = getValue(Ptr); 6389 IndexType = ISD::SIGNED_SCALED; 6390 Scale = 6391 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6392 } 6393 6394 EVT IdxVT = Index.getValueType(); 6395 EVT EltTy = IdxVT.getVectorElementType(); 6396 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6397 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6398 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6399 } 6400 6401 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6402 6403 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6404 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6405 Ops, MMO, IndexType); 6406 6407 setValue(&I, Histogram); 6408 DAG.setRoot(Histogram); 6409 } 6410 6411 /// Lower the call to the specified intrinsic function. 6412 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6413 unsigned Intrinsic) { 6414 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6415 SDLoc sdl = getCurSDLoc(); 6416 DebugLoc dl = getCurDebugLoc(); 6417 SDValue Res; 6418 6419 SDNodeFlags Flags; 6420 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6421 Flags.copyFMF(*FPOp); 6422 6423 switch (Intrinsic) { 6424 default: 6425 // By default, turn this into a target intrinsic node. 6426 visitTargetIntrinsic(I, Intrinsic); 6427 return; 6428 case Intrinsic::vscale: { 6429 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6430 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6431 return; 6432 } 6433 case Intrinsic::vastart: visitVAStart(I); return; 6434 case Intrinsic::vaend: visitVAEnd(I); return; 6435 case Intrinsic::vacopy: visitVACopy(I); return; 6436 case Intrinsic::returnaddress: 6437 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6438 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6439 getValue(I.getArgOperand(0)))); 6440 return; 6441 case Intrinsic::addressofreturnaddress: 6442 setValue(&I, 6443 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6444 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6445 return; 6446 case Intrinsic::sponentry: 6447 setValue(&I, 6448 DAG.getNode(ISD::SPONENTRY, sdl, 6449 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6450 return; 6451 case Intrinsic::frameaddress: 6452 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6453 TLI.getFrameIndexTy(DAG.getDataLayout()), 6454 getValue(I.getArgOperand(0)))); 6455 return; 6456 case Intrinsic::read_volatile_register: 6457 case Intrinsic::read_register: { 6458 Value *Reg = I.getArgOperand(0); 6459 SDValue Chain = getRoot(); 6460 SDValue RegName = 6461 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6462 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6463 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6464 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6465 setValue(&I, Res); 6466 DAG.setRoot(Res.getValue(1)); 6467 return; 6468 } 6469 case Intrinsic::write_register: { 6470 Value *Reg = I.getArgOperand(0); 6471 Value *RegValue = I.getArgOperand(1); 6472 SDValue Chain = getRoot(); 6473 SDValue RegName = 6474 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6475 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6476 RegName, getValue(RegValue))); 6477 return; 6478 } 6479 case Intrinsic::memcpy: { 6480 const auto &MCI = cast<MemCpyInst>(I); 6481 SDValue Op1 = getValue(I.getArgOperand(0)); 6482 SDValue Op2 = getValue(I.getArgOperand(1)); 6483 SDValue Op3 = getValue(I.getArgOperand(2)); 6484 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6485 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6486 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6487 Align Alignment = std::min(DstAlign, SrcAlign); 6488 bool isVol = MCI.isVolatile(); 6489 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6490 // node. 6491 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6492 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6493 /* AlwaysInline */ false, &I, std::nullopt, 6494 MachinePointerInfo(I.getArgOperand(0)), 6495 MachinePointerInfo(I.getArgOperand(1)), 6496 I.getAAMetadata(), AA); 6497 updateDAGForMaybeTailCall(MC); 6498 return; 6499 } 6500 case Intrinsic::memcpy_inline: { 6501 const auto &MCI = cast<MemCpyInlineInst>(I); 6502 SDValue Dst = getValue(I.getArgOperand(0)); 6503 SDValue Src = getValue(I.getArgOperand(1)); 6504 SDValue Size = getValue(I.getArgOperand(2)); 6505 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6506 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6507 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6508 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6509 Align Alignment = std::min(DstAlign, SrcAlign); 6510 bool isVol = MCI.isVolatile(); 6511 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6512 // node. 6513 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6514 /* AlwaysInline */ true, &I, std::nullopt, 6515 MachinePointerInfo(I.getArgOperand(0)), 6516 MachinePointerInfo(I.getArgOperand(1)), 6517 I.getAAMetadata(), AA); 6518 updateDAGForMaybeTailCall(MC); 6519 return; 6520 } 6521 case Intrinsic::memset: { 6522 const auto &MSI = cast<MemSetInst>(I); 6523 SDValue Op1 = getValue(I.getArgOperand(0)); 6524 SDValue Op2 = getValue(I.getArgOperand(1)); 6525 SDValue Op3 = getValue(I.getArgOperand(2)); 6526 // @llvm.memset defines 0 and 1 to both mean no alignment. 6527 Align Alignment = MSI.getDestAlign().valueOrOne(); 6528 bool isVol = MSI.isVolatile(); 6529 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6530 SDValue MS = DAG.getMemset( 6531 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6532 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6533 updateDAGForMaybeTailCall(MS); 6534 return; 6535 } 6536 case Intrinsic::memset_inline: { 6537 const auto &MSII = cast<MemSetInlineInst>(I); 6538 SDValue Dst = getValue(I.getArgOperand(0)); 6539 SDValue Value = getValue(I.getArgOperand(1)); 6540 SDValue Size = getValue(I.getArgOperand(2)); 6541 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6542 // @llvm.memset defines 0 and 1 to both mean no alignment. 6543 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6544 bool isVol = MSII.isVolatile(); 6545 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6546 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6547 /* AlwaysInline */ true, &I, 6548 MachinePointerInfo(I.getArgOperand(0)), 6549 I.getAAMetadata()); 6550 updateDAGForMaybeTailCall(MC); 6551 return; 6552 } 6553 case Intrinsic::memmove: { 6554 const auto &MMI = cast<MemMoveInst>(I); 6555 SDValue Op1 = getValue(I.getArgOperand(0)); 6556 SDValue Op2 = getValue(I.getArgOperand(1)); 6557 SDValue Op3 = getValue(I.getArgOperand(2)); 6558 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6559 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6560 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6561 Align Alignment = std::min(DstAlign, SrcAlign); 6562 bool isVol = MMI.isVolatile(); 6563 // FIXME: Support passing different dest/src alignments to the memmove DAG 6564 // node. 6565 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6566 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I, 6567 /* OverrideTailCall */ std::nullopt, 6568 MachinePointerInfo(I.getArgOperand(0)), 6569 MachinePointerInfo(I.getArgOperand(1)), 6570 I.getAAMetadata(), AA); 6571 updateDAGForMaybeTailCall(MM); 6572 return; 6573 } 6574 case Intrinsic::memcpy_element_unordered_atomic: { 6575 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6576 SDValue Dst = getValue(MI.getRawDest()); 6577 SDValue Src = getValue(MI.getRawSource()); 6578 SDValue Length = getValue(MI.getLength()); 6579 6580 Type *LengthTy = MI.getLength()->getType(); 6581 unsigned ElemSz = MI.getElementSizeInBytes(); 6582 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6583 SDValue MC = 6584 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6585 isTC, MachinePointerInfo(MI.getRawDest()), 6586 MachinePointerInfo(MI.getRawSource())); 6587 updateDAGForMaybeTailCall(MC); 6588 return; 6589 } 6590 case Intrinsic::memmove_element_unordered_atomic: { 6591 auto &MI = cast<AtomicMemMoveInst>(I); 6592 SDValue Dst = getValue(MI.getRawDest()); 6593 SDValue Src = getValue(MI.getRawSource()); 6594 SDValue Length = getValue(MI.getLength()); 6595 6596 Type *LengthTy = MI.getLength()->getType(); 6597 unsigned ElemSz = MI.getElementSizeInBytes(); 6598 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6599 SDValue MC = 6600 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6601 isTC, MachinePointerInfo(MI.getRawDest()), 6602 MachinePointerInfo(MI.getRawSource())); 6603 updateDAGForMaybeTailCall(MC); 6604 return; 6605 } 6606 case Intrinsic::memset_element_unordered_atomic: { 6607 auto &MI = cast<AtomicMemSetInst>(I); 6608 SDValue Dst = getValue(MI.getRawDest()); 6609 SDValue Val = getValue(MI.getValue()); 6610 SDValue Length = getValue(MI.getLength()); 6611 6612 Type *LengthTy = MI.getLength()->getType(); 6613 unsigned ElemSz = MI.getElementSizeInBytes(); 6614 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6615 SDValue MC = 6616 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6617 isTC, MachinePointerInfo(MI.getRawDest())); 6618 updateDAGForMaybeTailCall(MC); 6619 return; 6620 } 6621 case Intrinsic::call_preallocated_setup: { 6622 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6623 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6624 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6625 getRoot(), SrcValue); 6626 setValue(&I, Res); 6627 DAG.setRoot(Res); 6628 return; 6629 } 6630 case Intrinsic::call_preallocated_arg: { 6631 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6632 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6633 SDValue Ops[3]; 6634 Ops[0] = getRoot(); 6635 Ops[1] = SrcValue; 6636 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6637 MVT::i32); // arg index 6638 SDValue Res = DAG.getNode( 6639 ISD::PREALLOCATED_ARG, sdl, 6640 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6641 setValue(&I, Res); 6642 DAG.setRoot(Res.getValue(1)); 6643 return; 6644 } 6645 case Intrinsic::dbg_declare: { 6646 const auto &DI = cast<DbgDeclareInst>(I); 6647 // Debug intrinsics are handled separately in assignment tracking mode. 6648 // Some intrinsics are handled right after Argument lowering. 6649 if (AssignmentTrackingEnabled || 6650 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6651 return; 6652 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6653 DILocalVariable *Variable = DI.getVariable(); 6654 DIExpression *Expression = DI.getExpression(); 6655 dropDanglingDebugInfo(Variable, Expression); 6656 // Assume dbg.declare can not currently use DIArgList, i.e. 6657 // it is non-variadic. 6658 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6659 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6660 DI.getDebugLoc()); 6661 return; 6662 } 6663 case Intrinsic::dbg_label: { 6664 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6665 DILabel *Label = DI.getLabel(); 6666 assert(Label && "Missing label"); 6667 6668 SDDbgLabel *SDV; 6669 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6670 DAG.AddDbgLabel(SDV); 6671 return; 6672 } 6673 case Intrinsic::dbg_assign: { 6674 // Debug intrinsics are handled separately in assignment tracking mode. 6675 if (AssignmentTrackingEnabled) 6676 return; 6677 // If assignment tracking hasn't been enabled then fall through and treat 6678 // the dbg.assign as a dbg.value. 6679 [[fallthrough]]; 6680 } 6681 case Intrinsic::dbg_value: { 6682 // Debug intrinsics are handled separately in assignment tracking mode. 6683 if (AssignmentTrackingEnabled) 6684 return; 6685 const DbgValueInst &DI = cast<DbgValueInst>(I); 6686 assert(DI.getVariable() && "Missing variable"); 6687 6688 DILocalVariable *Variable = DI.getVariable(); 6689 DIExpression *Expression = DI.getExpression(); 6690 dropDanglingDebugInfo(Variable, Expression); 6691 6692 if (DI.isKillLocation()) { 6693 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6694 return; 6695 } 6696 6697 SmallVector<Value *, 4> Values(DI.getValues()); 6698 if (Values.empty()) 6699 return; 6700 6701 bool IsVariadic = DI.hasArgList(); 6702 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6703 SDNodeOrder, IsVariadic)) 6704 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6705 DI.getDebugLoc(), SDNodeOrder); 6706 return; 6707 } 6708 6709 case Intrinsic::eh_typeid_for: { 6710 // Find the type id for the given typeinfo. 6711 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6712 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6713 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6714 setValue(&I, Res); 6715 return; 6716 } 6717 6718 case Intrinsic::eh_return_i32: 6719 case Intrinsic::eh_return_i64: 6720 DAG.getMachineFunction().setCallsEHReturn(true); 6721 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6722 MVT::Other, 6723 getControlRoot(), 6724 getValue(I.getArgOperand(0)), 6725 getValue(I.getArgOperand(1)))); 6726 return; 6727 case Intrinsic::eh_unwind_init: 6728 DAG.getMachineFunction().setCallsUnwindInit(true); 6729 return; 6730 case Intrinsic::eh_dwarf_cfa: 6731 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6732 TLI.getPointerTy(DAG.getDataLayout()), 6733 getValue(I.getArgOperand(0)))); 6734 return; 6735 case Intrinsic::eh_sjlj_callsite: { 6736 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6737 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6738 6739 FuncInfo.setCurrentCallSite(CI->getZExtValue()); 6740 return; 6741 } 6742 case Intrinsic::eh_sjlj_functioncontext: { 6743 // Get and store the index of the function context. 6744 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6745 AllocaInst *FnCtx = 6746 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6747 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6748 MFI.setFunctionContextIndex(FI); 6749 return; 6750 } 6751 case Intrinsic::eh_sjlj_setjmp: { 6752 SDValue Ops[2]; 6753 Ops[0] = getRoot(); 6754 Ops[1] = getValue(I.getArgOperand(0)); 6755 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6756 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6757 setValue(&I, Op.getValue(0)); 6758 DAG.setRoot(Op.getValue(1)); 6759 return; 6760 } 6761 case Intrinsic::eh_sjlj_longjmp: 6762 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6763 getRoot(), getValue(I.getArgOperand(0)))); 6764 return; 6765 case Intrinsic::eh_sjlj_setup_dispatch: 6766 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6767 getRoot())); 6768 return; 6769 case Intrinsic::masked_gather: 6770 visitMaskedGather(I); 6771 return; 6772 case Intrinsic::masked_load: 6773 visitMaskedLoad(I); 6774 return; 6775 case Intrinsic::masked_scatter: 6776 visitMaskedScatter(I); 6777 return; 6778 case Intrinsic::masked_store: 6779 visitMaskedStore(I); 6780 return; 6781 case Intrinsic::masked_expandload: 6782 visitMaskedLoad(I, true /* IsExpanding */); 6783 return; 6784 case Intrinsic::masked_compressstore: 6785 visitMaskedStore(I, true /* IsCompressing */); 6786 return; 6787 case Intrinsic::powi: 6788 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6789 getValue(I.getArgOperand(1)), DAG)); 6790 return; 6791 case Intrinsic::log: 6792 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6793 return; 6794 case Intrinsic::log2: 6795 setValue(&I, 6796 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6797 return; 6798 case Intrinsic::log10: 6799 setValue(&I, 6800 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6801 return; 6802 case Intrinsic::exp: 6803 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6804 return; 6805 case Intrinsic::exp2: 6806 setValue(&I, 6807 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6808 return; 6809 case Intrinsic::pow: 6810 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6811 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6812 return; 6813 case Intrinsic::sqrt: 6814 case Intrinsic::fabs: 6815 case Intrinsic::sin: 6816 case Intrinsic::cos: 6817 case Intrinsic::tan: 6818 case Intrinsic::asin: 6819 case Intrinsic::acos: 6820 case Intrinsic::atan: 6821 case Intrinsic::sinh: 6822 case Intrinsic::cosh: 6823 case Intrinsic::tanh: 6824 case Intrinsic::exp10: 6825 case Intrinsic::floor: 6826 case Intrinsic::ceil: 6827 case Intrinsic::trunc: 6828 case Intrinsic::rint: 6829 case Intrinsic::nearbyint: 6830 case Intrinsic::round: 6831 case Intrinsic::roundeven: 6832 case Intrinsic::canonicalize: { 6833 unsigned Opcode; 6834 // clang-format off 6835 switch (Intrinsic) { 6836 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6837 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6838 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6839 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6840 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6841 case Intrinsic::tan: Opcode = ISD::FTAN; break; 6842 case Intrinsic::asin: Opcode = ISD::FASIN; break; 6843 case Intrinsic::acos: Opcode = ISD::FACOS; break; 6844 case Intrinsic::atan: Opcode = ISD::FATAN; break; 6845 case Intrinsic::sinh: Opcode = ISD::FSINH; break; 6846 case Intrinsic::cosh: Opcode = ISD::FCOSH; break; 6847 case Intrinsic::tanh: Opcode = ISD::FTANH; break; 6848 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6849 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6850 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6851 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6852 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6853 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6854 case Intrinsic::round: Opcode = ISD::FROUND; break; 6855 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6856 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6857 } 6858 // clang-format on 6859 6860 setValue(&I, DAG.getNode(Opcode, sdl, 6861 getValue(I.getArgOperand(0)).getValueType(), 6862 getValue(I.getArgOperand(0)), Flags)); 6863 return; 6864 } 6865 case Intrinsic::atan2: 6866 setValue(&I, DAG.getNode(ISD::FATAN2, sdl, 6867 getValue(I.getArgOperand(0)).getValueType(), 6868 getValue(I.getArgOperand(0)), 6869 getValue(I.getArgOperand(1)), Flags)); 6870 return; 6871 case Intrinsic::lround: 6872 case Intrinsic::llround: 6873 case Intrinsic::lrint: 6874 case Intrinsic::llrint: { 6875 unsigned Opcode; 6876 // clang-format off 6877 switch (Intrinsic) { 6878 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6879 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6880 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6881 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6882 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6883 } 6884 // clang-format on 6885 6886 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6887 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6888 getValue(I.getArgOperand(0)))); 6889 return; 6890 } 6891 case Intrinsic::minnum: 6892 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6893 getValue(I.getArgOperand(0)).getValueType(), 6894 getValue(I.getArgOperand(0)), 6895 getValue(I.getArgOperand(1)), Flags)); 6896 return; 6897 case Intrinsic::maxnum: 6898 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6899 getValue(I.getArgOperand(0)).getValueType(), 6900 getValue(I.getArgOperand(0)), 6901 getValue(I.getArgOperand(1)), Flags)); 6902 return; 6903 case Intrinsic::minimum: 6904 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6905 getValue(I.getArgOperand(0)).getValueType(), 6906 getValue(I.getArgOperand(0)), 6907 getValue(I.getArgOperand(1)), Flags)); 6908 return; 6909 case Intrinsic::maximum: 6910 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6911 getValue(I.getArgOperand(0)).getValueType(), 6912 getValue(I.getArgOperand(0)), 6913 getValue(I.getArgOperand(1)), Flags)); 6914 return; 6915 case Intrinsic::minimumnum: 6916 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl, 6917 getValue(I.getArgOperand(0)).getValueType(), 6918 getValue(I.getArgOperand(0)), 6919 getValue(I.getArgOperand(1)), Flags)); 6920 return; 6921 case Intrinsic::maximumnum: 6922 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl, 6923 getValue(I.getArgOperand(0)).getValueType(), 6924 getValue(I.getArgOperand(0)), 6925 getValue(I.getArgOperand(1)), Flags)); 6926 return; 6927 case Intrinsic::copysign: 6928 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6929 getValue(I.getArgOperand(0)).getValueType(), 6930 getValue(I.getArgOperand(0)), 6931 getValue(I.getArgOperand(1)), Flags)); 6932 return; 6933 case Intrinsic::ldexp: 6934 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6935 getValue(I.getArgOperand(0)).getValueType(), 6936 getValue(I.getArgOperand(0)), 6937 getValue(I.getArgOperand(1)), Flags)); 6938 return; 6939 case Intrinsic::sincos: 6940 case Intrinsic::frexp: { 6941 unsigned Opcode; 6942 switch (Intrinsic) { 6943 default: 6944 llvm_unreachable("unexpected intrinsic"); 6945 case Intrinsic::sincos: 6946 Opcode = ISD::FSINCOS; 6947 break; 6948 case Intrinsic::frexp: 6949 Opcode = ISD::FFREXP; 6950 break; 6951 } 6952 SmallVector<EVT, 2> ValueVTs; 6953 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6954 SDVTList VTs = DAG.getVTList(ValueVTs); 6955 setValue( 6956 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags)); 6957 return; 6958 } 6959 case Intrinsic::arithmetic_fence: { 6960 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6961 getValue(I.getArgOperand(0)).getValueType(), 6962 getValue(I.getArgOperand(0)), Flags)); 6963 return; 6964 } 6965 case Intrinsic::fma: 6966 setValue(&I, DAG.getNode( 6967 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6968 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6969 getValue(I.getArgOperand(2)), Flags)); 6970 return; 6971 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6972 case Intrinsic::INTRINSIC: 6973 #include "llvm/IR/ConstrainedOps.def" 6974 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6975 return; 6976 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6977 #include "llvm/IR/VPIntrinsics.def" 6978 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6979 return; 6980 case Intrinsic::fptrunc_round: { 6981 // Get the last argument, the metadata and convert it to an integer in the 6982 // call 6983 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6984 std::optional<RoundingMode> RoundMode = 6985 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6986 6987 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6988 6989 // Propagate fast-math-flags from IR to node(s). 6990 SDNodeFlags Flags; 6991 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6992 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6993 6994 SDValue Result; 6995 Result = DAG.getNode( 6996 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6997 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32)); 6998 setValue(&I, Result); 6999 7000 return; 7001 } 7002 case Intrinsic::fmuladd: { 7003 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7004 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7005 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7006 setValue(&I, DAG.getNode(ISD::FMA, sdl, 7007 getValue(I.getArgOperand(0)).getValueType(), 7008 getValue(I.getArgOperand(0)), 7009 getValue(I.getArgOperand(1)), 7010 getValue(I.getArgOperand(2)), Flags)); 7011 } else { 7012 // TODO: Intrinsic calls should have fast-math-flags. 7013 SDValue Mul = DAG.getNode( 7014 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 7015 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 7016 SDValue Add = DAG.getNode(ISD::FADD, sdl, 7017 getValue(I.getArgOperand(0)).getValueType(), 7018 Mul, getValue(I.getArgOperand(2)), Flags); 7019 setValue(&I, Add); 7020 } 7021 return; 7022 } 7023 case Intrinsic::convert_to_fp16: 7024 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 7025 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 7026 getValue(I.getArgOperand(0)), 7027 DAG.getTargetConstant(0, sdl, 7028 MVT::i32)))); 7029 return; 7030 case Intrinsic::convert_from_fp16: 7031 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 7032 TLI.getValueType(DAG.getDataLayout(), I.getType()), 7033 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 7034 getValue(I.getArgOperand(0))))); 7035 return; 7036 case Intrinsic::fptosi_sat: { 7037 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7038 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 7039 getValue(I.getArgOperand(0)), 7040 DAG.getValueType(VT.getScalarType()))); 7041 return; 7042 } 7043 case Intrinsic::fptoui_sat: { 7044 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7045 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 7046 getValue(I.getArgOperand(0)), 7047 DAG.getValueType(VT.getScalarType()))); 7048 return; 7049 } 7050 case Intrinsic::set_rounding: 7051 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 7052 {getRoot(), getValue(I.getArgOperand(0))}); 7053 setValue(&I, Res); 7054 DAG.setRoot(Res.getValue(0)); 7055 return; 7056 case Intrinsic::is_fpclass: { 7057 const DataLayout DLayout = DAG.getDataLayout(); 7058 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 7059 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 7060 FPClassTest Test = static_cast<FPClassTest>( 7061 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 7062 MachineFunction &MF = DAG.getMachineFunction(); 7063 const Function &F = MF.getFunction(); 7064 SDValue Op = getValue(I.getArgOperand(0)); 7065 SDNodeFlags Flags; 7066 Flags.setNoFPExcept( 7067 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 7068 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 7069 // expansion can use illegal types. Making expansion early allows 7070 // legalizing these types prior to selection. 7071 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) && 7072 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) { 7073 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 7074 setValue(&I, Result); 7075 return; 7076 } 7077 7078 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 7079 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 7080 setValue(&I, V); 7081 return; 7082 } 7083 case Intrinsic::get_fpenv: { 7084 const DataLayout DLayout = DAG.getDataLayout(); 7085 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 7086 Align TempAlign = DAG.getEVTAlign(EnvVT); 7087 SDValue Chain = getRoot(); 7088 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 7089 // and temporary storage in stack. 7090 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 7091 Res = DAG.getNode( 7092 ISD::GET_FPENV, sdl, 7093 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7094 MVT::Other), 7095 Chain); 7096 } else { 7097 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7098 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7099 auto MPI = 7100 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7101 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7102 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 7103 TempAlign); 7104 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7105 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 7106 } 7107 setValue(&I, Res); 7108 DAG.setRoot(Res.getValue(1)); 7109 return; 7110 } 7111 case Intrinsic::set_fpenv: { 7112 const DataLayout DLayout = DAG.getDataLayout(); 7113 SDValue Env = getValue(I.getArgOperand(0)); 7114 EVT EnvVT = Env.getValueType(); 7115 Align TempAlign = DAG.getEVTAlign(EnvVT); 7116 SDValue Chain = getRoot(); 7117 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7118 // environment from memory. 7119 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7120 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7121 } else { 7122 // Allocate space in stack, copy environment bits into it and use this 7123 // memory in SET_FPENV_MEM. 7124 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7125 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7126 auto MPI = 7127 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7128 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7129 MachineMemOperand::MOStore); 7130 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7131 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7132 TempAlign); 7133 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7134 } 7135 DAG.setRoot(Chain); 7136 return; 7137 } 7138 case Intrinsic::reset_fpenv: 7139 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7140 return; 7141 case Intrinsic::get_fpmode: 7142 Res = DAG.getNode( 7143 ISD::GET_FPMODE, sdl, 7144 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7145 MVT::Other), 7146 DAG.getRoot()); 7147 setValue(&I, Res); 7148 DAG.setRoot(Res.getValue(1)); 7149 return; 7150 case Intrinsic::set_fpmode: 7151 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7152 getValue(I.getArgOperand(0))); 7153 DAG.setRoot(Res); 7154 return; 7155 case Intrinsic::reset_fpmode: { 7156 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7157 DAG.setRoot(Res); 7158 return; 7159 } 7160 case Intrinsic::pcmarker: { 7161 SDValue Tmp = getValue(I.getArgOperand(0)); 7162 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7163 return; 7164 } 7165 case Intrinsic::readcyclecounter: { 7166 SDValue Op = getRoot(); 7167 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7168 DAG.getVTList(MVT::i64, MVT::Other), Op); 7169 setValue(&I, Res); 7170 DAG.setRoot(Res.getValue(1)); 7171 return; 7172 } 7173 case Intrinsic::readsteadycounter: { 7174 SDValue Op = getRoot(); 7175 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 7176 DAG.getVTList(MVT::i64, MVT::Other), Op); 7177 setValue(&I, Res); 7178 DAG.setRoot(Res.getValue(1)); 7179 return; 7180 } 7181 case Intrinsic::bitreverse: 7182 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7183 getValue(I.getArgOperand(0)).getValueType(), 7184 getValue(I.getArgOperand(0)))); 7185 return; 7186 case Intrinsic::bswap: 7187 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7188 getValue(I.getArgOperand(0)).getValueType(), 7189 getValue(I.getArgOperand(0)))); 7190 return; 7191 case Intrinsic::cttz: { 7192 SDValue Arg = getValue(I.getArgOperand(0)); 7193 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7194 EVT Ty = Arg.getValueType(); 7195 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7196 sdl, Ty, Arg)); 7197 return; 7198 } 7199 case Intrinsic::ctlz: { 7200 SDValue Arg = getValue(I.getArgOperand(0)); 7201 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7202 EVT Ty = Arg.getValueType(); 7203 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7204 sdl, Ty, Arg)); 7205 return; 7206 } 7207 case Intrinsic::ctpop: { 7208 SDValue Arg = getValue(I.getArgOperand(0)); 7209 EVT Ty = Arg.getValueType(); 7210 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7211 return; 7212 } 7213 case Intrinsic::fshl: 7214 case Intrinsic::fshr: { 7215 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7216 SDValue X = getValue(I.getArgOperand(0)); 7217 SDValue Y = getValue(I.getArgOperand(1)); 7218 SDValue Z = getValue(I.getArgOperand(2)); 7219 EVT VT = X.getValueType(); 7220 7221 if (X == Y) { 7222 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7223 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7224 } else { 7225 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7226 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7227 } 7228 return; 7229 } 7230 case Intrinsic::sadd_sat: { 7231 SDValue Op1 = getValue(I.getArgOperand(0)); 7232 SDValue Op2 = getValue(I.getArgOperand(1)); 7233 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7234 return; 7235 } 7236 case Intrinsic::uadd_sat: { 7237 SDValue Op1 = getValue(I.getArgOperand(0)); 7238 SDValue Op2 = getValue(I.getArgOperand(1)); 7239 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7240 return; 7241 } 7242 case Intrinsic::ssub_sat: { 7243 SDValue Op1 = getValue(I.getArgOperand(0)); 7244 SDValue Op2 = getValue(I.getArgOperand(1)); 7245 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7246 return; 7247 } 7248 case Intrinsic::usub_sat: { 7249 SDValue Op1 = getValue(I.getArgOperand(0)); 7250 SDValue Op2 = getValue(I.getArgOperand(1)); 7251 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7252 return; 7253 } 7254 case Intrinsic::sshl_sat: { 7255 SDValue Op1 = getValue(I.getArgOperand(0)); 7256 SDValue Op2 = getValue(I.getArgOperand(1)); 7257 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7258 return; 7259 } 7260 case Intrinsic::ushl_sat: { 7261 SDValue Op1 = getValue(I.getArgOperand(0)); 7262 SDValue Op2 = getValue(I.getArgOperand(1)); 7263 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7264 return; 7265 } 7266 case Intrinsic::smul_fix: 7267 case Intrinsic::umul_fix: 7268 case Intrinsic::smul_fix_sat: 7269 case Intrinsic::umul_fix_sat: { 7270 SDValue Op1 = getValue(I.getArgOperand(0)); 7271 SDValue Op2 = getValue(I.getArgOperand(1)); 7272 SDValue Op3 = getValue(I.getArgOperand(2)); 7273 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7274 Op1.getValueType(), Op1, Op2, Op3)); 7275 return; 7276 } 7277 case Intrinsic::sdiv_fix: 7278 case Intrinsic::udiv_fix: 7279 case Intrinsic::sdiv_fix_sat: 7280 case Intrinsic::udiv_fix_sat: { 7281 SDValue Op1 = getValue(I.getArgOperand(0)); 7282 SDValue Op2 = getValue(I.getArgOperand(1)); 7283 SDValue Op3 = getValue(I.getArgOperand(2)); 7284 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7285 Op1, Op2, Op3, DAG, TLI)); 7286 return; 7287 } 7288 case Intrinsic::smax: { 7289 SDValue Op1 = getValue(I.getArgOperand(0)); 7290 SDValue Op2 = getValue(I.getArgOperand(1)); 7291 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7292 return; 7293 } 7294 case Intrinsic::smin: { 7295 SDValue Op1 = getValue(I.getArgOperand(0)); 7296 SDValue Op2 = getValue(I.getArgOperand(1)); 7297 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7298 return; 7299 } 7300 case Intrinsic::umax: { 7301 SDValue Op1 = getValue(I.getArgOperand(0)); 7302 SDValue Op2 = getValue(I.getArgOperand(1)); 7303 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7304 return; 7305 } 7306 case Intrinsic::umin: { 7307 SDValue Op1 = getValue(I.getArgOperand(0)); 7308 SDValue Op2 = getValue(I.getArgOperand(1)); 7309 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7310 return; 7311 } 7312 case Intrinsic::abs: { 7313 // TODO: Preserve "int min is poison" arg in SDAG? 7314 SDValue Op1 = getValue(I.getArgOperand(0)); 7315 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7316 return; 7317 } 7318 case Intrinsic::scmp: { 7319 SDValue Op1 = getValue(I.getArgOperand(0)); 7320 SDValue Op2 = getValue(I.getArgOperand(1)); 7321 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7322 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2)); 7323 break; 7324 } 7325 case Intrinsic::ucmp: { 7326 SDValue Op1 = getValue(I.getArgOperand(0)); 7327 SDValue Op2 = getValue(I.getArgOperand(1)); 7328 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7329 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2)); 7330 break; 7331 } 7332 case Intrinsic::stacksave: { 7333 SDValue Op = getRoot(); 7334 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7335 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7336 setValue(&I, Res); 7337 DAG.setRoot(Res.getValue(1)); 7338 return; 7339 } 7340 case Intrinsic::stackrestore: 7341 Res = getValue(I.getArgOperand(0)); 7342 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7343 return; 7344 case Intrinsic::get_dynamic_area_offset: { 7345 SDValue Op = getRoot(); 7346 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7347 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7348 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7349 // target. 7350 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7351 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7352 " intrinsic!"); 7353 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7354 Op); 7355 DAG.setRoot(Op); 7356 setValue(&I, Res); 7357 return; 7358 } 7359 case Intrinsic::stackguard: { 7360 MachineFunction &MF = DAG.getMachineFunction(); 7361 const Module &M = *MF.getFunction().getParent(); 7362 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7363 SDValue Chain = getRoot(); 7364 if (TLI.useLoadStackGuardNode(M)) { 7365 Res = getLoadStackGuard(DAG, sdl, Chain); 7366 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7367 } else { 7368 const Value *Global = TLI.getSDagStackGuard(M); 7369 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7370 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7371 MachinePointerInfo(Global, 0), Align, 7372 MachineMemOperand::MOVolatile); 7373 } 7374 if (TLI.useStackGuardXorFP()) 7375 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7376 DAG.setRoot(Chain); 7377 setValue(&I, Res); 7378 return; 7379 } 7380 case Intrinsic::stackprotector: { 7381 // Emit code into the DAG to store the stack guard onto the stack. 7382 MachineFunction &MF = DAG.getMachineFunction(); 7383 MachineFrameInfo &MFI = MF.getFrameInfo(); 7384 const Module &M = *MF.getFunction().getParent(); 7385 SDValue Src, Chain = getRoot(); 7386 7387 if (TLI.useLoadStackGuardNode(M)) 7388 Src = getLoadStackGuard(DAG, sdl, Chain); 7389 else 7390 Src = getValue(I.getArgOperand(0)); // The guard's value. 7391 7392 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7393 7394 int FI = FuncInfo.StaticAllocaMap[Slot]; 7395 MFI.setStackProtectorIndex(FI); 7396 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7397 7398 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7399 7400 // Store the stack protector onto the stack. 7401 Res = DAG.getStore( 7402 Chain, sdl, Src, FIN, 7403 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7404 MaybeAlign(), MachineMemOperand::MOVolatile); 7405 setValue(&I, Res); 7406 DAG.setRoot(Res); 7407 return; 7408 } 7409 case Intrinsic::objectsize: 7410 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7411 7412 case Intrinsic::is_constant: 7413 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7414 7415 case Intrinsic::annotation: 7416 case Intrinsic::ptr_annotation: 7417 case Intrinsic::launder_invariant_group: 7418 case Intrinsic::strip_invariant_group: 7419 // Drop the intrinsic, but forward the value 7420 setValue(&I, getValue(I.getOperand(0))); 7421 return; 7422 7423 case Intrinsic::assume: 7424 case Intrinsic::experimental_noalias_scope_decl: 7425 case Intrinsic::var_annotation: 7426 case Intrinsic::sideeffect: 7427 // Discard annotate attributes, noalias scope declarations, assumptions, and 7428 // artificial side-effects. 7429 return; 7430 7431 case Intrinsic::codeview_annotation: { 7432 // Emit a label associated with this metadata. 7433 MachineFunction &MF = DAG.getMachineFunction(); 7434 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true); 7435 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7436 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7437 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7438 DAG.setRoot(Res); 7439 return; 7440 } 7441 7442 case Intrinsic::init_trampoline: { 7443 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7444 7445 SDValue Ops[6]; 7446 Ops[0] = getRoot(); 7447 Ops[1] = getValue(I.getArgOperand(0)); 7448 Ops[2] = getValue(I.getArgOperand(1)); 7449 Ops[3] = getValue(I.getArgOperand(2)); 7450 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7451 Ops[5] = DAG.getSrcValue(F); 7452 7453 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7454 7455 DAG.setRoot(Res); 7456 return; 7457 } 7458 case Intrinsic::adjust_trampoline: 7459 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7460 TLI.getPointerTy(DAG.getDataLayout()), 7461 getValue(I.getArgOperand(0)))); 7462 return; 7463 case Intrinsic::gcroot: { 7464 assert(DAG.getMachineFunction().getFunction().hasGC() && 7465 "only valid in functions with gc specified, enforced by Verifier"); 7466 assert(GFI && "implied by previous"); 7467 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7468 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7469 7470 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7471 GFI->addStackRoot(FI->getIndex(), TypeMap); 7472 return; 7473 } 7474 case Intrinsic::gcread: 7475 case Intrinsic::gcwrite: 7476 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7477 case Intrinsic::get_rounding: 7478 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7479 setValue(&I, Res); 7480 DAG.setRoot(Res.getValue(1)); 7481 return; 7482 7483 case Intrinsic::expect: 7484 // Just replace __builtin_expect(exp, c) with EXP. 7485 setValue(&I, getValue(I.getArgOperand(0))); 7486 return; 7487 7488 case Intrinsic::ubsantrap: 7489 case Intrinsic::debugtrap: 7490 case Intrinsic::trap: { 7491 StringRef TrapFuncName = 7492 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7493 if (TrapFuncName.empty()) { 7494 switch (Intrinsic) { 7495 case Intrinsic::trap: 7496 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7497 break; 7498 case Intrinsic::debugtrap: 7499 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7500 break; 7501 case Intrinsic::ubsantrap: 7502 DAG.setRoot(DAG.getNode( 7503 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7504 DAG.getTargetConstant( 7505 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7506 MVT::i32))); 7507 break; 7508 default: llvm_unreachable("unknown trap intrinsic"); 7509 } 7510 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(), 7511 I.hasFnAttr(Attribute::NoMerge)); 7512 return; 7513 } 7514 TargetLowering::ArgListTy Args; 7515 if (Intrinsic == Intrinsic::ubsantrap) { 7516 Args.push_back(TargetLoweringBase::ArgListEntry()); 7517 Args[0].Val = I.getArgOperand(0); 7518 Args[0].Node = getValue(Args[0].Val); 7519 Args[0].Ty = Args[0].Val->getType(); 7520 } 7521 7522 TargetLowering::CallLoweringInfo CLI(DAG); 7523 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7524 CallingConv::C, I.getType(), 7525 DAG.getExternalSymbol(TrapFuncName.data(), 7526 TLI.getPointerTy(DAG.getDataLayout())), 7527 std::move(Args)); 7528 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge); 7529 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7530 DAG.setRoot(Result.second); 7531 return; 7532 } 7533 7534 case Intrinsic::allow_runtime_check: 7535 case Intrinsic::allow_ubsan_check: 7536 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7537 return; 7538 7539 case Intrinsic::uadd_with_overflow: 7540 case Intrinsic::sadd_with_overflow: 7541 case Intrinsic::usub_with_overflow: 7542 case Intrinsic::ssub_with_overflow: 7543 case Intrinsic::umul_with_overflow: 7544 case Intrinsic::smul_with_overflow: { 7545 ISD::NodeType Op; 7546 switch (Intrinsic) { 7547 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7548 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7549 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7550 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7551 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7552 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7553 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7554 } 7555 SDValue Op1 = getValue(I.getArgOperand(0)); 7556 SDValue Op2 = getValue(I.getArgOperand(1)); 7557 7558 EVT ResultVT = Op1.getValueType(); 7559 EVT OverflowVT = MVT::i1; 7560 if (ResultVT.isVector()) 7561 OverflowVT = EVT::getVectorVT( 7562 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7563 7564 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7565 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7566 return; 7567 } 7568 case Intrinsic::prefetch: { 7569 SDValue Ops[5]; 7570 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7571 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7572 Ops[0] = DAG.getRoot(); 7573 Ops[1] = getValue(I.getArgOperand(0)); 7574 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7575 MVT::i32); 7576 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7577 MVT::i32); 7578 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7579 MVT::i32); 7580 SDValue Result = DAG.getMemIntrinsicNode( 7581 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7582 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7583 /* align */ std::nullopt, Flags); 7584 7585 // Chain the prefetch in parallel with any pending loads, to stay out of 7586 // the way of later optimizations. 7587 PendingLoads.push_back(Result); 7588 Result = getRoot(); 7589 DAG.setRoot(Result); 7590 return; 7591 } 7592 case Intrinsic::lifetime_start: 7593 case Intrinsic::lifetime_end: { 7594 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7595 // Stack coloring is not enabled in O0, discard region information. 7596 if (TM.getOptLevel() == CodeGenOptLevel::None) 7597 return; 7598 7599 const int64_t ObjectSize = 7600 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7601 Value *const ObjectPtr = I.getArgOperand(1); 7602 SmallVector<const Value *, 4> Allocas; 7603 getUnderlyingObjects(ObjectPtr, Allocas); 7604 7605 for (const Value *Alloca : Allocas) { 7606 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7607 7608 // Could not find an Alloca. 7609 if (!LifetimeObject) 7610 continue; 7611 7612 // First check that the Alloca is static, otherwise it won't have a 7613 // valid frame index. 7614 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7615 if (SI == FuncInfo.StaticAllocaMap.end()) 7616 return; 7617 7618 const int FrameIndex = SI->second; 7619 int64_t Offset; 7620 if (GetPointerBaseWithConstantOffset( 7621 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7622 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7623 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7624 Offset); 7625 DAG.setRoot(Res); 7626 } 7627 return; 7628 } 7629 case Intrinsic::pseudoprobe: { 7630 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7631 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7632 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7633 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7634 DAG.setRoot(Res); 7635 return; 7636 } 7637 case Intrinsic::invariant_start: 7638 // Discard region information. 7639 setValue(&I, 7640 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7641 return; 7642 case Intrinsic::invariant_end: 7643 // Discard region information. 7644 return; 7645 case Intrinsic::clear_cache: { 7646 SDValue InputChain = DAG.getRoot(); 7647 SDValue StartVal = getValue(I.getArgOperand(0)); 7648 SDValue EndVal = getValue(I.getArgOperand(1)); 7649 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7650 {InputChain, StartVal, EndVal}); 7651 setValue(&I, Res); 7652 DAG.setRoot(Res); 7653 return; 7654 } 7655 case Intrinsic::donothing: 7656 case Intrinsic::seh_try_begin: 7657 case Intrinsic::seh_scope_begin: 7658 case Intrinsic::seh_try_end: 7659 case Intrinsic::seh_scope_end: 7660 // ignore 7661 return; 7662 case Intrinsic::experimental_stackmap: 7663 visitStackmap(I); 7664 return; 7665 case Intrinsic::experimental_patchpoint_void: 7666 case Intrinsic::experimental_patchpoint: 7667 visitPatchpoint(I); 7668 return; 7669 case Intrinsic::experimental_gc_statepoint: 7670 LowerStatepoint(cast<GCStatepointInst>(I)); 7671 return; 7672 case Intrinsic::experimental_gc_result: 7673 visitGCResult(cast<GCResultInst>(I)); 7674 return; 7675 case Intrinsic::experimental_gc_relocate: 7676 visitGCRelocate(cast<GCRelocateInst>(I)); 7677 return; 7678 case Intrinsic::instrprof_cover: 7679 llvm_unreachable("instrprof failed to lower a cover"); 7680 case Intrinsic::instrprof_increment: 7681 llvm_unreachable("instrprof failed to lower an increment"); 7682 case Intrinsic::instrprof_timestamp: 7683 llvm_unreachable("instrprof failed to lower a timestamp"); 7684 case Intrinsic::instrprof_value_profile: 7685 llvm_unreachable("instrprof failed to lower a value profiling call"); 7686 case Intrinsic::instrprof_mcdc_parameters: 7687 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7688 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7689 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7690 case Intrinsic::localescape: { 7691 MachineFunction &MF = DAG.getMachineFunction(); 7692 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7693 7694 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7695 // is the same on all targets. 7696 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7697 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7698 if (isa<ConstantPointerNull>(Arg)) 7699 continue; // Skip null pointers. They represent a hole in index space. 7700 AllocaInst *Slot = cast<AllocaInst>(Arg); 7701 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7702 "can only escape static allocas"); 7703 int FI = FuncInfo.StaticAllocaMap[Slot]; 7704 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7705 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7707 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7708 .addSym(FrameAllocSym) 7709 .addFrameIndex(FI); 7710 } 7711 7712 return; 7713 } 7714 7715 case Intrinsic::localrecover: { 7716 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7717 MachineFunction &MF = DAG.getMachineFunction(); 7718 7719 // Get the symbol that defines the frame offset. 7720 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7721 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7722 unsigned IdxVal = 7723 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7724 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol( 7725 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7726 7727 Value *FP = I.getArgOperand(1); 7728 SDValue FPVal = getValue(FP); 7729 EVT PtrVT = FPVal.getValueType(); 7730 7731 // Create a MCSymbol for the label to avoid any target lowering 7732 // that would make this PC relative. 7733 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7734 SDValue OffsetVal = 7735 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7736 7737 // Add the offset to the FP. 7738 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7739 setValue(&I, Add); 7740 7741 return; 7742 } 7743 7744 case Intrinsic::fake_use: { 7745 Value *V = I.getArgOperand(0); 7746 SDValue Ops[2]; 7747 // For Values not declared or previously used in this basic block, the 7748 // NodeMap will not have an entry, and `getValue` will assert if V has no 7749 // valid register value. 7750 auto FakeUseValue = [&]() -> SDValue { 7751 SDValue &N = NodeMap[V]; 7752 if (N.getNode()) 7753 return N; 7754 7755 // If there's a virtual register allocated and initialized for this 7756 // value, use it. 7757 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 7758 return copyFromReg; 7759 // FIXME: Do we want to preserve constants? It seems pointless. 7760 if (isa<Constant>(V)) 7761 return getValue(V); 7762 return SDValue(); 7763 }(); 7764 if (!FakeUseValue || FakeUseValue.isUndef()) 7765 return; 7766 Ops[0] = getRoot(); 7767 Ops[1] = FakeUseValue; 7768 // Also, do not translate a fake use with an undef operand, or any other 7769 // empty SDValues. 7770 if (!Ops[1] || Ops[1].isUndef()) 7771 return; 7772 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops)); 7773 return; 7774 } 7775 7776 case Intrinsic::eh_exceptionpointer: 7777 case Intrinsic::eh_exceptioncode: { 7778 // Get the exception pointer vreg, copy from it, and resize it to fit. 7779 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7780 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7781 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7782 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7783 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7784 if (Intrinsic == Intrinsic::eh_exceptioncode) 7785 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7786 setValue(&I, N); 7787 return; 7788 } 7789 case Intrinsic::xray_customevent: { 7790 // Here we want to make sure that the intrinsic behaves as if it has a 7791 // specific calling convention. 7792 const auto &Triple = DAG.getTarget().getTargetTriple(); 7793 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7794 return; 7795 7796 SmallVector<SDValue, 8> Ops; 7797 7798 // We want to say that we always want the arguments in registers. 7799 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7800 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7801 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7802 SDValue Chain = getRoot(); 7803 Ops.push_back(LogEntryVal); 7804 Ops.push_back(StrSizeVal); 7805 Ops.push_back(Chain); 7806 7807 // We need to enforce the calling convention for the callsite, so that 7808 // argument ordering is enforced correctly, and that register allocation can 7809 // see that some registers may be assumed clobbered and have to preserve 7810 // them across calls to the intrinsic. 7811 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7812 sdl, NodeTys, Ops); 7813 SDValue patchableNode = SDValue(MN, 0); 7814 DAG.setRoot(patchableNode); 7815 setValue(&I, patchableNode); 7816 return; 7817 } 7818 case Intrinsic::xray_typedevent: { 7819 // Here we want to make sure that the intrinsic behaves as if it has a 7820 // specific calling convention. 7821 const auto &Triple = DAG.getTarget().getTargetTriple(); 7822 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7823 return; 7824 7825 SmallVector<SDValue, 8> Ops; 7826 7827 // We want to say that we always want the arguments in registers. 7828 // It's unclear to me how manipulating the selection DAG here forces callers 7829 // to provide arguments in registers instead of on the stack. 7830 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7831 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7832 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7833 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7834 SDValue Chain = getRoot(); 7835 Ops.push_back(LogTypeId); 7836 Ops.push_back(LogEntryVal); 7837 Ops.push_back(StrSizeVal); 7838 Ops.push_back(Chain); 7839 7840 // We need to enforce the calling convention for the callsite, so that 7841 // argument ordering is enforced correctly, and that register allocation can 7842 // see that some registers may be assumed clobbered and have to preserve 7843 // them across calls to the intrinsic. 7844 MachineSDNode *MN = DAG.getMachineNode( 7845 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7846 SDValue patchableNode = SDValue(MN, 0); 7847 DAG.setRoot(patchableNode); 7848 setValue(&I, patchableNode); 7849 return; 7850 } 7851 case Intrinsic::experimental_deoptimize: 7852 LowerDeoptimizeCall(&I); 7853 return; 7854 case Intrinsic::stepvector: 7855 visitStepVector(I); 7856 return; 7857 case Intrinsic::vector_reduce_fadd: 7858 case Intrinsic::vector_reduce_fmul: 7859 case Intrinsic::vector_reduce_add: 7860 case Intrinsic::vector_reduce_mul: 7861 case Intrinsic::vector_reduce_and: 7862 case Intrinsic::vector_reduce_or: 7863 case Intrinsic::vector_reduce_xor: 7864 case Intrinsic::vector_reduce_smax: 7865 case Intrinsic::vector_reduce_smin: 7866 case Intrinsic::vector_reduce_umax: 7867 case Intrinsic::vector_reduce_umin: 7868 case Intrinsic::vector_reduce_fmax: 7869 case Intrinsic::vector_reduce_fmin: 7870 case Intrinsic::vector_reduce_fmaximum: 7871 case Intrinsic::vector_reduce_fminimum: 7872 visitVectorReduce(I, Intrinsic); 7873 return; 7874 7875 case Intrinsic::icall_branch_funnel: { 7876 SmallVector<SDValue, 16> Ops; 7877 Ops.push_back(getValue(I.getArgOperand(0))); 7878 7879 int64_t Offset; 7880 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7881 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7882 if (!Base) 7883 report_fatal_error( 7884 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7885 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7886 7887 struct BranchFunnelTarget { 7888 int64_t Offset; 7889 SDValue Target; 7890 }; 7891 SmallVector<BranchFunnelTarget, 8> Targets; 7892 7893 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7894 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7895 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7896 if (ElemBase != Base) 7897 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7898 "to the same GlobalValue"); 7899 7900 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7901 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7902 if (!GA) 7903 report_fatal_error( 7904 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7905 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7906 GA->getGlobal(), sdl, Val.getValueType(), 7907 GA->getOffset())}); 7908 } 7909 llvm::sort(Targets, 7910 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7911 return T1.Offset < T2.Offset; 7912 }); 7913 7914 for (auto &T : Targets) { 7915 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7916 Ops.push_back(T.Target); 7917 } 7918 7919 Ops.push_back(DAG.getRoot()); // Chain 7920 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7921 MVT::Other, Ops), 7922 0); 7923 DAG.setRoot(N); 7924 setValue(&I, N); 7925 HasTailCall = true; 7926 return; 7927 } 7928 7929 case Intrinsic::wasm_landingpad_index: 7930 // Information this intrinsic contained has been transferred to 7931 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7932 // delete it now. 7933 return; 7934 7935 case Intrinsic::aarch64_settag: 7936 case Intrinsic::aarch64_settag_zero: { 7937 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7938 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7939 SDValue Val = TSI.EmitTargetCodeForSetTag( 7940 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7941 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7942 ZeroMemory); 7943 DAG.setRoot(Val); 7944 setValue(&I, Val); 7945 return; 7946 } 7947 case Intrinsic::amdgcn_cs_chain: { 7948 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7949 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7950 "Non-zero flags not supported yet"); 7951 7952 // At this point we don't care if it's amdgpu_cs_chain or 7953 // amdgpu_cs_chain_preserve. 7954 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7955 7956 Type *RetTy = I.getType(); 7957 assert(RetTy->isVoidTy() && "Should not return"); 7958 7959 SDValue Callee = getValue(I.getOperand(0)); 7960 7961 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7962 // We'll also tack the value of the EXEC mask at the end. 7963 TargetLowering::ArgListTy Args; 7964 Args.reserve(3); 7965 7966 for (unsigned Idx : {2, 3, 1}) { 7967 TargetLowering::ArgListEntry Arg; 7968 Arg.Node = getValue(I.getOperand(Idx)); 7969 Arg.Ty = I.getOperand(Idx)->getType(); 7970 Arg.setAttributes(&I, Idx); 7971 Args.push_back(Arg); 7972 } 7973 7974 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7975 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7976 Args[2].IsInReg = true; // EXEC should be inreg 7977 7978 TargetLowering::CallLoweringInfo CLI(DAG); 7979 CLI.setDebugLoc(getCurSDLoc()) 7980 .setChain(getRoot()) 7981 .setCallee(CC, RetTy, Callee, std::move(Args)) 7982 .setNoReturn(true) 7983 .setTailCall(true) 7984 .setConvergent(I.isConvergent()); 7985 CLI.CB = &I; 7986 std::pair<SDValue, SDValue> Result = 7987 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7988 (void)Result; 7989 assert(!Result.first.getNode() && !Result.second.getNode() && 7990 "Should've lowered as tail call"); 7991 7992 HasTailCall = true; 7993 return; 7994 } 7995 case Intrinsic::ptrmask: { 7996 SDValue Ptr = getValue(I.getOperand(0)); 7997 SDValue Mask = getValue(I.getOperand(1)); 7998 7999 // On arm64_32, pointers are 32 bits when stored in memory, but 8000 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to 8001 // match the index type, but the pointer is 64 bits, so the the mask must be 8002 // zero-extended up to 64 bits to match the pointer. 8003 EVT PtrVT = 8004 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 8005 EVT MemVT = 8006 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 8007 assert(PtrVT == Ptr.getValueType()); 8008 assert(MemVT == Mask.getValueType()); 8009 if (MemVT != PtrVT) 8010 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT); 8011 8012 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 8013 return; 8014 } 8015 case Intrinsic::threadlocal_address: { 8016 setValue(&I, getValue(I.getOperand(0))); 8017 return; 8018 } 8019 case Intrinsic::get_active_lane_mask: { 8020 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8021 SDValue Index = getValue(I.getOperand(0)); 8022 EVT ElementVT = Index.getValueType(); 8023 8024 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 8025 visitTargetIntrinsic(I, Intrinsic); 8026 return; 8027 } 8028 8029 SDValue TripCount = getValue(I.getOperand(1)); 8030 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 8031 CCVT.getVectorElementCount()); 8032 8033 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 8034 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 8035 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 8036 SDValue VectorInduction = DAG.getNode( 8037 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 8038 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 8039 VectorTripCount, ISD::CondCode::SETULT); 8040 setValue(&I, SetCC); 8041 return; 8042 } 8043 case Intrinsic::experimental_get_vector_length: { 8044 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 8045 "Expected positive VF"); 8046 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 8047 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 8048 8049 SDValue Count = getValue(I.getOperand(0)); 8050 EVT CountVT = Count.getValueType(); 8051 8052 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 8053 visitTargetIntrinsic(I, Intrinsic); 8054 return; 8055 } 8056 8057 // Expand to a umin between the trip count and the maximum elements the type 8058 // can hold. 8059 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8060 8061 // Extend the trip count to at least the result VT. 8062 if (CountVT.bitsLT(VT)) { 8063 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 8064 CountVT = VT; 8065 } 8066 8067 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 8068 ElementCount::get(VF, IsScalable)); 8069 8070 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 8071 // Clip to the result type if needed. 8072 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 8073 8074 setValue(&I, Trunc); 8075 return; 8076 } 8077 case Intrinsic::experimental_vector_partial_reduce_add: { 8078 8079 if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) { 8080 visitTargetIntrinsic(I, Intrinsic); 8081 return; 8082 } 8083 8084 setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()), 8085 getValue(I.getOperand(0)), 8086 getValue(I.getOperand(1)))); 8087 return; 8088 } 8089 case Intrinsic::experimental_cttz_elts: { 8090 auto DL = getCurSDLoc(); 8091 SDValue Op = getValue(I.getOperand(0)); 8092 EVT OpVT = Op.getValueType(); 8093 8094 if (!TLI.shouldExpandCttzElements(OpVT)) { 8095 visitTargetIntrinsic(I, Intrinsic); 8096 return; 8097 } 8098 8099 if (OpVT.getScalarType() != MVT::i1) { 8100 // Compare the input vector elements to zero & use to count trailing zeros 8101 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 8102 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 8103 OpVT.getVectorElementCount()); 8104 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 8105 } 8106 8107 // If the zero-is-poison flag is set, we can assume the upper limit 8108 // of the result is VF-1. 8109 bool ZeroIsPoison = 8110 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 8111 ConstantRange VScaleRange(1, true); // Dummy value. 8112 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 8113 VScaleRange = getVScaleRange(I.getCaller(), 64); 8114 unsigned EltWidth = TLI.getBitWidthForCttzElements( 8115 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 8116 8117 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 8118 8119 // Create the new vector type & get the vector length 8120 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 8121 OpVT.getVectorElementCount()); 8122 8123 SDValue VL = 8124 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 8125 8126 SDValue StepVec = DAG.getStepVector(DL, NewVT); 8127 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 8128 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 8129 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 8130 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 8131 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 8132 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 8133 8134 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8135 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 8136 8137 setValue(&I, Ret); 8138 return; 8139 } 8140 case Intrinsic::vector_insert: { 8141 SDValue Vec = getValue(I.getOperand(0)); 8142 SDValue SubVec = getValue(I.getOperand(1)); 8143 SDValue Index = getValue(I.getOperand(2)); 8144 8145 // The intrinsic's index type is i64, but the SDNode requires an index type 8146 // suitable for the target. Convert the index as required. 8147 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8148 if (Index.getValueType() != VectorIdxTy) 8149 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8150 8151 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8152 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 8153 Index)); 8154 return; 8155 } 8156 case Intrinsic::vector_extract: { 8157 SDValue Vec = getValue(I.getOperand(0)); 8158 SDValue Index = getValue(I.getOperand(1)); 8159 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8160 8161 // The intrinsic's index type is i64, but the SDNode requires an index type 8162 // suitable for the target. Convert the index as required. 8163 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8164 if (Index.getValueType() != VectorIdxTy) 8165 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 8166 8167 setValue(&I, 8168 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 8169 return; 8170 } 8171 case Intrinsic::vector_reverse: 8172 visitVectorReverse(I); 8173 return; 8174 case Intrinsic::vector_splice: 8175 visitVectorSplice(I); 8176 return; 8177 case Intrinsic::callbr_landingpad: 8178 visitCallBrLandingPad(I); 8179 return; 8180 case Intrinsic::vector_interleave2: 8181 visitVectorInterleave(I); 8182 return; 8183 case Intrinsic::vector_deinterleave2: 8184 visitVectorDeinterleave(I); 8185 return; 8186 case Intrinsic::experimental_vector_compress: 8187 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl, 8188 getValue(I.getArgOperand(0)).getValueType(), 8189 getValue(I.getArgOperand(0)), 8190 getValue(I.getArgOperand(1)), 8191 getValue(I.getArgOperand(2)), Flags)); 8192 return; 8193 case Intrinsic::experimental_convergence_anchor: 8194 case Intrinsic::experimental_convergence_entry: 8195 case Intrinsic::experimental_convergence_loop: 8196 visitConvergenceControl(I, Intrinsic); 8197 return; 8198 case Intrinsic::experimental_vector_histogram_add: { 8199 visitVectorHistogram(I, Intrinsic); 8200 return; 8201 } 8202 } 8203 } 8204 8205 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8206 const ConstrainedFPIntrinsic &FPI) { 8207 SDLoc sdl = getCurSDLoc(); 8208 8209 // We do not need to serialize constrained FP intrinsics against 8210 // each other or against (nonvolatile) loads, so they can be 8211 // chained like loads. 8212 SDValue Chain = DAG.getRoot(); 8213 SmallVector<SDValue, 4> Opers; 8214 Opers.push_back(Chain); 8215 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8216 Opers.push_back(getValue(FPI.getArgOperand(I))); 8217 8218 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8219 assert(Result.getNode()->getNumValues() == 2); 8220 8221 // Push node to the appropriate list so that future instructions can be 8222 // chained up correctly. 8223 SDValue OutChain = Result.getValue(1); 8224 switch (EB) { 8225 case fp::ExceptionBehavior::ebIgnore: 8226 // The only reason why ebIgnore nodes still need to be chained is that 8227 // they might depend on the current rounding mode, and therefore must 8228 // not be moved across instruction that may change that mode. 8229 [[fallthrough]]; 8230 case fp::ExceptionBehavior::ebMayTrap: 8231 // These must not be moved across calls or instructions that may change 8232 // floating-point exception masks. 8233 PendingConstrainedFP.push_back(OutChain); 8234 break; 8235 case fp::ExceptionBehavior::ebStrict: 8236 // These must not be moved across calls or instructions that may change 8237 // floating-point exception masks or read floating-point exception flags. 8238 // In addition, they cannot be optimized out even if unused. 8239 PendingConstrainedFPStrict.push_back(OutChain); 8240 break; 8241 } 8242 }; 8243 8244 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8245 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8246 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8247 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8248 8249 SDNodeFlags Flags; 8250 if (EB == fp::ExceptionBehavior::ebIgnore) 8251 Flags.setNoFPExcept(true); 8252 8253 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8254 Flags.copyFMF(*FPOp); 8255 8256 unsigned Opcode; 8257 switch (FPI.getIntrinsicID()) { 8258 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8259 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8260 case Intrinsic::INTRINSIC: \ 8261 Opcode = ISD::STRICT_##DAGN; \ 8262 break; 8263 #include "llvm/IR/ConstrainedOps.def" 8264 case Intrinsic::experimental_constrained_fmuladd: { 8265 Opcode = ISD::STRICT_FMA; 8266 // Break fmuladd into fmul and fadd. 8267 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8268 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8269 Opers.pop_back(); 8270 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8271 pushOutChain(Mul, EB); 8272 Opcode = ISD::STRICT_FADD; 8273 Opers.clear(); 8274 Opers.push_back(Mul.getValue(1)); 8275 Opers.push_back(Mul.getValue(0)); 8276 Opers.push_back(getValue(FPI.getArgOperand(2))); 8277 } 8278 break; 8279 } 8280 } 8281 8282 // A few strict DAG nodes carry additional operands that are not 8283 // set up by the default code above. 8284 switch (Opcode) { 8285 default: break; 8286 case ISD::STRICT_FP_ROUND: 8287 Opers.push_back( 8288 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8289 break; 8290 case ISD::STRICT_FSETCC: 8291 case ISD::STRICT_FSETCCS: { 8292 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8293 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8294 if (TM.Options.NoNaNsFPMath) 8295 Condition = getFCmpCodeWithoutNaN(Condition); 8296 Opers.push_back(DAG.getCondCode(Condition)); 8297 break; 8298 } 8299 } 8300 8301 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8302 pushOutChain(Result, EB); 8303 8304 SDValue FPResult = Result.getValue(0); 8305 setValue(&FPI, FPResult); 8306 } 8307 8308 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8309 std::optional<unsigned> ResOPC; 8310 switch (VPIntrin.getIntrinsicID()) { 8311 case Intrinsic::vp_ctlz: { 8312 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8313 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8314 break; 8315 } 8316 case Intrinsic::vp_cttz: { 8317 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8318 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8319 break; 8320 } 8321 case Intrinsic::vp_cttz_elts: { 8322 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8323 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8324 break; 8325 } 8326 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8327 case Intrinsic::VPID: \ 8328 ResOPC = ISD::VPSD; \ 8329 break; 8330 #include "llvm/IR/VPIntrinsics.def" 8331 } 8332 8333 if (!ResOPC) 8334 llvm_unreachable( 8335 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8336 8337 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8338 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8339 if (VPIntrin.getFastMathFlags().allowReassoc()) 8340 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8341 : ISD::VP_REDUCE_FMUL; 8342 } 8343 8344 return *ResOPC; 8345 } 8346 8347 void SelectionDAGBuilder::visitVPLoad( 8348 const VPIntrinsic &VPIntrin, EVT VT, 8349 const SmallVectorImpl<SDValue> &OpValues) { 8350 SDLoc DL = getCurSDLoc(); 8351 Value *PtrOperand = VPIntrin.getArgOperand(0); 8352 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8353 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8354 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8355 SDValue LD; 8356 // Do not serialize variable-length loads of constant memory with 8357 // anything. 8358 if (!Alignment) 8359 Alignment = DAG.getEVTAlign(VT); 8360 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8361 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8362 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8363 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8364 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8365 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8366 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8367 MMO, false /*IsExpanding */); 8368 if (AddToChain) 8369 PendingLoads.push_back(LD.getValue(1)); 8370 setValue(&VPIntrin, LD); 8371 } 8372 8373 void SelectionDAGBuilder::visitVPGather( 8374 const VPIntrinsic &VPIntrin, EVT VT, 8375 const SmallVectorImpl<SDValue> &OpValues) { 8376 SDLoc DL = getCurSDLoc(); 8377 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8378 Value *PtrOperand = VPIntrin.getArgOperand(0); 8379 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8380 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8381 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8382 SDValue LD; 8383 if (!Alignment) 8384 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8385 unsigned AS = 8386 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8387 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8388 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8389 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8390 SDValue Base, Index, Scale; 8391 ISD::MemIndexType IndexType; 8392 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8393 this, VPIntrin.getParent(), 8394 VT.getScalarStoreSize()); 8395 if (!UniformBase) { 8396 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8397 Index = getValue(PtrOperand); 8398 IndexType = ISD::SIGNED_SCALED; 8399 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8400 } 8401 EVT IdxVT = Index.getValueType(); 8402 EVT EltTy = IdxVT.getVectorElementType(); 8403 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8404 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8405 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8406 } 8407 LD = DAG.getGatherVP( 8408 DAG.getVTList(VT, MVT::Other), VT, DL, 8409 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8410 IndexType); 8411 PendingLoads.push_back(LD.getValue(1)); 8412 setValue(&VPIntrin, LD); 8413 } 8414 8415 void SelectionDAGBuilder::visitVPStore( 8416 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8417 SDLoc DL = getCurSDLoc(); 8418 Value *PtrOperand = VPIntrin.getArgOperand(1); 8419 EVT VT = OpValues[0].getValueType(); 8420 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8421 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8422 SDValue ST; 8423 if (!Alignment) 8424 Alignment = DAG.getEVTAlign(VT); 8425 SDValue Ptr = OpValues[1]; 8426 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8427 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8428 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8429 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8430 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8431 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8432 /* IsTruncating */ false, /*IsCompressing*/ false); 8433 DAG.setRoot(ST); 8434 setValue(&VPIntrin, ST); 8435 } 8436 8437 void SelectionDAGBuilder::visitVPScatter( 8438 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8439 SDLoc DL = getCurSDLoc(); 8440 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8441 Value *PtrOperand = VPIntrin.getArgOperand(1); 8442 EVT VT = OpValues[0].getValueType(); 8443 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8444 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8445 SDValue ST; 8446 if (!Alignment) 8447 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8448 unsigned AS = 8449 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8450 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8451 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8452 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8453 SDValue Base, Index, Scale; 8454 ISD::MemIndexType IndexType; 8455 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8456 this, VPIntrin.getParent(), 8457 VT.getScalarStoreSize()); 8458 if (!UniformBase) { 8459 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8460 Index = getValue(PtrOperand); 8461 IndexType = ISD::SIGNED_SCALED; 8462 Scale = 8463 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8464 } 8465 EVT IdxVT = Index.getValueType(); 8466 EVT EltTy = IdxVT.getVectorElementType(); 8467 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8468 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8469 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8470 } 8471 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8472 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8473 OpValues[2], OpValues[3]}, 8474 MMO, IndexType); 8475 DAG.setRoot(ST); 8476 setValue(&VPIntrin, ST); 8477 } 8478 8479 void SelectionDAGBuilder::visitVPStridedLoad( 8480 const VPIntrinsic &VPIntrin, EVT VT, 8481 const SmallVectorImpl<SDValue> &OpValues) { 8482 SDLoc DL = getCurSDLoc(); 8483 Value *PtrOperand = VPIntrin.getArgOperand(0); 8484 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8485 if (!Alignment) 8486 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8487 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8488 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8489 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8490 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8491 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8492 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8493 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8494 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8495 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8496 8497 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8498 OpValues[2], OpValues[3], MMO, 8499 false /*IsExpanding*/); 8500 8501 if (AddToChain) 8502 PendingLoads.push_back(LD.getValue(1)); 8503 setValue(&VPIntrin, LD); 8504 } 8505 8506 void SelectionDAGBuilder::visitVPStridedStore( 8507 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8508 SDLoc DL = getCurSDLoc(); 8509 Value *PtrOperand = VPIntrin.getArgOperand(1); 8510 EVT VT = OpValues[0].getValueType(); 8511 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8512 if (!Alignment) 8513 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8514 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8515 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8516 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8517 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8518 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8519 8520 SDValue ST = DAG.getStridedStoreVP( 8521 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8522 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8523 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8524 /*IsCompressing*/ false); 8525 8526 DAG.setRoot(ST); 8527 setValue(&VPIntrin, ST); 8528 } 8529 8530 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8532 SDLoc DL = getCurSDLoc(); 8533 8534 ISD::CondCode Condition; 8535 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8536 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8537 if (IsFP) { 8538 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8539 // flags, but calls that don't return floating-point types can't be 8540 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8541 Condition = getFCmpCondCode(CondCode); 8542 if (TM.Options.NoNaNsFPMath) 8543 Condition = getFCmpCodeWithoutNaN(Condition); 8544 } else { 8545 Condition = getICmpCondCode(CondCode); 8546 } 8547 8548 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8549 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8550 // #2 is the condition code 8551 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8552 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8553 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8554 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8555 "Unexpected target EVL type"); 8556 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8557 8558 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8559 VPIntrin.getType()); 8560 setValue(&VPIntrin, 8561 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8562 } 8563 8564 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8565 const VPIntrinsic &VPIntrin) { 8566 SDLoc DL = getCurSDLoc(); 8567 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8568 8569 auto IID = VPIntrin.getIntrinsicID(); 8570 8571 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8572 return visitVPCmp(*CmpI); 8573 8574 SmallVector<EVT, 4> ValueVTs; 8575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8576 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8577 SDVTList VTs = DAG.getVTList(ValueVTs); 8578 8579 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8580 8581 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8582 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8583 "Unexpected target EVL type"); 8584 8585 // Request operands. 8586 SmallVector<SDValue, 7> OpValues; 8587 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8588 auto Op = getValue(VPIntrin.getArgOperand(I)); 8589 if (I == EVLParamPos) 8590 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8591 OpValues.push_back(Op); 8592 } 8593 8594 switch (Opcode) { 8595 default: { 8596 SDNodeFlags SDFlags; 8597 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8598 SDFlags.copyFMF(*FPMO); 8599 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8600 setValue(&VPIntrin, Result); 8601 break; 8602 } 8603 case ISD::VP_LOAD: 8604 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8605 break; 8606 case ISD::VP_GATHER: 8607 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8608 break; 8609 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8610 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8611 break; 8612 case ISD::VP_STORE: 8613 visitVPStore(VPIntrin, OpValues); 8614 break; 8615 case ISD::VP_SCATTER: 8616 visitVPScatter(VPIntrin, OpValues); 8617 break; 8618 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8619 visitVPStridedStore(VPIntrin, OpValues); 8620 break; 8621 case ISD::VP_FMULADD: { 8622 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8623 SDNodeFlags SDFlags; 8624 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8625 SDFlags.copyFMF(*FPMO); 8626 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8627 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8628 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8629 } else { 8630 SDValue Mul = DAG.getNode( 8631 ISD::VP_FMUL, DL, VTs, 8632 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8633 SDValue Add = 8634 DAG.getNode(ISD::VP_FADD, DL, VTs, 8635 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8636 setValue(&VPIntrin, Add); 8637 } 8638 break; 8639 } 8640 case ISD::VP_IS_FPCLASS: { 8641 const DataLayout DLayout = DAG.getDataLayout(); 8642 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8643 auto Constant = OpValues[1]->getAsZExtVal(); 8644 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8645 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8646 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8647 setValue(&VPIntrin, V); 8648 return; 8649 } 8650 case ISD::VP_INTTOPTR: { 8651 SDValue N = OpValues[0]; 8652 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8653 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8654 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8655 OpValues[2]); 8656 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8657 OpValues[2]); 8658 setValue(&VPIntrin, N); 8659 break; 8660 } 8661 case ISD::VP_PTRTOINT: { 8662 SDValue N = OpValues[0]; 8663 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8664 VPIntrin.getType()); 8665 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8666 VPIntrin.getOperand(0)->getType()); 8667 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8668 OpValues[2]); 8669 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8670 OpValues[2]); 8671 setValue(&VPIntrin, N); 8672 break; 8673 } 8674 case ISD::VP_ABS: 8675 case ISD::VP_CTLZ: 8676 case ISD::VP_CTLZ_ZERO_UNDEF: 8677 case ISD::VP_CTTZ: 8678 case ISD::VP_CTTZ_ZERO_UNDEF: 8679 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8680 case ISD::VP_CTTZ_ELTS: { 8681 SDValue Result = 8682 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8683 setValue(&VPIntrin, Result); 8684 break; 8685 } 8686 } 8687 } 8688 8689 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8690 const BasicBlock *EHPadBB, 8691 MCSymbol *&BeginLabel) { 8692 MachineFunction &MF = DAG.getMachineFunction(); 8693 8694 // Insert a label before the invoke call to mark the try range. This can be 8695 // used to detect deletion of the invoke via the MachineModuleInfo. 8696 BeginLabel = MF.getContext().createTempSymbol(); 8697 8698 // For SjLj, keep track of which landing pads go with which invokes 8699 // so as to maintain the ordering of pads in the LSDA. 8700 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite(); 8701 if (CallSiteIndex) { 8702 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8703 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex); 8704 8705 // Now that the call site is handled, stop tracking it. 8706 FuncInfo.setCurrentCallSite(0); 8707 } 8708 8709 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8710 } 8711 8712 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8713 const BasicBlock *EHPadBB, 8714 MCSymbol *BeginLabel) { 8715 assert(BeginLabel && "BeginLabel should've been set"); 8716 8717 MachineFunction &MF = DAG.getMachineFunction(); 8718 8719 // Insert a label at the end of the invoke call to mark the try range. This 8720 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8721 MCSymbol *EndLabel = MF.getContext().createTempSymbol(); 8722 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8723 8724 // Inform MachineModuleInfo of range. 8725 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8726 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8727 // actually use outlined funclets and their LSDA info style. 8728 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8729 assert(II && "II should've been set"); 8730 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8731 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8732 } else if (!isScopedEHPersonality(Pers)) { 8733 assert(EHPadBB); 8734 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel); 8735 } 8736 8737 return Chain; 8738 } 8739 8740 std::pair<SDValue, SDValue> 8741 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8742 const BasicBlock *EHPadBB) { 8743 MCSymbol *BeginLabel = nullptr; 8744 8745 if (EHPadBB) { 8746 // Both PendingLoads and PendingExports must be flushed here; 8747 // this call might not return. 8748 (void)getRoot(); 8749 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8750 CLI.setChain(getRoot()); 8751 } 8752 8753 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8754 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8755 8756 assert((CLI.IsTailCall || Result.second.getNode()) && 8757 "Non-null chain expected with non-tail call!"); 8758 assert((Result.second.getNode() || !Result.first.getNode()) && 8759 "Null value expected with tail call!"); 8760 8761 if (!Result.second.getNode()) { 8762 // As a special case, a null chain means that a tail call has been emitted 8763 // and the DAG root is already updated. 8764 HasTailCall = true; 8765 8766 // Since there's no actual continuation from this block, nothing can be 8767 // relying on us setting vregs for them. 8768 PendingExports.clear(); 8769 } else { 8770 DAG.setRoot(Result.second); 8771 } 8772 8773 if (EHPadBB) { 8774 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8775 BeginLabel)); 8776 Result.second = getRoot(); 8777 } 8778 8779 return Result; 8780 } 8781 8782 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8783 bool isTailCall, bool isMustTailCall, 8784 const BasicBlock *EHPadBB, 8785 const TargetLowering::PtrAuthInfo *PAI) { 8786 auto &DL = DAG.getDataLayout(); 8787 FunctionType *FTy = CB.getFunctionType(); 8788 Type *RetTy = CB.getType(); 8789 8790 TargetLowering::ArgListTy Args; 8791 Args.reserve(CB.arg_size()); 8792 8793 const Value *SwiftErrorVal = nullptr; 8794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8795 8796 if (isTailCall) { 8797 // Avoid emitting tail calls in functions with the disable-tail-calls 8798 // attribute. 8799 auto *Caller = CB.getParent()->getParent(); 8800 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8801 "true" && !isMustTailCall) 8802 isTailCall = false; 8803 8804 // We can't tail call inside a function with a swifterror argument. Lowering 8805 // does not support this yet. It would have to move into the swifterror 8806 // register before the call. 8807 if (TLI.supportSwiftError() && 8808 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8809 isTailCall = false; 8810 } 8811 8812 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8813 TargetLowering::ArgListEntry Entry; 8814 const Value *V = *I; 8815 8816 // Skip empty types 8817 if (V->getType()->isEmptyTy()) 8818 continue; 8819 8820 SDValue ArgNode = getValue(V); 8821 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8822 8823 Entry.setAttributes(&CB, I - CB.arg_begin()); 8824 8825 // Use swifterror virtual register as input to the call. 8826 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8827 SwiftErrorVal = V; 8828 // We find the virtual register for the actual swifterror argument. 8829 // Instead of using the Value, we use the virtual register instead. 8830 Entry.Node = 8831 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8832 EVT(TLI.getPointerTy(DL))); 8833 } 8834 8835 Args.push_back(Entry); 8836 8837 // If we have an explicit sret argument that is an Instruction, (i.e., it 8838 // might point to function-local memory), we can't meaningfully tail-call. 8839 if (Entry.IsSRet && isa<Instruction>(V)) 8840 isTailCall = false; 8841 } 8842 8843 // If call site has a cfguardtarget operand bundle, create and add an 8844 // additional ArgListEntry. 8845 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8846 TargetLowering::ArgListEntry Entry; 8847 Value *V = Bundle->Inputs[0]; 8848 SDValue ArgNode = getValue(V); 8849 Entry.Node = ArgNode; 8850 Entry.Ty = V->getType(); 8851 Entry.IsCFGuardTarget = true; 8852 Args.push_back(Entry); 8853 } 8854 8855 // Check if target-independent constraints permit a tail call here. 8856 // Target-dependent constraints are checked within TLI->LowerCallTo. 8857 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8858 isTailCall = false; 8859 8860 // Disable tail calls if there is an swifterror argument. Targets have not 8861 // been updated to support tail calls. 8862 if (TLI.supportSwiftError() && SwiftErrorVal) 8863 isTailCall = false; 8864 8865 ConstantInt *CFIType = nullptr; 8866 if (CB.isIndirectCall()) { 8867 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8868 if (!TLI.supportKCFIBundles()) 8869 report_fatal_error( 8870 "Target doesn't support calls with kcfi operand bundles."); 8871 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8872 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8873 } 8874 } 8875 8876 SDValue ConvControlToken; 8877 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8878 auto *Token = Bundle->Inputs[0].get(); 8879 ConvControlToken = getValue(Token); 8880 } 8881 8882 TargetLowering::CallLoweringInfo CLI(DAG); 8883 CLI.setDebugLoc(getCurSDLoc()) 8884 .setChain(getRoot()) 8885 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8886 .setTailCall(isTailCall) 8887 .setConvergent(CB.isConvergent()) 8888 .setIsPreallocated( 8889 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8890 .setCFIType(CFIType) 8891 .setConvergenceControlToken(ConvControlToken); 8892 8893 // Set the pointer authentication info if we have it. 8894 if (PAI) { 8895 if (!TLI.supportPtrAuthBundles()) 8896 report_fatal_error( 8897 "This target doesn't support calls with ptrauth operand bundles."); 8898 CLI.setPtrAuth(*PAI); 8899 } 8900 8901 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8902 8903 if (Result.first.getNode()) { 8904 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8905 setValue(&CB, Result.first); 8906 } 8907 8908 // The last element of CLI.InVals has the SDValue for swifterror return. 8909 // Here we copy it to a virtual register and update SwiftErrorMap for 8910 // book-keeping. 8911 if (SwiftErrorVal && TLI.supportSwiftError()) { 8912 // Get the last element of InVals. 8913 SDValue Src = CLI.InVals.back(); 8914 Register VReg = 8915 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8916 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8917 DAG.setRoot(CopyNode); 8918 } 8919 } 8920 8921 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8922 SelectionDAGBuilder &Builder) { 8923 // Check to see if this load can be trivially constant folded, e.g. if the 8924 // input is from a string literal. 8925 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8926 // Cast pointer to the type we really want to load. 8927 Type *LoadTy = 8928 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8929 if (LoadVT.isVector()) 8930 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8931 8932 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8933 PointerType::getUnqual(LoadTy)); 8934 8935 if (const Constant *LoadCst = 8936 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8937 LoadTy, Builder.DAG.getDataLayout())) 8938 return Builder.getValue(LoadCst); 8939 } 8940 8941 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8942 // still constant memory, the input chain can be the entry node. 8943 SDValue Root; 8944 bool ConstantMemory = false; 8945 8946 // Do not serialize (non-volatile) loads of constant memory with anything. 8947 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8948 Root = Builder.DAG.getEntryNode(); 8949 ConstantMemory = true; 8950 } else { 8951 // Do not serialize non-volatile loads against each other. 8952 Root = Builder.DAG.getRoot(); 8953 } 8954 8955 SDValue Ptr = Builder.getValue(PtrVal); 8956 SDValue LoadVal = 8957 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8958 MachinePointerInfo(PtrVal), Align(1)); 8959 8960 if (!ConstantMemory) 8961 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8962 return LoadVal; 8963 } 8964 8965 /// Record the value for an instruction that produces an integer result, 8966 /// converting the type where necessary. 8967 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8968 SDValue Value, 8969 bool IsSigned) { 8970 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8971 I.getType(), true); 8972 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8973 setValue(&I, Value); 8974 } 8975 8976 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8977 /// true and lower it. Otherwise return false, and it will be lowered like a 8978 /// normal call. 8979 /// The caller already checked that \p I calls the appropriate LibFunc with a 8980 /// correct prototype. 8981 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8982 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8983 const Value *Size = I.getArgOperand(2); 8984 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8985 if (CSize && CSize->getZExtValue() == 0) { 8986 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8987 I.getType(), true); 8988 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8989 return true; 8990 } 8991 8992 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8993 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8994 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8995 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8996 if (Res.first.getNode()) { 8997 processIntegerCallValue(I, Res.first, true); 8998 PendingLoads.push_back(Res.second); 8999 return true; 9000 } 9001 9002 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 9003 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 9004 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 9005 return false; 9006 9007 // If the target has a fast compare for the given size, it will return a 9008 // preferred load type for that size. Require that the load VT is legal and 9009 // that the target supports unaligned loads of that type. Otherwise, return 9010 // INVALID. 9011 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 9012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9013 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 9014 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 9015 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 9016 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 9017 // TODO: Check alignment of src and dest ptrs. 9018 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 9019 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 9020 if (!TLI.isTypeLegal(LVT) || 9021 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 9022 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 9023 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 9024 } 9025 9026 return LVT; 9027 }; 9028 9029 // This turns into unaligned loads. We only do this if the target natively 9030 // supports the MVT we'll be loading or if it is small enough (<= 4) that 9031 // we'll only produce a small number of byte loads. 9032 MVT LoadVT; 9033 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 9034 switch (NumBitsToCompare) { 9035 default: 9036 return false; 9037 case 16: 9038 LoadVT = MVT::i16; 9039 break; 9040 case 32: 9041 LoadVT = MVT::i32; 9042 break; 9043 case 64: 9044 case 128: 9045 case 256: 9046 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 9047 break; 9048 } 9049 9050 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 9051 return false; 9052 9053 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 9054 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 9055 9056 // Bitcast to a wide integer type if the loads are vectors. 9057 if (LoadVT.isVector()) { 9058 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 9059 LoadL = DAG.getBitcast(CmpVT, LoadL); 9060 LoadR = DAG.getBitcast(CmpVT, LoadR); 9061 } 9062 9063 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 9064 processIntegerCallValue(I, Cmp, false); 9065 return true; 9066 } 9067 9068 /// See if we can lower a memchr call into an optimized form. If so, return 9069 /// true and lower it. Otherwise return false, and it will be lowered like a 9070 /// normal call. 9071 /// The caller already checked that \p I calls the appropriate LibFunc with a 9072 /// correct prototype. 9073 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 9074 const Value *Src = I.getArgOperand(0); 9075 const Value *Char = I.getArgOperand(1); 9076 const Value *Length = I.getArgOperand(2); 9077 9078 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9079 std::pair<SDValue, SDValue> Res = 9080 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 9081 getValue(Src), getValue(Char), getValue(Length), 9082 MachinePointerInfo(Src)); 9083 if (Res.first.getNode()) { 9084 setValue(&I, Res.first); 9085 PendingLoads.push_back(Res.second); 9086 return true; 9087 } 9088 9089 return false; 9090 } 9091 9092 /// See if we can lower a mempcpy call into an optimized form. If so, return 9093 /// true and lower it. Otherwise return false, and it will be lowered like a 9094 /// normal call. 9095 /// The caller already checked that \p I calls the appropriate LibFunc with a 9096 /// correct prototype. 9097 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 9098 SDValue Dst = getValue(I.getArgOperand(0)); 9099 SDValue Src = getValue(I.getArgOperand(1)); 9100 SDValue Size = getValue(I.getArgOperand(2)); 9101 9102 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 9103 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 9104 // DAG::getMemcpy needs Alignment to be defined. 9105 Align Alignment = std::min(DstAlign, SrcAlign); 9106 9107 SDLoc sdl = getCurSDLoc(); 9108 9109 // In the mempcpy context we need to pass in a false value for isTailCall 9110 // because the return pointer needs to be adjusted by the size of 9111 // the copied memory. 9112 SDValue Root = getMemoryRoot(); 9113 SDValue MC = DAG.getMemcpy( 9114 Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr, 9115 std::nullopt, MachinePointerInfo(I.getArgOperand(0)), 9116 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata()); 9117 assert(MC.getNode() != nullptr && 9118 "** memcpy should not be lowered as TailCall in mempcpy context **"); 9119 DAG.setRoot(MC); 9120 9121 // Check if Size needs to be truncated or extended. 9122 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 9123 9124 // Adjust return pointer to point just past the last dst byte. 9125 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 9126 Dst, Size); 9127 setValue(&I, DstPlusSize); 9128 return true; 9129 } 9130 9131 /// See if we can lower a strcpy call into an optimized form. If so, return 9132 /// true and lower it, otherwise return false and it will be lowered like a 9133 /// normal call. 9134 /// The caller already checked that \p I calls the appropriate LibFunc with a 9135 /// correct prototype. 9136 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 9137 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9138 9139 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9140 std::pair<SDValue, SDValue> Res = 9141 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 9142 getValue(Arg0), getValue(Arg1), 9143 MachinePointerInfo(Arg0), 9144 MachinePointerInfo(Arg1), isStpcpy); 9145 if (Res.first.getNode()) { 9146 setValue(&I, Res.first); 9147 DAG.setRoot(Res.second); 9148 return true; 9149 } 9150 9151 return false; 9152 } 9153 9154 /// See if we can lower a strcmp call into an optimized form. If so, return 9155 /// true and lower it, otherwise return false and it will be lowered like a 9156 /// normal call. 9157 /// The caller already checked that \p I calls the appropriate LibFunc with a 9158 /// correct prototype. 9159 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 9160 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9161 9162 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9163 std::pair<SDValue, SDValue> Res = 9164 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 9165 getValue(Arg0), getValue(Arg1), 9166 MachinePointerInfo(Arg0), 9167 MachinePointerInfo(Arg1)); 9168 if (Res.first.getNode()) { 9169 processIntegerCallValue(I, Res.first, true); 9170 PendingLoads.push_back(Res.second); 9171 return true; 9172 } 9173 9174 return false; 9175 } 9176 9177 /// See if we can lower a strlen call into an optimized form. If so, return 9178 /// true and lower it, otherwise return false and it will be lowered like a 9179 /// normal call. 9180 /// The caller already checked that \p I calls the appropriate LibFunc with a 9181 /// correct prototype. 9182 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 9183 const Value *Arg0 = I.getArgOperand(0); 9184 9185 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9186 std::pair<SDValue, SDValue> Res = 9187 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 9188 getValue(Arg0), MachinePointerInfo(Arg0)); 9189 if (Res.first.getNode()) { 9190 processIntegerCallValue(I, Res.first, false); 9191 PendingLoads.push_back(Res.second); 9192 return true; 9193 } 9194 9195 return false; 9196 } 9197 9198 /// See if we can lower a strnlen call into an optimized form. If so, return 9199 /// true and lower it, otherwise return false and it will be lowered like a 9200 /// normal call. 9201 /// The caller already checked that \p I calls the appropriate LibFunc with a 9202 /// correct prototype. 9203 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9204 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9205 9206 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9207 std::pair<SDValue, SDValue> Res = 9208 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9209 getValue(Arg0), getValue(Arg1), 9210 MachinePointerInfo(Arg0)); 9211 if (Res.first.getNode()) { 9212 processIntegerCallValue(I, Res.first, false); 9213 PendingLoads.push_back(Res.second); 9214 return true; 9215 } 9216 9217 return false; 9218 } 9219 9220 /// See if we can lower a unary floating-point operation into an SDNode with 9221 /// the specified Opcode. If so, return true and lower it, otherwise return 9222 /// false and it will be lowered like a normal call. 9223 /// The caller already checked that \p I calls the appropriate LibFunc with a 9224 /// correct prototype. 9225 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9226 unsigned Opcode) { 9227 // We already checked this call's prototype; verify it doesn't modify errno. 9228 if (!I.onlyReadsMemory()) 9229 return false; 9230 9231 SDNodeFlags Flags; 9232 Flags.copyFMF(cast<FPMathOperator>(I)); 9233 9234 SDValue Tmp = getValue(I.getArgOperand(0)); 9235 setValue(&I, 9236 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9237 return true; 9238 } 9239 9240 /// See if we can lower a binary floating-point operation into an SDNode with 9241 /// the specified Opcode. If so, return true and lower it. Otherwise return 9242 /// false, and it will be lowered like a normal call. 9243 /// The caller already checked that \p I calls the appropriate LibFunc with a 9244 /// correct prototype. 9245 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9246 unsigned Opcode) { 9247 // We already checked this call's prototype; verify it doesn't modify errno. 9248 if (!I.onlyReadsMemory()) 9249 return false; 9250 9251 SDNodeFlags Flags; 9252 Flags.copyFMF(cast<FPMathOperator>(I)); 9253 9254 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9255 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9256 EVT VT = Tmp0.getValueType(); 9257 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9258 return true; 9259 } 9260 9261 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9262 // Handle inline assembly differently. 9263 if (I.isInlineAsm()) { 9264 visitInlineAsm(I); 9265 return; 9266 } 9267 9268 diagnoseDontCall(I); 9269 9270 if (Function *F = I.getCalledFunction()) { 9271 if (F->isDeclaration()) { 9272 // Is this an LLVM intrinsic or a target-specific intrinsic? 9273 unsigned IID = F->getIntrinsicID(); 9274 if (!IID) 9275 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9276 IID = II->getIntrinsicID(F); 9277 9278 if (IID) { 9279 visitIntrinsicCall(I, IID); 9280 return; 9281 } 9282 } 9283 9284 // Check for well-known libc/libm calls. If the function is internal, it 9285 // can't be a library call. Don't do the check if marked as nobuiltin for 9286 // some reason or the call site requires strict floating point semantics. 9287 LibFunc Func; 9288 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9289 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9290 LibInfo->hasOptimizedCodeGen(Func)) { 9291 switch (Func) { 9292 default: break; 9293 case LibFunc_bcmp: 9294 if (visitMemCmpBCmpCall(I)) 9295 return; 9296 break; 9297 case LibFunc_copysign: 9298 case LibFunc_copysignf: 9299 case LibFunc_copysignl: 9300 // We already checked this call's prototype; verify it doesn't modify 9301 // errno. 9302 if (I.onlyReadsMemory()) { 9303 SDValue LHS = getValue(I.getArgOperand(0)); 9304 SDValue RHS = getValue(I.getArgOperand(1)); 9305 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9306 LHS.getValueType(), LHS, RHS)); 9307 return; 9308 } 9309 break; 9310 case LibFunc_fabs: 9311 case LibFunc_fabsf: 9312 case LibFunc_fabsl: 9313 if (visitUnaryFloatCall(I, ISD::FABS)) 9314 return; 9315 break; 9316 case LibFunc_fmin: 9317 case LibFunc_fminf: 9318 case LibFunc_fminl: 9319 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9320 return; 9321 break; 9322 case LibFunc_fmax: 9323 case LibFunc_fmaxf: 9324 case LibFunc_fmaxl: 9325 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9326 return; 9327 break; 9328 case LibFunc_fminimum_num: 9329 case LibFunc_fminimum_numf: 9330 case LibFunc_fminimum_numl: 9331 if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM)) 9332 return; 9333 break; 9334 case LibFunc_fmaximum_num: 9335 case LibFunc_fmaximum_numf: 9336 case LibFunc_fmaximum_numl: 9337 if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM)) 9338 return; 9339 break; 9340 case LibFunc_sin: 9341 case LibFunc_sinf: 9342 case LibFunc_sinl: 9343 if (visitUnaryFloatCall(I, ISD::FSIN)) 9344 return; 9345 break; 9346 case LibFunc_cos: 9347 case LibFunc_cosf: 9348 case LibFunc_cosl: 9349 if (visitUnaryFloatCall(I, ISD::FCOS)) 9350 return; 9351 break; 9352 case LibFunc_tan: 9353 case LibFunc_tanf: 9354 case LibFunc_tanl: 9355 if (visitUnaryFloatCall(I, ISD::FTAN)) 9356 return; 9357 break; 9358 case LibFunc_asin: 9359 case LibFunc_asinf: 9360 case LibFunc_asinl: 9361 if (visitUnaryFloatCall(I, ISD::FASIN)) 9362 return; 9363 break; 9364 case LibFunc_acos: 9365 case LibFunc_acosf: 9366 case LibFunc_acosl: 9367 if (visitUnaryFloatCall(I, ISD::FACOS)) 9368 return; 9369 break; 9370 case LibFunc_atan: 9371 case LibFunc_atanf: 9372 case LibFunc_atanl: 9373 if (visitUnaryFloatCall(I, ISD::FATAN)) 9374 return; 9375 break; 9376 case LibFunc_atan2: 9377 case LibFunc_atan2f: 9378 case LibFunc_atan2l: 9379 if (visitBinaryFloatCall(I, ISD::FATAN2)) 9380 return; 9381 break; 9382 case LibFunc_sinh: 9383 case LibFunc_sinhf: 9384 case LibFunc_sinhl: 9385 if (visitUnaryFloatCall(I, ISD::FSINH)) 9386 return; 9387 break; 9388 case LibFunc_cosh: 9389 case LibFunc_coshf: 9390 case LibFunc_coshl: 9391 if (visitUnaryFloatCall(I, ISD::FCOSH)) 9392 return; 9393 break; 9394 case LibFunc_tanh: 9395 case LibFunc_tanhf: 9396 case LibFunc_tanhl: 9397 if (visitUnaryFloatCall(I, ISD::FTANH)) 9398 return; 9399 break; 9400 case LibFunc_sqrt: 9401 case LibFunc_sqrtf: 9402 case LibFunc_sqrtl: 9403 case LibFunc_sqrt_finite: 9404 case LibFunc_sqrtf_finite: 9405 case LibFunc_sqrtl_finite: 9406 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9407 return; 9408 break; 9409 case LibFunc_floor: 9410 case LibFunc_floorf: 9411 case LibFunc_floorl: 9412 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9413 return; 9414 break; 9415 case LibFunc_nearbyint: 9416 case LibFunc_nearbyintf: 9417 case LibFunc_nearbyintl: 9418 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9419 return; 9420 break; 9421 case LibFunc_ceil: 9422 case LibFunc_ceilf: 9423 case LibFunc_ceill: 9424 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9425 return; 9426 break; 9427 case LibFunc_rint: 9428 case LibFunc_rintf: 9429 case LibFunc_rintl: 9430 if (visitUnaryFloatCall(I, ISD::FRINT)) 9431 return; 9432 break; 9433 case LibFunc_round: 9434 case LibFunc_roundf: 9435 case LibFunc_roundl: 9436 if (visitUnaryFloatCall(I, ISD::FROUND)) 9437 return; 9438 break; 9439 case LibFunc_trunc: 9440 case LibFunc_truncf: 9441 case LibFunc_truncl: 9442 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9443 return; 9444 break; 9445 case LibFunc_log2: 9446 case LibFunc_log2f: 9447 case LibFunc_log2l: 9448 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9449 return; 9450 break; 9451 case LibFunc_exp2: 9452 case LibFunc_exp2f: 9453 case LibFunc_exp2l: 9454 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9455 return; 9456 break; 9457 case LibFunc_exp10: 9458 case LibFunc_exp10f: 9459 case LibFunc_exp10l: 9460 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9461 return; 9462 break; 9463 case LibFunc_ldexp: 9464 case LibFunc_ldexpf: 9465 case LibFunc_ldexpl: 9466 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9467 return; 9468 break; 9469 case LibFunc_memcmp: 9470 if (visitMemCmpBCmpCall(I)) 9471 return; 9472 break; 9473 case LibFunc_mempcpy: 9474 if (visitMemPCpyCall(I)) 9475 return; 9476 break; 9477 case LibFunc_memchr: 9478 if (visitMemChrCall(I)) 9479 return; 9480 break; 9481 case LibFunc_strcpy: 9482 if (visitStrCpyCall(I, false)) 9483 return; 9484 break; 9485 case LibFunc_stpcpy: 9486 if (visitStrCpyCall(I, true)) 9487 return; 9488 break; 9489 case LibFunc_strcmp: 9490 if (visitStrCmpCall(I)) 9491 return; 9492 break; 9493 case LibFunc_strlen: 9494 if (visitStrLenCall(I)) 9495 return; 9496 break; 9497 case LibFunc_strnlen: 9498 if (visitStrNLenCall(I)) 9499 return; 9500 break; 9501 } 9502 } 9503 } 9504 9505 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) { 9506 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr); 9507 return; 9508 } 9509 9510 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9511 // have to do anything here to lower funclet bundles. 9512 // CFGuardTarget bundles are lowered in LowerCallTo. 9513 assert(!I.hasOperandBundlesOtherThan( 9514 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9515 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9516 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9517 LLVMContext::OB_convergencectrl}) && 9518 "Cannot lower calls with arbitrary operand bundles!"); 9519 9520 SDValue Callee = getValue(I.getCalledOperand()); 9521 9522 if (I.hasDeoptState()) 9523 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9524 else 9525 // Check if we can potentially perform a tail call. More detailed checking 9526 // is be done within LowerCallTo, after more information about the call is 9527 // known. 9528 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9529 } 9530 9531 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle( 9532 const CallBase &CB, const BasicBlock *EHPadBB) { 9533 auto PAB = CB.getOperandBundle("ptrauth"); 9534 const Value *CalleeV = CB.getCalledOperand(); 9535 9536 // Gather the call ptrauth data from the operand bundle: 9537 // [ i32 <key>, i64 <discriminator> ] 9538 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]); 9539 const Value *Discriminator = PAB->Inputs[1]; 9540 9541 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key"); 9542 assert(Discriminator->getType()->isIntegerTy(64) && 9543 "Invalid ptrauth discriminator"); 9544 9545 // Look through ptrauth constants to find the raw callee. 9546 // Do a direct unauthenticated call if we found it and everything matches. 9547 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV)) 9548 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator, 9549 DAG.getDataLayout())) 9550 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(), 9551 CB.isMustTailCall(), EHPadBB); 9552 9553 // Functions should never be ptrauth-called directly. 9554 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call"); 9555 9556 // Otherwise, do an authenticated indirect call. 9557 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(), 9558 getValue(Discriminator)}; 9559 9560 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(), 9561 EHPadBB, &PAI); 9562 } 9563 9564 namespace { 9565 9566 /// AsmOperandInfo - This contains information for each constraint that we are 9567 /// lowering. 9568 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9569 public: 9570 /// CallOperand - If this is the result output operand or a clobber 9571 /// this is null, otherwise it is the incoming operand to the CallInst. 9572 /// This gets modified as the asm is processed. 9573 SDValue CallOperand; 9574 9575 /// AssignedRegs - If this is a register or register class operand, this 9576 /// contains the set of register corresponding to the operand. 9577 RegsForValue AssignedRegs; 9578 9579 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9580 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9581 } 9582 9583 /// Whether or not this operand accesses memory 9584 bool hasMemory(const TargetLowering &TLI) const { 9585 // Indirect operand accesses access memory. 9586 if (isIndirect) 9587 return true; 9588 9589 for (const auto &Code : Codes) 9590 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9591 return true; 9592 9593 return false; 9594 } 9595 }; 9596 9597 9598 } // end anonymous namespace 9599 9600 /// Make sure that the output operand \p OpInfo and its corresponding input 9601 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9602 /// out). 9603 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9604 SDISelAsmOperandInfo &MatchingOpInfo, 9605 SelectionDAG &DAG) { 9606 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9607 return; 9608 9609 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9610 const auto &TLI = DAG.getTargetLoweringInfo(); 9611 9612 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9613 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9614 OpInfo.ConstraintVT); 9615 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9616 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9617 MatchingOpInfo.ConstraintVT); 9618 const bool OutOpIsIntOrFP = 9619 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint(); 9620 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() || 9621 MatchingOpInfo.ConstraintVT.isFloatingPoint(); 9622 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) { 9623 // FIXME: error out in a more elegant fashion 9624 report_fatal_error("Unsupported asm: input constraint" 9625 " with a matching output constraint of" 9626 " incompatible type!"); 9627 } 9628 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9629 } 9630 9631 /// Get a direct memory input to behave well as an indirect operand. 9632 /// This may introduce stores, hence the need for a \p Chain. 9633 /// \return The (possibly updated) chain. 9634 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9635 SDISelAsmOperandInfo &OpInfo, 9636 SelectionDAG &DAG) { 9637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9638 9639 // If we don't have an indirect input, put it in the constpool if we can, 9640 // otherwise spill it to a stack slot. 9641 // TODO: This isn't quite right. We need to handle these according to 9642 // the addressing mode that the constraint wants. Also, this may take 9643 // an additional register for the computation and we don't want that 9644 // either. 9645 9646 // If the operand is a float, integer, or vector constant, spill to a 9647 // constant pool entry to get its address. 9648 const Value *OpVal = OpInfo.CallOperandVal; 9649 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9650 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9651 OpInfo.CallOperand = DAG.getConstantPool( 9652 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9653 return Chain; 9654 } 9655 9656 // Otherwise, create a stack slot and emit a store to it before the asm. 9657 Type *Ty = OpVal->getType(); 9658 auto &DL = DAG.getDataLayout(); 9659 TypeSize TySize = DL.getTypeAllocSize(Ty); 9660 MachineFunction &MF = DAG.getMachineFunction(); 9661 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 9662 int StackID = 0; 9663 if (TySize.isScalable()) 9664 StackID = TFI->getStackIDForScalableVectors(); 9665 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(), 9666 DL.getPrefTypeAlign(Ty), false, 9667 nullptr, StackID); 9668 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9669 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9670 MachinePointerInfo::getFixedStack(MF, SSFI), 9671 TLI.getMemValueType(DL, Ty)); 9672 OpInfo.CallOperand = StackSlot; 9673 9674 return Chain; 9675 } 9676 9677 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9678 /// specified operand. We prefer to assign virtual registers, to allow the 9679 /// register allocator to handle the assignment process. However, if the asm 9680 /// uses features that we can't model on machineinstrs, we have SDISel do the 9681 /// allocation. This produces generally horrible, but correct, code. 9682 /// 9683 /// OpInfo describes the operand 9684 /// RefOpInfo describes the matching operand if any, the operand otherwise 9685 static std::optional<unsigned> 9686 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9687 SDISelAsmOperandInfo &OpInfo, 9688 SDISelAsmOperandInfo &RefOpInfo) { 9689 LLVMContext &Context = *DAG.getContext(); 9690 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9691 9692 MachineFunction &MF = DAG.getMachineFunction(); 9693 SmallVector<Register, 4> Regs; 9694 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9695 9696 // No work to do for memory/address operands. 9697 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9698 OpInfo.ConstraintType == TargetLowering::C_Address) 9699 return std::nullopt; 9700 9701 // If this is a constraint for a single physreg, or a constraint for a 9702 // register class, find it. 9703 unsigned AssignedReg; 9704 const TargetRegisterClass *RC; 9705 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9706 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9707 // RC is unset only on failure. Return immediately. 9708 if (!RC) 9709 return std::nullopt; 9710 9711 // Get the actual register value type. This is important, because the user 9712 // may have asked for (e.g.) the AX register in i32 type. We need to 9713 // remember that AX is actually i16 to get the right extension. 9714 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9715 9716 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9717 // If this is an FP operand in an integer register (or visa versa), or more 9718 // generally if the operand value disagrees with the register class we plan 9719 // to stick it in, fix the operand type. 9720 // 9721 // If this is an input value, the bitcast to the new type is done now. 9722 // Bitcast for output value is done at the end of visitInlineAsm(). 9723 if ((OpInfo.Type == InlineAsm::isOutput || 9724 OpInfo.Type == InlineAsm::isInput) && 9725 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9726 // Try to convert to the first EVT that the reg class contains. If the 9727 // types are identical size, use a bitcast to convert (e.g. two differing 9728 // vector types). Note: output bitcast is done at the end of 9729 // visitInlineAsm(). 9730 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9731 // Exclude indirect inputs while they are unsupported because the code 9732 // to perform the load is missing and thus OpInfo.CallOperand still 9733 // refers to the input address rather than the pointed-to value. 9734 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9735 OpInfo.CallOperand = 9736 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9737 OpInfo.ConstraintVT = RegVT; 9738 // If the operand is an FP value and we want it in integer registers, 9739 // use the corresponding integer type. This turns an f64 value into 9740 // i64, which can be passed with two i32 values on a 32-bit machine. 9741 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9742 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9743 if (OpInfo.Type == InlineAsm::isInput) 9744 OpInfo.CallOperand = 9745 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9746 OpInfo.ConstraintVT = VT; 9747 } 9748 } 9749 } 9750 9751 // No need to allocate a matching input constraint since the constraint it's 9752 // matching to has already been allocated. 9753 if (OpInfo.isMatchingInputConstraint()) 9754 return std::nullopt; 9755 9756 EVT ValueVT = OpInfo.ConstraintVT; 9757 if (OpInfo.ConstraintVT == MVT::Other) 9758 ValueVT = RegVT; 9759 9760 // Initialize NumRegs. 9761 unsigned NumRegs = 1; 9762 if (OpInfo.ConstraintVT != MVT::Other) 9763 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9764 9765 // If this is a constraint for a specific physical register, like {r17}, 9766 // assign it now. 9767 9768 // If this associated to a specific register, initialize iterator to correct 9769 // place. If virtual, make sure we have enough registers 9770 9771 // Initialize iterator if necessary 9772 TargetRegisterClass::iterator I = RC->begin(); 9773 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9774 9775 // Do not check for single registers. 9776 if (AssignedReg) { 9777 I = std::find(I, RC->end(), AssignedReg); 9778 if (I == RC->end()) { 9779 // RC does not contain the selected register, which indicates a 9780 // mismatch between the register and the required type/bitwidth. 9781 return {AssignedReg}; 9782 } 9783 } 9784 9785 for (; NumRegs; --NumRegs, ++I) { 9786 assert(I != RC->end() && "Ran out of registers to allocate!"); 9787 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9788 Regs.push_back(R); 9789 } 9790 9791 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9792 return std::nullopt; 9793 } 9794 9795 static unsigned 9796 findMatchingInlineAsmOperand(unsigned OperandNo, 9797 const std::vector<SDValue> &AsmNodeOperands) { 9798 // Scan until we find the definition we already emitted of this operand. 9799 unsigned CurOp = InlineAsm::Op_FirstOperand; 9800 for (; OperandNo; --OperandNo) { 9801 // Advance to the next operand. 9802 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9803 const InlineAsm::Flag F(OpFlag); 9804 assert( 9805 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9806 "Skipped past definitions?"); 9807 CurOp += F.getNumOperandRegisters() + 1; 9808 } 9809 return CurOp; 9810 } 9811 9812 namespace { 9813 9814 class ExtraFlags { 9815 unsigned Flags = 0; 9816 9817 public: 9818 explicit ExtraFlags(const CallBase &Call) { 9819 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9820 if (IA->hasSideEffects()) 9821 Flags |= InlineAsm::Extra_HasSideEffects; 9822 if (IA->isAlignStack()) 9823 Flags |= InlineAsm::Extra_IsAlignStack; 9824 if (Call.isConvergent()) 9825 Flags |= InlineAsm::Extra_IsConvergent; 9826 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9827 } 9828 9829 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9830 // Ideally, we would only check against memory constraints. However, the 9831 // meaning of an Other constraint can be target-specific and we can't easily 9832 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9833 // for Other constraints as well. 9834 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9835 OpInfo.ConstraintType == TargetLowering::C_Other) { 9836 if (OpInfo.Type == InlineAsm::isInput) 9837 Flags |= InlineAsm::Extra_MayLoad; 9838 else if (OpInfo.Type == InlineAsm::isOutput) 9839 Flags |= InlineAsm::Extra_MayStore; 9840 else if (OpInfo.Type == InlineAsm::isClobber) 9841 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9842 } 9843 } 9844 9845 unsigned get() const { return Flags; } 9846 }; 9847 9848 } // end anonymous namespace 9849 9850 static bool isFunction(SDValue Op) { 9851 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9852 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9853 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9854 9855 // In normal "call dllimport func" instruction (non-inlineasm) it force 9856 // indirect access by specifing call opcode. And usually specially print 9857 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9858 // not do in this way now. (In fact, this is similar with "Data Access" 9859 // action). So here we ignore dllimport function. 9860 if (Fn && !Fn->hasDLLImportStorageClass()) 9861 return true; 9862 } 9863 } 9864 return false; 9865 } 9866 9867 /// visitInlineAsm - Handle a call to an InlineAsm object. 9868 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9869 const BasicBlock *EHPadBB) { 9870 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9871 9872 /// ConstraintOperands - Information about all of the constraints. 9873 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9874 9875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9876 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9877 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9878 9879 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9880 // AsmDialect, MayLoad, MayStore). 9881 bool HasSideEffect = IA->hasSideEffects(); 9882 ExtraFlags ExtraInfo(Call); 9883 9884 for (auto &T : TargetConstraints) { 9885 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9886 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9887 9888 if (OpInfo.CallOperandVal) 9889 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9890 9891 if (!HasSideEffect) 9892 HasSideEffect = OpInfo.hasMemory(TLI); 9893 9894 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9895 // FIXME: Could we compute this on OpInfo rather than T? 9896 9897 // Compute the constraint code and ConstraintType to use. 9898 TLI.ComputeConstraintToUse(T, SDValue()); 9899 9900 if (T.ConstraintType == TargetLowering::C_Immediate && 9901 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9902 // We've delayed emitting a diagnostic like the "n" constraint because 9903 // inlining could cause an integer showing up. 9904 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9905 "' expects an integer constant " 9906 "expression"); 9907 9908 ExtraInfo.update(T); 9909 } 9910 9911 // We won't need to flush pending loads if this asm doesn't touch 9912 // memory and is nonvolatile. 9913 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9914 9915 bool EmitEHLabels = isa<InvokeInst>(Call); 9916 if (EmitEHLabels) { 9917 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9918 } 9919 bool IsCallBr = isa<CallBrInst>(Call); 9920 9921 if (IsCallBr || EmitEHLabels) { 9922 // If this is a callbr or invoke we need to flush pending exports since 9923 // inlineasm_br and invoke are terminators. 9924 // We need to do this before nodes are glued to the inlineasm_br node. 9925 Chain = getControlRoot(); 9926 } 9927 9928 MCSymbol *BeginLabel = nullptr; 9929 if (EmitEHLabels) { 9930 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9931 } 9932 9933 int OpNo = -1; 9934 SmallVector<StringRef> AsmStrs; 9935 IA->collectAsmStrs(AsmStrs); 9936 9937 // Second pass over the constraints: compute which constraint option to use. 9938 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9939 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9940 OpNo++; 9941 9942 // If this is an output operand with a matching input operand, look up the 9943 // matching input. If their types mismatch, e.g. one is an integer, the 9944 // other is floating point, or their sizes are different, flag it as an 9945 // error. 9946 if (OpInfo.hasMatchingInput()) { 9947 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9948 patchMatchingInput(OpInfo, Input, DAG); 9949 } 9950 9951 // Compute the constraint code and ConstraintType to use. 9952 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9953 9954 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9955 OpInfo.Type == InlineAsm::isClobber) || 9956 OpInfo.ConstraintType == TargetLowering::C_Address) 9957 continue; 9958 9959 // In Linux PIC model, there are 4 cases about value/label addressing: 9960 // 9961 // 1: Function call or Label jmp inside the module. 9962 // 2: Data access (such as global variable, static variable) inside module. 9963 // 3: Function call or Label jmp outside the module. 9964 // 4: Data access (such as global variable) outside the module. 9965 // 9966 // Due to current llvm inline asm architecture designed to not "recognize" 9967 // the asm code, there are quite troubles for us to treat mem addressing 9968 // differently for same value/adress used in different instuctions. 9969 // For example, in pic model, call a func may in plt way or direclty 9970 // pc-related, but lea/mov a function adress may use got. 9971 // 9972 // Here we try to "recognize" function call for the case 1 and case 3 in 9973 // inline asm. And try to adjust the constraint for them. 9974 // 9975 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9976 // label, so here we don't handle jmp function label now, but we need to 9977 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9978 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9979 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9980 TM.getCodeModel() != CodeModel::Large) { 9981 OpInfo.isIndirect = false; 9982 OpInfo.ConstraintType = TargetLowering::C_Address; 9983 } 9984 9985 // If this is a memory input, and if the operand is not indirect, do what we 9986 // need to provide an address for the memory input. 9987 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9988 !OpInfo.isIndirect) { 9989 assert((OpInfo.isMultipleAlternative || 9990 (OpInfo.Type == InlineAsm::isInput)) && 9991 "Can only indirectify direct input operands!"); 9992 9993 // Memory operands really want the address of the value. 9994 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9995 9996 // There is no longer a Value* corresponding to this operand. 9997 OpInfo.CallOperandVal = nullptr; 9998 9999 // It is now an indirect operand. 10000 OpInfo.isIndirect = true; 10001 } 10002 10003 } 10004 10005 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 10006 std::vector<SDValue> AsmNodeOperands; 10007 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 10008 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 10009 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 10010 10011 // If we have a !srcloc metadata node associated with it, we want to attach 10012 // this to the ultimately generated inline asm machineinstr. To do this, we 10013 // pass in the third operand as this (potentially null) inline asm MDNode. 10014 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 10015 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 10016 10017 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 10018 // bits as operand 3. 10019 AsmNodeOperands.push_back(DAG.getTargetConstant( 10020 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10021 10022 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 10023 // this, assign virtual and physical registers for inputs and otput. 10024 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10025 // Assign Registers. 10026 SDISelAsmOperandInfo &RefOpInfo = 10027 OpInfo.isMatchingInputConstraint() 10028 ? ConstraintOperands[OpInfo.getMatchedOperand()] 10029 : OpInfo; 10030 const auto RegError = 10031 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 10032 if (RegError) { 10033 const MachineFunction &MF = DAG.getMachineFunction(); 10034 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10035 const char *RegName = TRI.getName(*RegError); 10036 emitInlineAsmError(Call, "register '" + Twine(RegName) + 10037 "' allocated for constraint '" + 10038 Twine(OpInfo.ConstraintCode) + 10039 "' does not match required type"); 10040 return; 10041 } 10042 10043 auto DetectWriteToReservedRegister = [&]() { 10044 const MachineFunction &MF = DAG.getMachineFunction(); 10045 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10046 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 10047 if (Register::isPhysicalRegister(Reg) && 10048 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 10049 const char *RegName = TRI.getName(Reg); 10050 emitInlineAsmError(Call, "write to reserved register '" + 10051 Twine(RegName) + "'"); 10052 return true; 10053 } 10054 } 10055 return false; 10056 }; 10057 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 10058 (OpInfo.Type == InlineAsm::isInput && 10059 !OpInfo.isMatchingInputConstraint())) && 10060 "Only address as input operand is allowed."); 10061 10062 switch (OpInfo.Type) { 10063 case InlineAsm::isOutput: 10064 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10065 const InlineAsm::ConstraintCode ConstraintID = 10066 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10067 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10068 "Failed to convert memory constraint code to constraint id."); 10069 10070 // Add information to the INLINEASM node to know about this output. 10071 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 10072 OpFlags.setMemConstraint(ConstraintID); 10073 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 10074 MVT::i32)); 10075 AsmNodeOperands.push_back(OpInfo.CallOperand); 10076 } else { 10077 // Otherwise, this outputs to a register (directly for C_Register / 10078 // C_RegisterClass, and a target-defined fashion for 10079 // C_Immediate/C_Other). Find a register that we can use. 10080 if (OpInfo.AssignedRegs.Regs.empty()) { 10081 emitInlineAsmError( 10082 Call, "couldn't allocate output register for constraint '" + 10083 Twine(OpInfo.ConstraintCode) + "'"); 10084 return; 10085 } 10086 10087 if (DetectWriteToReservedRegister()) 10088 return; 10089 10090 // Add information to the INLINEASM node to know that this register is 10091 // set. 10092 OpInfo.AssignedRegs.AddInlineAsmOperands( 10093 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 10094 : InlineAsm::Kind::RegDef, 10095 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 10096 } 10097 break; 10098 10099 case InlineAsm::isInput: 10100 case InlineAsm::isLabel: { 10101 SDValue InOperandVal = OpInfo.CallOperand; 10102 10103 if (OpInfo.isMatchingInputConstraint()) { 10104 // If this is required to match an output register we have already set, 10105 // just use its register. 10106 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 10107 AsmNodeOperands); 10108 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 10109 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 10110 if (OpInfo.isIndirect) { 10111 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 10112 emitInlineAsmError(Call, "inline asm not supported yet: " 10113 "don't know how to handle tied " 10114 "indirect register inputs"); 10115 return; 10116 } 10117 10118 SmallVector<Register, 4> Regs; 10119 MachineFunction &MF = DAG.getMachineFunction(); 10120 MachineRegisterInfo &MRI = MF.getRegInfo(); 10121 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 10122 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 10123 Register TiedReg = R->getReg(); 10124 MVT RegVT = R->getSimpleValueType(0); 10125 const TargetRegisterClass *RC = 10126 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 10127 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 10128 : TRI.getMinimalPhysRegClass(TiedReg); 10129 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 10130 Regs.push_back(MRI.createVirtualRegister(RC)); 10131 10132 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 10133 10134 SDLoc dl = getCurSDLoc(); 10135 // Use the produced MatchedRegs object to 10136 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 10137 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 10138 OpInfo.getMatchedOperand(), dl, DAG, 10139 AsmNodeOperands); 10140 break; 10141 } 10142 10143 assert(Flag.isMemKind() && "Unknown matching constraint!"); 10144 assert(Flag.getNumOperandRegisters() == 1 && 10145 "Unexpected number of operands"); 10146 // Add information to the INLINEASM node to know about this input. 10147 // See InlineAsm.h isUseOperandTiedToDef. 10148 Flag.clearMemConstraint(); 10149 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 10150 AsmNodeOperands.push_back(DAG.getTargetConstant( 10151 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10152 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 10153 break; 10154 } 10155 10156 // Treat indirect 'X' constraint as memory. 10157 if (OpInfo.ConstraintType == TargetLowering::C_Other && 10158 OpInfo.isIndirect) 10159 OpInfo.ConstraintType = TargetLowering::C_Memory; 10160 10161 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 10162 OpInfo.ConstraintType == TargetLowering::C_Other) { 10163 std::vector<SDValue> Ops; 10164 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 10165 Ops, DAG); 10166 if (Ops.empty()) { 10167 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 10168 if (isa<ConstantSDNode>(InOperandVal)) { 10169 emitInlineAsmError(Call, "value out of range for constraint '" + 10170 Twine(OpInfo.ConstraintCode) + "'"); 10171 return; 10172 } 10173 10174 emitInlineAsmError(Call, 10175 "invalid operand for inline asm constraint '" + 10176 Twine(OpInfo.ConstraintCode) + "'"); 10177 return; 10178 } 10179 10180 // Add information to the INLINEASM node to know about this input. 10181 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 10182 AsmNodeOperands.push_back(DAG.getTargetConstant( 10183 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 10184 llvm::append_range(AsmNodeOperands, Ops); 10185 break; 10186 } 10187 10188 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 10189 assert((OpInfo.isIndirect || 10190 OpInfo.ConstraintType != TargetLowering::C_Memory) && 10191 "Operand must be indirect to be a mem!"); 10192 assert(InOperandVal.getValueType() == 10193 TLI.getPointerTy(DAG.getDataLayout()) && 10194 "Memory operands expect pointer values"); 10195 10196 const InlineAsm::ConstraintCode ConstraintID = 10197 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10198 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10199 "Failed to convert memory constraint code to constraint id."); 10200 10201 // Add information to the INLINEASM node to know about this input. 10202 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10203 ResOpType.setMemConstraint(ConstraintID); 10204 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 10205 getCurSDLoc(), 10206 MVT::i32)); 10207 AsmNodeOperands.push_back(InOperandVal); 10208 break; 10209 } 10210 10211 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 10212 const InlineAsm::ConstraintCode ConstraintID = 10213 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 10214 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 10215 "Failed to convert memory constraint code to constraint id."); 10216 10217 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 10218 10219 SDValue AsmOp = InOperandVal; 10220 if (isFunction(InOperandVal)) { 10221 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 10222 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 10223 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 10224 InOperandVal.getValueType(), 10225 GA->getOffset()); 10226 } 10227 10228 // Add information to the INLINEASM node to know about this input. 10229 ResOpType.setMemConstraint(ConstraintID); 10230 10231 AsmNodeOperands.push_back( 10232 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 10233 10234 AsmNodeOperands.push_back(AsmOp); 10235 break; 10236 } 10237 10238 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 10239 OpInfo.ConstraintType != TargetLowering::C_Register) { 10240 emitInlineAsmError(Call, "unknown asm constraint '" + 10241 Twine(OpInfo.ConstraintCode) + "'"); 10242 return; 10243 } 10244 10245 // TODO: Support this. 10246 if (OpInfo.isIndirect) { 10247 emitInlineAsmError( 10248 Call, "Don't know how to handle indirect register inputs yet " 10249 "for constraint '" + 10250 Twine(OpInfo.ConstraintCode) + "'"); 10251 return; 10252 } 10253 10254 // Copy the input into the appropriate registers. 10255 if (OpInfo.AssignedRegs.Regs.empty()) { 10256 emitInlineAsmError(Call, 10257 "couldn't allocate input reg for constraint '" + 10258 Twine(OpInfo.ConstraintCode) + "'"); 10259 return; 10260 } 10261 10262 if (DetectWriteToReservedRegister()) 10263 return; 10264 10265 SDLoc dl = getCurSDLoc(); 10266 10267 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 10268 &Call); 10269 10270 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 10271 0, dl, DAG, AsmNodeOperands); 10272 break; 10273 } 10274 case InlineAsm::isClobber: 10275 // Add the clobbered value to the operand list, so that the register 10276 // allocator is aware that the physreg got clobbered. 10277 if (!OpInfo.AssignedRegs.Regs.empty()) 10278 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 10279 false, 0, getCurSDLoc(), DAG, 10280 AsmNodeOperands); 10281 break; 10282 } 10283 } 10284 10285 // Finish up input operands. Set the input chain and add the flag last. 10286 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 10287 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 10288 10289 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 10290 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 10291 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 10292 Glue = Chain.getValue(1); 10293 10294 // Do additional work to generate outputs. 10295 10296 SmallVector<EVT, 1> ResultVTs; 10297 SmallVector<SDValue, 1> ResultValues; 10298 SmallVector<SDValue, 8> OutChains; 10299 10300 llvm::Type *CallResultType = Call.getType(); 10301 ArrayRef<Type *> ResultTypes; 10302 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10303 ResultTypes = StructResult->elements(); 10304 else if (!CallResultType->isVoidTy()) 10305 ResultTypes = ArrayRef(CallResultType); 10306 10307 auto CurResultType = ResultTypes.begin(); 10308 auto handleRegAssign = [&](SDValue V) { 10309 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10310 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10311 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10312 ++CurResultType; 10313 // If the type of the inline asm call site return value is different but has 10314 // same size as the type of the asm output bitcast it. One example of this 10315 // is for vectors with different width / number of elements. This can 10316 // happen for register classes that can contain multiple different value 10317 // types. The preg or vreg allocated may not have the same VT as was 10318 // expected. 10319 // 10320 // This can also happen for a return value that disagrees with the register 10321 // class it is put in, eg. a double in a general-purpose register on a 10322 // 32-bit machine. 10323 if (ResultVT != V.getValueType() && 10324 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10325 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10326 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10327 V.getValueType().isInteger()) { 10328 // If a result value was tied to an input value, the computed result 10329 // may have a wider width than the expected result. Extract the 10330 // relevant portion. 10331 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10332 } 10333 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10334 ResultVTs.push_back(ResultVT); 10335 ResultValues.push_back(V); 10336 }; 10337 10338 // Deal with output operands. 10339 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10340 if (OpInfo.Type == InlineAsm::isOutput) { 10341 SDValue Val; 10342 // Skip trivial output operands. 10343 if (OpInfo.AssignedRegs.Regs.empty()) 10344 continue; 10345 10346 switch (OpInfo.ConstraintType) { 10347 case TargetLowering::C_Register: 10348 case TargetLowering::C_RegisterClass: 10349 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10350 Chain, &Glue, &Call); 10351 break; 10352 case TargetLowering::C_Immediate: 10353 case TargetLowering::C_Other: 10354 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10355 OpInfo, DAG); 10356 break; 10357 case TargetLowering::C_Memory: 10358 break; // Already handled. 10359 case TargetLowering::C_Address: 10360 break; // Silence warning. 10361 case TargetLowering::C_Unknown: 10362 assert(false && "Unexpected unknown constraint"); 10363 } 10364 10365 // Indirect output manifest as stores. Record output chains. 10366 if (OpInfo.isIndirect) { 10367 const Value *Ptr = OpInfo.CallOperandVal; 10368 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10369 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10370 MachinePointerInfo(Ptr)); 10371 OutChains.push_back(Store); 10372 } else { 10373 // generate CopyFromRegs to associated registers. 10374 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10375 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10376 for (const SDValue &V : Val->op_values()) 10377 handleRegAssign(V); 10378 } else 10379 handleRegAssign(Val); 10380 } 10381 } 10382 } 10383 10384 // Set results. 10385 if (!ResultValues.empty()) { 10386 assert(CurResultType == ResultTypes.end() && 10387 "Mismatch in number of ResultTypes"); 10388 assert(ResultValues.size() == ResultTypes.size() && 10389 "Mismatch in number of output operands in asm result"); 10390 10391 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10392 DAG.getVTList(ResultVTs), ResultValues); 10393 setValue(&Call, V); 10394 } 10395 10396 // Collect store chains. 10397 if (!OutChains.empty()) 10398 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10399 10400 if (EmitEHLabels) { 10401 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10402 } 10403 10404 // Only Update Root if inline assembly has a memory effect. 10405 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10406 EmitEHLabels) 10407 DAG.setRoot(Chain); 10408 } 10409 10410 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10411 const Twine &Message) { 10412 LLVMContext &Ctx = *DAG.getContext(); 10413 Ctx.emitError(&Call, Message); 10414 10415 // Make sure we leave the DAG in a valid state 10416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10417 SmallVector<EVT, 1> ValueVTs; 10418 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10419 10420 if (ValueVTs.empty()) 10421 return; 10422 10423 SmallVector<SDValue, 1> Ops; 10424 for (const EVT &VT : ValueVTs) 10425 Ops.push_back(DAG.getUNDEF(VT)); 10426 10427 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10428 } 10429 10430 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10431 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10432 MVT::Other, getRoot(), 10433 getValue(I.getArgOperand(0)), 10434 DAG.getSrcValue(I.getArgOperand(0)))); 10435 } 10436 10437 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10439 const DataLayout &DL = DAG.getDataLayout(); 10440 SDValue V = DAG.getVAArg( 10441 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10442 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10443 DL.getABITypeAlign(I.getType()).value()); 10444 DAG.setRoot(V.getValue(1)); 10445 10446 if (I.getType()->isPointerTy()) 10447 V = DAG.getPtrExtOrTrunc( 10448 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10449 setValue(&I, V); 10450 } 10451 10452 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10453 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10454 MVT::Other, getRoot(), 10455 getValue(I.getArgOperand(0)), 10456 DAG.getSrcValue(I.getArgOperand(0)))); 10457 } 10458 10459 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10460 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10461 MVT::Other, getRoot(), 10462 getValue(I.getArgOperand(0)), 10463 getValue(I.getArgOperand(1)), 10464 DAG.getSrcValue(I.getArgOperand(0)), 10465 DAG.getSrcValue(I.getArgOperand(1)))); 10466 } 10467 10468 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10469 const Instruction &I, 10470 SDValue Op) { 10471 std::optional<ConstantRange> CR = getRange(I); 10472 10473 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped()) 10474 return Op; 10475 10476 APInt Lo = CR->getUnsignedMin(); 10477 if (!Lo.isMinValue()) 10478 return Op; 10479 10480 APInt Hi = CR->getUnsignedMax(); 10481 unsigned Bits = std::max(Hi.getActiveBits(), 10482 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10483 10484 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10485 10486 SDLoc SL = getCurSDLoc(); 10487 10488 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10489 DAG.getValueType(SmallVT)); 10490 unsigned NumVals = Op.getNode()->getNumValues(); 10491 if (NumVals == 1) 10492 return ZExt; 10493 10494 SmallVector<SDValue, 4> Ops; 10495 10496 Ops.push_back(ZExt); 10497 for (unsigned I = 1; I != NumVals; ++I) 10498 Ops.push_back(Op.getValue(I)); 10499 10500 return DAG.getMergeValues(Ops, SL); 10501 } 10502 10503 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10504 /// the call being lowered. 10505 /// 10506 /// This is a helper for lowering intrinsics that follow a target calling 10507 /// convention or require stack pointer adjustment. Only a subset of the 10508 /// intrinsic's operands need to participate in the calling convention. 10509 void SelectionDAGBuilder::populateCallLoweringInfo( 10510 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10511 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10512 AttributeSet RetAttrs, bool IsPatchPoint) { 10513 TargetLowering::ArgListTy Args; 10514 Args.reserve(NumArgs); 10515 10516 // Populate the argument list. 10517 // Attributes for args start at offset 1, after the return attribute. 10518 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10519 ArgI != ArgE; ++ArgI) { 10520 const Value *V = Call->getOperand(ArgI); 10521 10522 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10523 10524 TargetLowering::ArgListEntry Entry; 10525 Entry.Node = getValue(V); 10526 Entry.Ty = V->getType(); 10527 Entry.setAttributes(Call, ArgI); 10528 Args.push_back(Entry); 10529 } 10530 10531 CLI.setDebugLoc(getCurSDLoc()) 10532 .setChain(getRoot()) 10533 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10534 RetAttrs) 10535 .setDiscardResult(Call->use_empty()) 10536 .setIsPatchPoint(IsPatchPoint) 10537 .setIsPreallocated( 10538 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10539 } 10540 10541 /// Add a stack map intrinsic call's live variable operands to a stackmap 10542 /// or patchpoint target node's operand list. 10543 /// 10544 /// Constants are converted to TargetConstants purely as an optimization to 10545 /// avoid constant materialization and register allocation. 10546 /// 10547 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10548 /// generate addess computation nodes, and so FinalizeISel can convert the 10549 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10550 /// address materialization and register allocation, but may also be required 10551 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10552 /// alloca in the entry block, then the runtime may assume that the alloca's 10553 /// StackMap location can be read immediately after compilation and that the 10554 /// location is valid at any point during execution (this is similar to the 10555 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10556 /// only available in a register, then the runtime would need to trap when 10557 /// execution reaches the StackMap in order to read the alloca's location. 10558 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10559 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10560 SelectionDAGBuilder &Builder) { 10561 SelectionDAG &DAG = Builder.DAG; 10562 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10563 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10564 10565 // Things on the stack are pointer-typed, meaning that they are already 10566 // legal and can be emitted directly to target nodes. 10567 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10568 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10569 } else { 10570 // Otherwise emit a target independent node to be legalised. 10571 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10572 } 10573 } 10574 } 10575 10576 /// Lower llvm.experimental.stackmap. 10577 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10578 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10579 // [live variables...]) 10580 10581 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10582 10583 SDValue Chain, InGlue, Callee; 10584 SmallVector<SDValue, 32> Ops; 10585 10586 SDLoc DL = getCurSDLoc(); 10587 Callee = getValue(CI.getCalledOperand()); 10588 10589 // The stackmap intrinsic only records the live variables (the arguments 10590 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10591 // intrinsic, this won't be lowered to a function call. This means we don't 10592 // have to worry about calling conventions and target specific lowering code. 10593 // Instead we perform the call lowering right here. 10594 // 10595 // chain, flag = CALLSEQ_START(chain, 0, 0) 10596 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10597 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10598 // 10599 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10600 InGlue = Chain.getValue(1); 10601 10602 // Add the STACKMAP operands, starting with DAG house-keeping. 10603 Ops.push_back(Chain); 10604 Ops.push_back(InGlue); 10605 10606 // Add the <id>, <numShadowBytes> operands. 10607 // 10608 // These do not require legalisation, and can be emitted directly to target 10609 // constant nodes. 10610 SDValue ID = getValue(CI.getArgOperand(0)); 10611 assert(ID.getValueType() == MVT::i64); 10612 SDValue IDConst = 10613 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10614 Ops.push_back(IDConst); 10615 10616 SDValue Shad = getValue(CI.getArgOperand(1)); 10617 assert(Shad.getValueType() == MVT::i32); 10618 SDValue ShadConst = 10619 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10620 Ops.push_back(ShadConst); 10621 10622 // Add the live variables. 10623 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10624 10625 // Create the STACKMAP node. 10626 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10627 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10628 InGlue = Chain.getValue(1); 10629 10630 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10631 10632 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10633 10634 // Set the root to the target-lowered call chain. 10635 DAG.setRoot(Chain); 10636 10637 // Inform the Frame Information that we have a stackmap in this function. 10638 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10639 } 10640 10641 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10642 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10643 const BasicBlock *EHPadBB) { 10644 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10645 // i32 <numBytes>, 10646 // i8* <target>, 10647 // i32 <numArgs>, 10648 // [Args...], 10649 // [live variables...]) 10650 10651 CallingConv::ID CC = CB.getCallingConv(); 10652 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10653 bool HasDef = !CB.getType()->isVoidTy(); 10654 SDLoc dl = getCurSDLoc(); 10655 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10656 10657 // Handle immediate and symbolic callees. 10658 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10659 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10660 /*isTarget=*/true); 10661 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10662 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10663 SDLoc(SymbolicCallee), 10664 SymbolicCallee->getValueType(0)); 10665 10666 // Get the real number of arguments participating in the call <numArgs> 10667 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10668 unsigned NumArgs = NArgVal->getAsZExtVal(); 10669 10670 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10671 // Intrinsics include all meta-operands up to but not including CC. 10672 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10673 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10674 "Not enough arguments provided to the patchpoint intrinsic"); 10675 10676 // For AnyRegCC the arguments are lowered later on manually. 10677 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10678 Type *ReturnTy = 10679 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10680 10681 TargetLowering::CallLoweringInfo CLI(DAG); 10682 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10683 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10684 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10685 10686 SDNode *CallEnd = Result.second.getNode(); 10687 if (CallEnd->getOpcode() == ISD::EH_LABEL) 10688 CallEnd = CallEnd->getOperand(0).getNode(); 10689 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10690 CallEnd = CallEnd->getOperand(0).getNode(); 10691 10692 /// Get a call instruction from the call sequence chain. 10693 /// Tail calls are not allowed. 10694 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10695 "Expected a callseq node."); 10696 SDNode *Call = CallEnd->getOperand(0).getNode(); 10697 bool HasGlue = Call->getGluedNode(); 10698 10699 // Replace the target specific call node with the patchable intrinsic. 10700 SmallVector<SDValue, 8> Ops; 10701 10702 // Push the chain. 10703 Ops.push_back(*(Call->op_begin())); 10704 10705 // Optionally, push the glue (if any). 10706 if (HasGlue) 10707 Ops.push_back(*(Call->op_end() - 1)); 10708 10709 // Push the register mask info. 10710 if (HasGlue) 10711 Ops.push_back(*(Call->op_end() - 2)); 10712 else 10713 Ops.push_back(*(Call->op_end() - 1)); 10714 10715 // Add the <id> and <numBytes> constants. 10716 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10717 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10718 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10719 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10720 10721 // Add the callee. 10722 Ops.push_back(Callee); 10723 10724 // Adjust <numArgs> to account for any arguments that have been passed on the 10725 // stack instead. 10726 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10727 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10728 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10729 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10730 10731 // Add the calling convention 10732 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10733 10734 // Add the arguments we omitted previously. The register allocator should 10735 // place these in any free register. 10736 if (IsAnyRegCC) 10737 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10738 Ops.push_back(getValue(CB.getArgOperand(i))); 10739 10740 // Push the arguments from the call instruction. 10741 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10742 Ops.append(Call->op_begin() + 2, e); 10743 10744 // Push live variables for the stack map. 10745 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10746 10747 SDVTList NodeTys; 10748 if (IsAnyRegCC && HasDef) { 10749 // Create the return types based on the intrinsic definition 10750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10751 SmallVector<EVT, 3> ValueVTs; 10752 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10753 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10754 10755 // There is always a chain and a glue type at the end 10756 ValueVTs.push_back(MVT::Other); 10757 ValueVTs.push_back(MVT::Glue); 10758 NodeTys = DAG.getVTList(ValueVTs); 10759 } else 10760 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10761 10762 // Replace the target specific call node with a PATCHPOINT node. 10763 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10764 10765 // Update the NodeMap. 10766 if (HasDef) { 10767 if (IsAnyRegCC) 10768 setValue(&CB, SDValue(PPV.getNode(), 0)); 10769 else 10770 setValue(&CB, Result.first); 10771 } 10772 10773 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10774 // call sequence. Furthermore the location of the chain and glue can change 10775 // when the AnyReg calling convention is used and the intrinsic returns a 10776 // value. 10777 if (IsAnyRegCC && HasDef) { 10778 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10779 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10780 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10781 } else 10782 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10783 DAG.DeleteNode(Call); 10784 10785 // Inform the Frame Information that we have a patchpoint in this function. 10786 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10787 } 10788 10789 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10790 unsigned Intrinsic) { 10791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10792 SDValue Op1 = getValue(I.getArgOperand(0)); 10793 SDValue Op2; 10794 if (I.arg_size() > 1) 10795 Op2 = getValue(I.getArgOperand(1)); 10796 SDLoc dl = getCurSDLoc(); 10797 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10798 SDValue Res; 10799 SDNodeFlags SDFlags; 10800 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10801 SDFlags.copyFMF(*FPMO); 10802 10803 switch (Intrinsic) { 10804 case Intrinsic::vector_reduce_fadd: 10805 if (SDFlags.hasAllowReassociation()) 10806 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10807 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10808 SDFlags); 10809 else 10810 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10811 break; 10812 case Intrinsic::vector_reduce_fmul: 10813 if (SDFlags.hasAllowReassociation()) 10814 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10815 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10816 SDFlags); 10817 else 10818 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10819 break; 10820 case Intrinsic::vector_reduce_add: 10821 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10822 break; 10823 case Intrinsic::vector_reduce_mul: 10824 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10825 break; 10826 case Intrinsic::vector_reduce_and: 10827 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10828 break; 10829 case Intrinsic::vector_reduce_or: 10830 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10831 break; 10832 case Intrinsic::vector_reduce_xor: 10833 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10834 break; 10835 case Intrinsic::vector_reduce_smax: 10836 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10837 break; 10838 case Intrinsic::vector_reduce_smin: 10839 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10840 break; 10841 case Intrinsic::vector_reduce_umax: 10842 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10843 break; 10844 case Intrinsic::vector_reduce_umin: 10845 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10846 break; 10847 case Intrinsic::vector_reduce_fmax: 10848 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10849 break; 10850 case Intrinsic::vector_reduce_fmin: 10851 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10852 break; 10853 case Intrinsic::vector_reduce_fmaximum: 10854 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10855 break; 10856 case Intrinsic::vector_reduce_fminimum: 10857 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10858 break; 10859 default: 10860 llvm_unreachable("Unhandled vector reduce intrinsic"); 10861 } 10862 setValue(&I, Res); 10863 } 10864 10865 /// Returns an AttributeList representing the attributes applied to the return 10866 /// value of the given call. 10867 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10868 SmallVector<Attribute::AttrKind, 2> Attrs; 10869 if (CLI.RetSExt) 10870 Attrs.push_back(Attribute::SExt); 10871 if (CLI.RetZExt) 10872 Attrs.push_back(Attribute::ZExt); 10873 if (CLI.IsInReg) 10874 Attrs.push_back(Attribute::InReg); 10875 10876 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10877 Attrs); 10878 } 10879 10880 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10881 /// implementation, which just calls LowerCall. 10882 /// FIXME: When all targets are 10883 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10884 std::pair<SDValue, SDValue> 10885 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10886 // Handle the incoming return values from the call. 10887 CLI.Ins.clear(); 10888 Type *OrigRetTy = CLI.RetTy; 10889 SmallVector<EVT, 4> RetTys; 10890 SmallVector<TypeSize, 4> Offsets; 10891 auto &DL = CLI.DAG.getDataLayout(); 10892 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10893 10894 if (CLI.IsPostTypeLegalization) { 10895 // If we are lowering a libcall after legalization, split the return type. 10896 SmallVector<EVT, 4> OldRetTys; 10897 SmallVector<TypeSize, 4> OldOffsets; 10898 RetTys.swap(OldRetTys); 10899 Offsets.swap(OldOffsets); 10900 10901 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10902 EVT RetVT = OldRetTys[i]; 10903 uint64_t Offset = OldOffsets[i]; 10904 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10905 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10906 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10907 RetTys.append(NumRegs, RegisterVT); 10908 for (unsigned j = 0; j != NumRegs; ++j) 10909 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10910 } 10911 } 10912 10913 SmallVector<ISD::OutputArg, 4> Outs; 10914 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10915 10916 bool CanLowerReturn = 10917 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10918 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10919 10920 SDValue DemoteStackSlot; 10921 int DemoteStackIdx = -100; 10922 if (!CanLowerReturn) { 10923 // FIXME: equivalent assert? 10924 // assert(!CS.hasInAllocaArgument() && 10925 // "sret demotion is incompatible with inalloca"); 10926 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10927 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10928 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10929 DemoteStackIdx = 10930 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10931 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10932 DL.getAllocaAddrSpace()); 10933 10934 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10935 ArgListEntry Entry; 10936 Entry.Node = DemoteStackSlot; 10937 Entry.Ty = StackSlotPtrType; 10938 Entry.IsSExt = false; 10939 Entry.IsZExt = false; 10940 Entry.IsInReg = false; 10941 Entry.IsSRet = true; 10942 Entry.IsNest = false; 10943 Entry.IsByVal = false; 10944 Entry.IsByRef = false; 10945 Entry.IsReturned = false; 10946 Entry.IsSwiftSelf = false; 10947 Entry.IsSwiftAsync = false; 10948 Entry.IsSwiftError = false; 10949 Entry.IsCFGuardTarget = false; 10950 Entry.Alignment = Alignment; 10951 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10952 CLI.NumFixedArgs += 1; 10953 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10954 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10955 10956 // sret demotion isn't compatible with tail-calls, since the sret argument 10957 // points into the callers stack frame. 10958 CLI.IsTailCall = false; 10959 } else { 10960 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10961 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10962 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10963 ISD::ArgFlagsTy Flags; 10964 if (NeedsRegBlock) { 10965 Flags.setInConsecutiveRegs(); 10966 if (I == RetTys.size() - 1) 10967 Flags.setInConsecutiveRegsLast(); 10968 } 10969 EVT VT = RetTys[I]; 10970 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10971 CLI.CallConv, VT); 10972 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10973 CLI.CallConv, VT); 10974 for (unsigned i = 0; i != NumRegs; ++i) { 10975 ISD::InputArg MyFlags; 10976 MyFlags.Flags = Flags; 10977 MyFlags.VT = RegisterVT; 10978 MyFlags.ArgVT = VT; 10979 MyFlags.Used = CLI.IsReturnValueUsed; 10980 if (CLI.RetTy->isPointerTy()) { 10981 MyFlags.Flags.setPointer(); 10982 MyFlags.Flags.setPointerAddrSpace( 10983 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10984 } 10985 if (CLI.RetSExt) 10986 MyFlags.Flags.setSExt(); 10987 if (CLI.RetZExt) 10988 MyFlags.Flags.setZExt(); 10989 if (CLI.IsInReg) 10990 MyFlags.Flags.setInReg(); 10991 CLI.Ins.push_back(MyFlags); 10992 } 10993 } 10994 } 10995 10996 // We push in swifterror return as the last element of CLI.Ins. 10997 ArgListTy &Args = CLI.getArgs(); 10998 if (supportSwiftError()) { 10999 for (const ArgListEntry &Arg : Args) { 11000 if (Arg.IsSwiftError) { 11001 ISD::InputArg MyFlags; 11002 MyFlags.VT = getPointerTy(DL); 11003 MyFlags.ArgVT = EVT(getPointerTy(DL)); 11004 MyFlags.Flags.setSwiftError(); 11005 CLI.Ins.push_back(MyFlags); 11006 } 11007 } 11008 } 11009 11010 // Handle all of the outgoing arguments. 11011 CLI.Outs.clear(); 11012 CLI.OutVals.clear(); 11013 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 11014 SmallVector<EVT, 4> ValueVTs; 11015 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 11016 // FIXME: Split arguments if CLI.IsPostTypeLegalization 11017 Type *FinalType = Args[i].Ty; 11018 if (Args[i].IsByVal) 11019 FinalType = Args[i].IndirectType; 11020 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 11021 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 11022 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 11023 ++Value) { 11024 EVT VT = ValueVTs[Value]; 11025 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 11026 SDValue Op = SDValue(Args[i].Node.getNode(), 11027 Args[i].Node.getResNo() + Value); 11028 ISD::ArgFlagsTy Flags; 11029 11030 // Certain targets (such as MIPS), may have a different ABI alignment 11031 // for a type depending on the context. Give the target a chance to 11032 // specify the alignment it wants. 11033 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 11034 Flags.setOrigAlign(OriginalAlignment); 11035 11036 if (Args[i].Ty->isPointerTy()) { 11037 Flags.setPointer(); 11038 Flags.setPointerAddrSpace( 11039 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 11040 } 11041 if (Args[i].IsZExt) 11042 Flags.setZExt(); 11043 if (Args[i].IsSExt) 11044 Flags.setSExt(); 11045 if (Args[i].IsNoExt) 11046 Flags.setNoExt(); 11047 if (Args[i].IsInReg) { 11048 // If we are using vectorcall calling convention, a structure that is 11049 // passed InReg - is surely an HVA 11050 if (CLI.CallConv == CallingConv::X86_VectorCall && 11051 isa<StructType>(FinalType)) { 11052 // The first value of a structure is marked 11053 if (0 == Value) 11054 Flags.setHvaStart(); 11055 Flags.setHva(); 11056 } 11057 // Set InReg Flag 11058 Flags.setInReg(); 11059 } 11060 if (Args[i].IsSRet) 11061 Flags.setSRet(); 11062 if (Args[i].IsSwiftSelf) 11063 Flags.setSwiftSelf(); 11064 if (Args[i].IsSwiftAsync) 11065 Flags.setSwiftAsync(); 11066 if (Args[i].IsSwiftError) 11067 Flags.setSwiftError(); 11068 if (Args[i].IsCFGuardTarget) 11069 Flags.setCFGuardTarget(); 11070 if (Args[i].IsByVal) 11071 Flags.setByVal(); 11072 if (Args[i].IsByRef) 11073 Flags.setByRef(); 11074 if (Args[i].IsPreallocated) { 11075 Flags.setPreallocated(); 11076 // Set the byval flag for CCAssignFn callbacks that don't know about 11077 // preallocated. This way we can know how many bytes we should've 11078 // allocated and how many bytes a callee cleanup function will pop. If 11079 // we port preallocated to more targets, we'll have to add custom 11080 // preallocated handling in the various CC lowering callbacks. 11081 Flags.setByVal(); 11082 } 11083 if (Args[i].IsInAlloca) { 11084 Flags.setInAlloca(); 11085 // Set the byval flag for CCAssignFn callbacks that don't know about 11086 // inalloca. This way we can know how many bytes we should've allocated 11087 // and how many bytes a callee cleanup function will pop. If we port 11088 // inalloca to more targets, we'll have to add custom inalloca handling 11089 // in the various CC lowering callbacks. 11090 Flags.setByVal(); 11091 } 11092 Align MemAlign; 11093 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 11094 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 11095 Flags.setByValSize(FrameSize); 11096 11097 // info is not there but there are cases it cannot get right. 11098 if (auto MA = Args[i].Alignment) 11099 MemAlign = *MA; 11100 else 11101 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 11102 } else if (auto MA = Args[i].Alignment) { 11103 MemAlign = *MA; 11104 } else { 11105 MemAlign = OriginalAlignment; 11106 } 11107 Flags.setMemAlign(MemAlign); 11108 if (Args[i].IsNest) 11109 Flags.setNest(); 11110 if (NeedsRegBlock) 11111 Flags.setInConsecutiveRegs(); 11112 11113 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11114 CLI.CallConv, VT); 11115 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11116 CLI.CallConv, VT); 11117 SmallVector<SDValue, 4> Parts(NumParts); 11118 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 11119 11120 if (Args[i].IsSExt) 11121 ExtendKind = ISD::SIGN_EXTEND; 11122 else if (Args[i].IsZExt) 11123 ExtendKind = ISD::ZERO_EXTEND; 11124 11125 // Conservatively only handle 'returned' on non-vectors that can be lowered, 11126 // for now. 11127 if (Args[i].IsReturned && !Op.getValueType().isVector() && 11128 CanLowerReturn) { 11129 assert((CLI.RetTy == Args[i].Ty || 11130 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 11131 CLI.RetTy->getPointerAddressSpace() == 11132 Args[i].Ty->getPointerAddressSpace())) && 11133 RetTys.size() == NumValues && "unexpected use of 'returned'"); 11134 // Before passing 'returned' to the target lowering code, ensure that 11135 // either the register MVT and the actual EVT are the same size or that 11136 // the return value and argument are extended in the same way; in these 11137 // cases it's safe to pass the argument register value unchanged as the 11138 // return register value (although it's at the target's option whether 11139 // to do so) 11140 // TODO: allow code generation to take advantage of partially preserved 11141 // registers rather than clobbering the entire register when the 11142 // parameter extension method is not compatible with the return 11143 // extension method 11144 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 11145 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 11146 CLI.RetZExt == Args[i].IsZExt)) 11147 Flags.setReturned(); 11148 } 11149 11150 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 11151 CLI.CallConv, ExtendKind); 11152 11153 for (unsigned j = 0; j != NumParts; ++j) { 11154 // if it isn't first piece, alignment must be 1 11155 // For scalable vectors the scalable part is currently handled 11156 // by individual targets, so we just use the known minimum size here. 11157 ISD::OutputArg MyFlags( 11158 Flags, Parts[j].getValueType().getSimpleVT(), VT, 11159 i < CLI.NumFixedArgs, i, 11160 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 11161 if (NumParts > 1 && j == 0) 11162 MyFlags.Flags.setSplit(); 11163 else if (j != 0) { 11164 MyFlags.Flags.setOrigAlign(Align(1)); 11165 if (j == NumParts - 1) 11166 MyFlags.Flags.setSplitEnd(); 11167 } 11168 11169 CLI.Outs.push_back(MyFlags); 11170 CLI.OutVals.push_back(Parts[j]); 11171 } 11172 11173 if (NeedsRegBlock && Value == NumValues - 1) 11174 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 11175 } 11176 } 11177 11178 SmallVector<SDValue, 4> InVals; 11179 CLI.Chain = LowerCall(CLI, InVals); 11180 11181 // Update CLI.InVals to use outside of this function. 11182 CLI.InVals = InVals; 11183 11184 // Verify that the target's LowerCall behaved as expected. 11185 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 11186 "LowerCall didn't return a valid chain!"); 11187 assert((!CLI.IsTailCall || InVals.empty()) && 11188 "LowerCall emitted a return value for a tail call!"); 11189 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 11190 "LowerCall didn't emit the correct number of values!"); 11191 11192 // For a tail call, the return value is merely live-out and there aren't 11193 // any nodes in the DAG representing it. Return a special value to 11194 // indicate that a tail call has been emitted and no more Instructions 11195 // should be processed in the current block. 11196 if (CLI.IsTailCall) { 11197 CLI.DAG.setRoot(CLI.Chain); 11198 return std::make_pair(SDValue(), SDValue()); 11199 } 11200 11201 #ifndef NDEBUG 11202 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 11203 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 11204 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 11205 "LowerCall emitted a value with the wrong type!"); 11206 } 11207 #endif 11208 11209 SmallVector<SDValue, 4> ReturnValues; 11210 if (!CanLowerReturn) { 11211 // The instruction result is the result of loading from the 11212 // hidden sret parameter. 11213 SmallVector<EVT, 1> PVTs; 11214 Type *PtrRetTy = 11215 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 11216 11217 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 11218 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 11219 EVT PtrVT = PVTs[0]; 11220 11221 unsigned NumValues = RetTys.size(); 11222 ReturnValues.resize(NumValues); 11223 SmallVector<SDValue, 4> Chains(NumValues); 11224 11225 // An aggregate return value cannot wrap around the address space, so 11226 // offsets to its parts don't wrap either. 11227 MachineFunction &MF = CLI.DAG.getMachineFunction(); 11228 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 11229 for (unsigned i = 0; i < NumValues; ++i) { 11230 SDValue Add = 11231 CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 11232 CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT), 11233 SDNodeFlags::NoUnsignedWrap); 11234 SDValue L = CLI.DAG.getLoad( 11235 RetTys[i], CLI.DL, CLI.Chain, Add, 11236 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 11237 DemoteStackIdx, Offsets[i]), 11238 HiddenSRetAlign); 11239 ReturnValues[i] = L; 11240 Chains[i] = L.getValue(1); 11241 } 11242 11243 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 11244 } else { 11245 // Collect the legal value parts into potentially illegal values 11246 // that correspond to the original function's return values. 11247 std::optional<ISD::NodeType> AssertOp; 11248 if (CLI.RetSExt) 11249 AssertOp = ISD::AssertSext; 11250 else if (CLI.RetZExt) 11251 AssertOp = ISD::AssertZext; 11252 unsigned CurReg = 0; 11253 for (EVT VT : RetTys) { 11254 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 11255 CLI.CallConv, VT); 11256 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 11257 CLI.CallConv, VT); 11258 11259 ReturnValues.push_back(getCopyFromParts( 11260 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 11261 CLI.Chain, CLI.CallConv, AssertOp)); 11262 CurReg += NumRegs; 11263 } 11264 11265 // For a function returning void, there is no return value. We can't create 11266 // such a node, so we just return a null return value in that case. In 11267 // that case, nothing will actually look at the value. 11268 if (ReturnValues.empty()) 11269 return std::make_pair(SDValue(), CLI.Chain); 11270 } 11271 11272 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 11273 CLI.DAG.getVTList(RetTys), ReturnValues); 11274 return std::make_pair(Res, CLI.Chain); 11275 } 11276 11277 /// Places new result values for the node in Results (their number 11278 /// and types must exactly match those of the original return values of 11279 /// the node), or leaves Results empty, which indicates that the node is not 11280 /// to be custom lowered after all. 11281 void TargetLowering::LowerOperationWrapper(SDNode *N, 11282 SmallVectorImpl<SDValue> &Results, 11283 SelectionDAG &DAG) const { 11284 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 11285 11286 if (!Res.getNode()) 11287 return; 11288 11289 // If the original node has one result, take the return value from 11290 // LowerOperation as is. It might not be result number 0. 11291 if (N->getNumValues() == 1) { 11292 Results.push_back(Res); 11293 return; 11294 } 11295 11296 // If the original node has multiple results, then the return node should 11297 // have the same number of results. 11298 assert((N->getNumValues() == Res->getNumValues()) && 11299 "Lowering returned the wrong number of results!"); 11300 11301 // Places new result values base on N result number. 11302 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11303 Results.push_back(Res.getValue(I)); 11304 } 11305 11306 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11307 llvm_unreachable("LowerOperation not implemented for this target!"); 11308 } 11309 11310 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11311 unsigned Reg, 11312 ISD::NodeType ExtendType) { 11313 SDValue Op = getNonRegisterValue(V); 11314 assert((Op.getOpcode() != ISD::CopyFromReg || 11315 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11316 "Copy from a reg to the same reg!"); 11317 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11318 11319 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11320 // If this is an InlineAsm we have to match the registers required, not the 11321 // notional registers required by the type. 11322 11323 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11324 std::nullopt); // This is not an ABI copy. 11325 SDValue Chain = DAG.getEntryNode(); 11326 11327 if (ExtendType == ISD::ANY_EXTEND) { 11328 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11329 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11330 ExtendType = PreferredExtendIt->second; 11331 } 11332 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11333 PendingExports.push_back(Chain); 11334 } 11335 11336 #include "llvm/CodeGen/SelectionDAGISel.h" 11337 11338 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11339 /// entry block, return true. This includes arguments used by switches, since 11340 /// the switch may expand into multiple basic blocks. 11341 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11342 // With FastISel active, we may be splitting blocks, so force creation 11343 // of virtual registers for all non-dead arguments. 11344 if (FastISel) 11345 return A->use_empty(); 11346 11347 const BasicBlock &Entry = A->getParent()->front(); 11348 for (const User *U : A->users()) 11349 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11350 return false; // Use not in entry block. 11351 11352 return true; 11353 } 11354 11355 using ArgCopyElisionMapTy = 11356 DenseMap<const Argument *, 11357 std::pair<const AllocaInst *, const StoreInst *>>; 11358 11359 /// Scan the entry block of the function in FuncInfo for arguments that look 11360 /// like copies into a local alloca. Record any copied arguments in 11361 /// ArgCopyElisionCandidates. 11362 static void 11363 findArgumentCopyElisionCandidates(const DataLayout &DL, 11364 FunctionLoweringInfo *FuncInfo, 11365 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11366 // Record the state of every static alloca used in the entry block. Argument 11367 // allocas are all used in the entry block, so we need approximately as many 11368 // entries as we have arguments. 11369 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11370 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11371 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11372 StaticAllocas.reserve(NumArgs * 2); 11373 11374 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11375 if (!V) 11376 return nullptr; 11377 V = V->stripPointerCasts(); 11378 const auto *AI = dyn_cast<AllocaInst>(V); 11379 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11380 return nullptr; 11381 auto Iter = StaticAllocas.insert({AI, Unknown}); 11382 return &Iter.first->second; 11383 }; 11384 11385 // Look for stores of arguments to static allocas. Look through bitcasts and 11386 // GEPs to handle type coercions, as long as the alloca is fully initialized 11387 // by the store. Any non-store use of an alloca escapes it and any subsequent 11388 // unanalyzed store might write it. 11389 // FIXME: Handle structs initialized with multiple stores. 11390 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11391 // Look for stores, and handle non-store uses conservatively. 11392 const auto *SI = dyn_cast<StoreInst>(&I); 11393 if (!SI) { 11394 // We will look through cast uses, so ignore them completely. 11395 if (I.isCast()) 11396 continue; 11397 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11398 // to allocas. 11399 if (I.isDebugOrPseudoInst()) 11400 continue; 11401 // This is an unknown instruction. Assume it escapes or writes to all 11402 // static alloca operands. 11403 for (const Use &U : I.operands()) { 11404 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11405 *Info = StaticAllocaInfo::Clobbered; 11406 } 11407 continue; 11408 } 11409 11410 // If the stored value is a static alloca, mark it as escaped. 11411 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11412 *Info = StaticAllocaInfo::Clobbered; 11413 11414 // Check if the destination is a static alloca. 11415 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11416 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11417 if (!Info) 11418 continue; 11419 const AllocaInst *AI = cast<AllocaInst>(Dst); 11420 11421 // Skip allocas that have been initialized or clobbered. 11422 if (*Info != StaticAllocaInfo::Unknown) 11423 continue; 11424 11425 // Check if the stored value is an argument, and that this store fully 11426 // initializes the alloca. 11427 // If the argument type has padding bits we can't directly forward a pointer 11428 // as the upper bits may contain garbage. 11429 // Don't elide copies from the same argument twice. 11430 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11431 const auto *Arg = dyn_cast<Argument>(Val); 11432 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11433 Arg->getType()->isEmptyTy() || 11434 DL.getTypeStoreSize(Arg->getType()) != 11435 DL.getTypeAllocSize(AI->getAllocatedType()) || 11436 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11437 ArgCopyElisionCandidates.count(Arg)) { 11438 *Info = StaticAllocaInfo::Clobbered; 11439 continue; 11440 } 11441 11442 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11443 << '\n'); 11444 11445 // Mark this alloca and store for argument copy elision. 11446 *Info = StaticAllocaInfo::Elidable; 11447 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11448 11449 // Stop scanning if we've seen all arguments. This will happen early in -O0 11450 // builds, which is useful, because -O0 builds have large entry blocks and 11451 // many allocas. 11452 if (ArgCopyElisionCandidates.size() == NumArgs) 11453 break; 11454 } 11455 } 11456 11457 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11458 /// ArgVal is a load from a suitable fixed stack object. 11459 static void tryToElideArgumentCopy( 11460 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11461 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11462 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11463 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11464 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11465 // Check if this is a load from a fixed stack object. 11466 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11467 if (!LNode) 11468 return; 11469 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11470 if (!FINode) 11471 return; 11472 11473 // Check that the fixed stack object is the right size and alignment. 11474 // Look at the alignment that the user wrote on the alloca instead of looking 11475 // at the stack object. 11476 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11477 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11478 const AllocaInst *AI = ArgCopyIter->second.first; 11479 int FixedIndex = FINode->getIndex(); 11480 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11481 int OldIndex = AllocaIndex; 11482 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11483 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11484 LLVM_DEBUG( 11485 dbgs() << " argument copy elision failed due to bad fixed stack " 11486 "object size\n"); 11487 return; 11488 } 11489 Align RequiredAlignment = AI->getAlign(); 11490 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11491 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11492 "greater than stack argument alignment (" 11493 << DebugStr(RequiredAlignment) << " vs " 11494 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11495 return; 11496 } 11497 11498 // Perform the elision. Delete the old stack object and replace its only use 11499 // in the variable info map. Mark the stack object as mutable and aliased. 11500 LLVM_DEBUG({ 11501 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11502 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11503 << '\n'; 11504 }); 11505 MFI.RemoveStackObject(OldIndex); 11506 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11507 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11508 AllocaIndex = FixedIndex; 11509 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11510 for (SDValue ArgVal : ArgVals) 11511 Chains.push_back(ArgVal.getValue(1)); 11512 11513 // Avoid emitting code for the store implementing the copy. 11514 const StoreInst *SI = ArgCopyIter->second.second; 11515 ElidedArgCopyInstrs.insert(SI); 11516 11517 // Check for uses of the argument again so that we can avoid exporting ArgVal 11518 // if it is't used by anything other than the store. 11519 for (const Value *U : Arg.users()) { 11520 if (U != SI) { 11521 ArgHasUses = true; 11522 break; 11523 } 11524 } 11525 } 11526 11527 void SelectionDAGISel::LowerArguments(const Function &F) { 11528 SelectionDAG &DAG = SDB->DAG; 11529 SDLoc dl = SDB->getCurSDLoc(); 11530 const DataLayout &DL = DAG.getDataLayout(); 11531 SmallVector<ISD::InputArg, 16> Ins; 11532 11533 // In Naked functions we aren't going to save any registers. 11534 if (F.hasFnAttribute(Attribute::Naked)) 11535 return; 11536 11537 if (!FuncInfo->CanLowerReturn) { 11538 // Put in an sret pointer parameter before all the other parameters. 11539 SmallVector<EVT, 1> ValueVTs; 11540 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11541 PointerType::get(F.getContext(), 11542 DAG.getDataLayout().getAllocaAddrSpace()), 11543 ValueVTs); 11544 11545 // NOTE: Assuming that a pointer will never break down to more than one VT 11546 // or one register. 11547 ISD::ArgFlagsTy Flags; 11548 Flags.setSRet(); 11549 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11550 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11551 ISD::InputArg::NoArgIndex, 0); 11552 Ins.push_back(RetArg); 11553 } 11554 11555 // Look for stores of arguments to static allocas. Mark such arguments with a 11556 // flag to ask the target to give us the memory location of that argument if 11557 // available. 11558 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11559 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11560 ArgCopyElisionCandidates); 11561 11562 // Set up the incoming argument description vector. 11563 for (const Argument &Arg : F.args()) { 11564 unsigned ArgNo = Arg.getArgNo(); 11565 SmallVector<EVT, 4> ValueVTs; 11566 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11567 bool isArgValueUsed = !Arg.use_empty(); 11568 unsigned PartBase = 0; 11569 Type *FinalType = Arg.getType(); 11570 if (Arg.hasAttribute(Attribute::ByVal)) 11571 FinalType = Arg.getParamByValType(); 11572 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11573 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11574 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11575 Value != NumValues; ++Value) { 11576 EVT VT = ValueVTs[Value]; 11577 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11578 ISD::ArgFlagsTy Flags; 11579 11580 11581 if (Arg.getType()->isPointerTy()) { 11582 Flags.setPointer(); 11583 Flags.setPointerAddrSpace( 11584 cast<PointerType>(Arg.getType())->getAddressSpace()); 11585 } 11586 if (Arg.hasAttribute(Attribute::ZExt)) 11587 Flags.setZExt(); 11588 if (Arg.hasAttribute(Attribute::SExt)) 11589 Flags.setSExt(); 11590 if (Arg.hasAttribute(Attribute::InReg)) { 11591 // If we are using vectorcall calling convention, a structure that is 11592 // passed InReg - is surely an HVA 11593 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11594 isa<StructType>(Arg.getType())) { 11595 // The first value of a structure is marked 11596 if (0 == Value) 11597 Flags.setHvaStart(); 11598 Flags.setHva(); 11599 } 11600 // Set InReg Flag 11601 Flags.setInReg(); 11602 } 11603 if (Arg.hasAttribute(Attribute::StructRet)) 11604 Flags.setSRet(); 11605 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11606 Flags.setSwiftSelf(); 11607 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11608 Flags.setSwiftAsync(); 11609 if (Arg.hasAttribute(Attribute::SwiftError)) 11610 Flags.setSwiftError(); 11611 if (Arg.hasAttribute(Attribute::ByVal)) 11612 Flags.setByVal(); 11613 if (Arg.hasAttribute(Attribute::ByRef)) 11614 Flags.setByRef(); 11615 if (Arg.hasAttribute(Attribute::InAlloca)) { 11616 Flags.setInAlloca(); 11617 // Set the byval flag for CCAssignFn callbacks that don't know about 11618 // inalloca. This way we can know how many bytes we should've allocated 11619 // and how many bytes a callee cleanup function will pop. If we port 11620 // inalloca to more targets, we'll have to add custom inalloca handling 11621 // in the various CC lowering callbacks. 11622 Flags.setByVal(); 11623 } 11624 if (Arg.hasAttribute(Attribute::Preallocated)) { 11625 Flags.setPreallocated(); 11626 // Set the byval flag for CCAssignFn callbacks that don't know about 11627 // preallocated. This way we can know how many bytes we should've 11628 // allocated and how many bytes a callee cleanup function will pop. If 11629 // we port preallocated to more targets, we'll have to add custom 11630 // preallocated handling in the various CC lowering callbacks. 11631 Flags.setByVal(); 11632 } 11633 11634 // Certain targets (such as MIPS), may have a different ABI alignment 11635 // for a type depending on the context. Give the target a chance to 11636 // specify the alignment it wants. 11637 const Align OriginalAlignment( 11638 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11639 Flags.setOrigAlign(OriginalAlignment); 11640 11641 Align MemAlign; 11642 Type *ArgMemTy = nullptr; 11643 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11644 Flags.isByRef()) { 11645 if (!ArgMemTy) 11646 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11647 11648 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11649 11650 // For in-memory arguments, size and alignment should be passed from FE. 11651 // BE will guess if this info is not there but there are cases it cannot 11652 // get right. 11653 if (auto ParamAlign = Arg.getParamStackAlign()) 11654 MemAlign = *ParamAlign; 11655 else if ((ParamAlign = Arg.getParamAlign())) 11656 MemAlign = *ParamAlign; 11657 else 11658 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11659 if (Flags.isByRef()) 11660 Flags.setByRefSize(MemSize); 11661 else 11662 Flags.setByValSize(MemSize); 11663 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11664 MemAlign = *ParamAlign; 11665 } else { 11666 MemAlign = OriginalAlignment; 11667 } 11668 Flags.setMemAlign(MemAlign); 11669 11670 if (Arg.hasAttribute(Attribute::Nest)) 11671 Flags.setNest(); 11672 if (NeedsRegBlock) 11673 Flags.setInConsecutiveRegs(); 11674 if (ArgCopyElisionCandidates.count(&Arg)) 11675 Flags.setCopyElisionCandidate(); 11676 if (Arg.hasAttribute(Attribute::Returned)) 11677 Flags.setReturned(); 11678 11679 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11680 *CurDAG->getContext(), F.getCallingConv(), VT); 11681 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11682 *CurDAG->getContext(), F.getCallingConv(), VT); 11683 for (unsigned i = 0; i != NumRegs; ++i) { 11684 // For scalable vectors, use the minimum size; individual targets 11685 // are responsible for handling scalable vector arguments and 11686 // return values. 11687 ISD::InputArg MyFlags( 11688 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11689 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11690 if (NumRegs > 1 && i == 0) 11691 MyFlags.Flags.setSplit(); 11692 // if it isn't first piece, alignment must be 1 11693 else if (i > 0) { 11694 MyFlags.Flags.setOrigAlign(Align(1)); 11695 if (i == NumRegs - 1) 11696 MyFlags.Flags.setSplitEnd(); 11697 } 11698 Ins.push_back(MyFlags); 11699 } 11700 if (NeedsRegBlock && Value == NumValues - 1) 11701 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11702 PartBase += VT.getStoreSize().getKnownMinValue(); 11703 } 11704 } 11705 11706 // Call the target to set up the argument values. 11707 SmallVector<SDValue, 8> InVals; 11708 SDValue NewRoot = TLI->LowerFormalArguments( 11709 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11710 11711 // Verify that the target's LowerFormalArguments behaved as expected. 11712 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11713 "LowerFormalArguments didn't return a valid chain!"); 11714 assert(InVals.size() == Ins.size() && 11715 "LowerFormalArguments didn't emit the correct number of values!"); 11716 LLVM_DEBUG({ 11717 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11718 assert(InVals[i].getNode() && 11719 "LowerFormalArguments emitted a null value!"); 11720 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11721 "LowerFormalArguments emitted a value with the wrong type!"); 11722 } 11723 }); 11724 11725 // Update the DAG with the new chain value resulting from argument lowering. 11726 DAG.setRoot(NewRoot); 11727 11728 // Set up the argument values. 11729 unsigned i = 0; 11730 if (!FuncInfo->CanLowerReturn) { 11731 // Create a virtual register for the sret pointer, and put in a copy 11732 // from the sret argument into it. 11733 SmallVector<EVT, 1> ValueVTs; 11734 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11735 PointerType::get(F.getContext(), 11736 DAG.getDataLayout().getAllocaAddrSpace()), 11737 ValueVTs); 11738 MVT VT = ValueVTs[0].getSimpleVT(); 11739 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11740 std::optional<ISD::NodeType> AssertOp; 11741 SDValue ArgValue = 11742 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11743 F.getCallingConv(), AssertOp); 11744 11745 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11746 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11747 Register SRetReg = 11748 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11749 FuncInfo->DemoteRegister = SRetReg; 11750 NewRoot = 11751 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11752 DAG.setRoot(NewRoot); 11753 11754 // i indexes lowered arguments. Bump it past the hidden sret argument. 11755 ++i; 11756 } 11757 11758 SmallVector<SDValue, 4> Chains; 11759 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11760 for (const Argument &Arg : F.args()) { 11761 SmallVector<SDValue, 4> ArgValues; 11762 SmallVector<EVT, 4> ValueVTs; 11763 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11764 unsigned NumValues = ValueVTs.size(); 11765 if (NumValues == 0) 11766 continue; 11767 11768 bool ArgHasUses = !Arg.use_empty(); 11769 11770 // Elide the copying store if the target loaded this argument from a 11771 // suitable fixed stack object. 11772 if (Ins[i].Flags.isCopyElisionCandidate()) { 11773 unsigned NumParts = 0; 11774 for (EVT VT : ValueVTs) 11775 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11776 F.getCallingConv(), VT); 11777 11778 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11779 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11780 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11781 } 11782 11783 // If this argument is unused then remember its value. It is used to generate 11784 // debugging information. 11785 bool isSwiftErrorArg = 11786 TLI->supportSwiftError() && 11787 Arg.hasAttribute(Attribute::SwiftError); 11788 if (!ArgHasUses && !isSwiftErrorArg) { 11789 SDB->setUnusedArgValue(&Arg, InVals[i]); 11790 11791 // Also remember any frame index for use in FastISel. 11792 if (FrameIndexSDNode *FI = 11793 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11794 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11795 } 11796 11797 for (unsigned Val = 0; Val != NumValues; ++Val) { 11798 EVT VT = ValueVTs[Val]; 11799 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11800 F.getCallingConv(), VT); 11801 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11802 *CurDAG->getContext(), F.getCallingConv(), VT); 11803 11804 // Even an apparent 'unused' swifterror argument needs to be returned. So 11805 // we do generate a copy for it that can be used on return from the 11806 // function. 11807 if (ArgHasUses || isSwiftErrorArg) { 11808 std::optional<ISD::NodeType> AssertOp; 11809 if (Arg.hasAttribute(Attribute::SExt)) 11810 AssertOp = ISD::AssertSext; 11811 else if (Arg.hasAttribute(Attribute::ZExt)) 11812 AssertOp = ISD::AssertZext; 11813 11814 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11815 PartVT, VT, nullptr, NewRoot, 11816 F.getCallingConv(), AssertOp)); 11817 } 11818 11819 i += NumParts; 11820 } 11821 11822 // We don't need to do anything else for unused arguments. 11823 if (ArgValues.empty()) 11824 continue; 11825 11826 // Note down frame index. 11827 if (FrameIndexSDNode *FI = 11828 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11829 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11830 11831 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11832 SDB->getCurSDLoc()); 11833 11834 SDB->setValue(&Arg, Res); 11835 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11836 // We want to associate the argument with the frame index, among 11837 // involved operands, that correspond to the lowest address. The 11838 // getCopyFromParts function, called earlier, is swapping the order of 11839 // the operands to BUILD_PAIR depending on endianness. The result of 11840 // that swapping is that the least significant bits of the argument will 11841 // be in the first operand of the BUILD_PAIR node, and the most 11842 // significant bits will be in the second operand. 11843 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11844 if (LoadSDNode *LNode = 11845 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11846 if (FrameIndexSDNode *FI = 11847 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11848 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11849 } 11850 11851 // Analyses past this point are naive and don't expect an assertion. 11852 if (Res.getOpcode() == ISD::AssertZext) 11853 Res = Res.getOperand(0); 11854 11855 // Update the SwiftErrorVRegDefMap. 11856 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11857 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11858 if (Reg.isVirtual()) 11859 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11860 Reg); 11861 } 11862 11863 // If this argument is live outside of the entry block, insert a copy from 11864 // wherever we got it to the vreg that other BB's will reference it as. 11865 if (Res.getOpcode() == ISD::CopyFromReg) { 11866 // If we can, though, try to skip creating an unnecessary vreg. 11867 // FIXME: This isn't very clean... it would be nice to make this more 11868 // general. 11869 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11870 if (Reg.isVirtual()) { 11871 FuncInfo->ValueMap[&Arg] = Reg; 11872 continue; 11873 } 11874 } 11875 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11876 FuncInfo->InitializeRegForValue(&Arg); 11877 SDB->CopyToExportRegsIfNeeded(&Arg); 11878 } 11879 } 11880 11881 if (!Chains.empty()) { 11882 Chains.push_back(NewRoot); 11883 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11884 } 11885 11886 DAG.setRoot(NewRoot); 11887 11888 assert(i == InVals.size() && "Argument register count mismatch!"); 11889 11890 // If any argument copy elisions occurred and we have debug info, update the 11891 // stale frame indices used in the dbg.declare variable info table. 11892 if (!ArgCopyElisionFrameIndexMap.empty()) { 11893 for (MachineFunction::VariableDbgInfo &VI : 11894 MF->getInStackSlotVariableDbgInfo()) { 11895 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11896 if (I != ArgCopyElisionFrameIndexMap.end()) 11897 VI.updateStackSlot(I->second); 11898 } 11899 } 11900 11901 // Finally, if the target has anything special to do, allow it to do so. 11902 emitFunctionEntryCode(); 11903 } 11904 11905 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11906 /// ensure constants are generated when needed. Remember the virtual registers 11907 /// that need to be added to the Machine PHI nodes as input. We cannot just 11908 /// directly add them, because expansion might result in multiple MBB's for one 11909 /// BB. As such, the start of the BB might correspond to a different MBB than 11910 /// the end. 11911 void 11912 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11914 11915 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11916 11917 // Check PHI nodes in successors that expect a value to be available from this 11918 // block. 11919 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11920 if (!isa<PHINode>(SuccBB->begin())) continue; 11921 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB); 11922 11923 // If this terminator has multiple identical successors (common for 11924 // switches), only handle each succ once. 11925 if (!SuccsHandled.insert(SuccMBB).second) 11926 continue; 11927 11928 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11929 11930 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11931 // nodes and Machine PHI nodes, but the incoming operands have not been 11932 // emitted yet. 11933 for (const PHINode &PN : SuccBB->phis()) { 11934 // Ignore dead phi's. 11935 if (PN.use_empty()) 11936 continue; 11937 11938 // Skip empty types 11939 if (PN.getType()->isEmptyTy()) 11940 continue; 11941 11942 unsigned Reg; 11943 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11944 11945 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11946 unsigned &RegOut = ConstantsOut[C]; 11947 if (RegOut == 0) { 11948 RegOut = FuncInfo.CreateRegs(C); 11949 // We need to zero/sign extend ConstantInt phi operands to match 11950 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11951 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11952 if (auto *CI = dyn_cast<ConstantInt>(C)) 11953 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11954 : ISD::ZERO_EXTEND; 11955 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11956 } 11957 Reg = RegOut; 11958 } else { 11959 DenseMap<const Value *, Register>::iterator I = 11960 FuncInfo.ValueMap.find(PHIOp); 11961 if (I != FuncInfo.ValueMap.end()) 11962 Reg = I->second; 11963 else { 11964 assert(isa<AllocaInst>(PHIOp) && 11965 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11966 "Didn't codegen value into a register!??"); 11967 Reg = FuncInfo.CreateRegs(PHIOp); 11968 CopyValueToVirtualRegister(PHIOp, Reg); 11969 } 11970 } 11971 11972 // Remember that this register needs to added to the machine PHI node as 11973 // the input for this MBB. 11974 SmallVector<EVT, 4> ValueVTs; 11975 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11976 for (EVT VT : ValueVTs) { 11977 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11978 for (unsigned i = 0; i != NumRegisters; ++i) 11979 FuncInfo.PHINodesToUpdate.push_back( 11980 std::make_pair(&*MBBI++, Reg + i)); 11981 Reg += NumRegisters; 11982 } 11983 } 11984 } 11985 11986 ConstantsOut.clear(); 11987 } 11988 11989 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11990 MachineFunction::iterator I(MBB); 11991 if (++I == FuncInfo.MF->end()) 11992 return nullptr; 11993 return &*I; 11994 } 11995 11996 /// During lowering new call nodes can be created (such as memset, etc.). 11997 /// Those will become new roots of the current DAG, but complications arise 11998 /// when they are tail calls. In such cases, the call lowering will update 11999 /// the root, but the builder still needs to know that a tail call has been 12000 /// lowered in order to avoid generating an additional return. 12001 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 12002 // If the node is null, we do have a tail call. 12003 if (MaybeTC.getNode() != nullptr) 12004 DAG.setRoot(MaybeTC); 12005 else 12006 HasTailCall = true; 12007 } 12008 12009 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 12010 MachineBasicBlock *SwitchMBB, 12011 MachineBasicBlock *DefaultMBB) { 12012 MachineFunction *CurMF = FuncInfo.MF; 12013 MachineBasicBlock *NextMBB = nullptr; 12014 MachineFunction::iterator BBI(W.MBB); 12015 if (++BBI != FuncInfo.MF->end()) 12016 NextMBB = &*BBI; 12017 12018 unsigned Size = W.LastCluster - W.FirstCluster + 1; 12019 12020 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12021 12022 if (Size == 2 && W.MBB == SwitchMBB) { 12023 // If any two of the cases has the same destination, and if one value 12024 // is the same as the other, but has one bit unset that the other has set, 12025 // use bit manipulation to do two compares at once. For example: 12026 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 12027 // TODO: This could be extended to merge any 2 cases in switches with 3 12028 // cases. 12029 // TODO: Handle cases where W.CaseBB != SwitchBB. 12030 CaseCluster &Small = *W.FirstCluster; 12031 CaseCluster &Big = *W.LastCluster; 12032 12033 if (Small.Low == Small.High && Big.Low == Big.High && 12034 Small.MBB == Big.MBB) { 12035 const APInt &SmallValue = Small.Low->getValue(); 12036 const APInt &BigValue = Big.Low->getValue(); 12037 12038 // Check that there is only one bit different. 12039 APInt CommonBit = BigValue ^ SmallValue; 12040 if (CommonBit.isPowerOf2()) { 12041 SDValue CondLHS = getValue(Cond); 12042 EVT VT = CondLHS.getValueType(); 12043 SDLoc DL = getCurSDLoc(); 12044 12045 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 12046 DAG.getConstant(CommonBit, DL, VT)); 12047 SDValue Cond = DAG.getSetCC( 12048 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 12049 ISD::SETEQ); 12050 12051 // Update successor info. 12052 // Both Small and Big will jump to Small.BB, so we sum up the 12053 // probabilities. 12054 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 12055 if (BPI) 12056 addSuccessorWithProb( 12057 SwitchMBB, DefaultMBB, 12058 // The default destination is the first successor in IR. 12059 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 12060 else 12061 addSuccessorWithProb(SwitchMBB, DefaultMBB); 12062 12063 // Insert the true branch. 12064 SDValue BrCond = 12065 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 12066 DAG.getBasicBlock(Small.MBB)); 12067 // Insert the false branch. 12068 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 12069 DAG.getBasicBlock(DefaultMBB)); 12070 12071 DAG.setRoot(BrCond); 12072 return; 12073 } 12074 } 12075 } 12076 12077 if (TM.getOptLevel() != CodeGenOptLevel::None) { 12078 // Here, we order cases by probability so the most likely case will be 12079 // checked first. However, two clusters can have the same probability in 12080 // which case their relative ordering is non-deterministic. So we use Low 12081 // as a tie-breaker as clusters are guaranteed to never overlap. 12082 llvm::sort(W.FirstCluster, W.LastCluster + 1, 12083 [](const CaseCluster &a, const CaseCluster &b) { 12084 return a.Prob != b.Prob ? 12085 a.Prob > b.Prob : 12086 a.Low->getValue().slt(b.Low->getValue()); 12087 }); 12088 12089 // Rearrange the case blocks so that the last one falls through if possible 12090 // without changing the order of probabilities. 12091 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 12092 --I; 12093 if (I->Prob > W.LastCluster->Prob) 12094 break; 12095 if (I->Kind == CC_Range && I->MBB == NextMBB) { 12096 std::swap(*I, *W.LastCluster); 12097 break; 12098 } 12099 } 12100 } 12101 12102 // Compute total probability. 12103 BranchProbability DefaultProb = W.DefaultProb; 12104 BranchProbability UnhandledProbs = DefaultProb; 12105 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 12106 UnhandledProbs += I->Prob; 12107 12108 MachineBasicBlock *CurMBB = W.MBB; 12109 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 12110 bool FallthroughUnreachable = false; 12111 MachineBasicBlock *Fallthrough; 12112 if (I == W.LastCluster) { 12113 // For the last cluster, fall through to the default destination. 12114 Fallthrough = DefaultMBB; 12115 FallthroughUnreachable = isa<UnreachableInst>( 12116 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 12117 } else { 12118 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 12119 CurMF->insert(BBI, Fallthrough); 12120 // Put Cond in a virtual register to make it available from the new blocks. 12121 ExportFromCurrentBlock(Cond); 12122 } 12123 UnhandledProbs -= I->Prob; 12124 12125 switch (I->Kind) { 12126 case CC_JumpTable: { 12127 // FIXME: Optimize away range check based on pivot comparisons. 12128 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 12129 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 12130 12131 // The jump block hasn't been inserted yet; insert it here. 12132 MachineBasicBlock *JumpMBB = JT->MBB; 12133 CurMF->insert(BBI, JumpMBB); 12134 12135 auto JumpProb = I->Prob; 12136 auto FallthroughProb = UnhandledProbs; 12137 12138 // If the default statement is a target of the jump table, we evenly 12139 // distribute the default probability to successors of CurMBB. Also 12140 // update the probability on the edge from JumpMBB to Fallthrough. 12141 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 12142 SE = JumpMBB->succ_end(); 12143 SI != SE; ++SI) { 12144 if (*SI == DefaultMBB) { 12145 JumpProb += DefaultProb / 2; 12146 FallthroughProb -= DefaultProb / 2; 12147 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 12148 JumpMBB->normalizeSuccProbs(); 12149 break; 12150 } 12151 } 12152 12153 // If the default clause is unreachable, propagate that knowledge into 12154 // JTH->FallthroughUnreachable which will use it to suppress the range 12155 // check. 12156 // 12157 // However, don't do this if we're doing branch target enforcement, 12158 // because a table branch _without_ a range check can be a tempting JOP 12159 // gadget - out-of-bounds inputs that are impossible in correct 12160 // execution become possible again if an attacker can influence the 12161 // control flow. So if an attacker doesn't already have a BTI bypass 12162 // available, we don't want them to be able to get one out of this 12163 // table branch. 12164 if (FallthroughUnreachable) { 12165 Function &CurFunc = CurMF->getFunction(); 12166 if (!CurFunc.hasFnAttribute("branch-target-enforcement")) 12167 JTH->FallthroughUnreachable = true; 12168 } 12169 12170 if (!JTH->FallthroughUnreachable) 12171 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 12172 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 12173 CurMBB->normalizeSuccProbs(); 12174 12175 // The jump table header will be inserted in our current block, do the 12176 // range check, and fall through to our fallthrough block. 12177 JTH->HeaderBB = CurMBB; 12178 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 12179 12180 // If we're in the right place, emit the jump table header right now. 12181 if (CurMBB == SwitchMBB) { 12182 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 12183 JTH->Emitted = true; 12184 } 12185 break; 12186 } 12187 case CC_BitTests: { 12188 // FIXME: Optimize away range check based on pivot comparisons. 12189 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 12190 12191 // The bit test blocks haven't been inserted yet; insert them here. 12192 for (BitTestCase &BTC : BTB->Cases) 12193 CurMF->insert(BBI, BTC.ThisBB); 12194 12195 // Fill in fields of the BitTestBlock. 12196 BTB->Parent = CurMBB; 12197 BTB->Default = Fallthrough; 12198 12199 BTB->DefaultProb = UnhandledProbs; 12200 // If the cases in bit test don't form a contiguous range, we evenly 12201 // distribute the probability on the edge to Fallthrough to two 12202 // successors of CurMBB. 12203 if (!BTB->ContiguousRange) { 12204 BTB->Prob += DefaultProb / 2; 12205 BTB->DefaultProb -= DefaultProb / 2; 12206 } 12207 12208 if (FallthroughUnreachable) 12209 BTB->FallthroughUnreachable = true; 12210 12211 // If we're in the right place, emit the bit test header right now. 12212 if (CurMBB == SwitchMBB) { 12213 visitBitTestHeader(*BTB, SwitchMBB); 12214 BTB->Emitted = true; 12215 } 12216 break; 12217 } 12218 case CC_Range: { 12219 const Value *RHS, *LHS, *MHS; 12220 ISD::CondCode CC; 12221 if (I->Low == I->High) { 12222 // Check Cond == I->Low. 12223 CC = ISD::SETEQ; 12224 LHS = Cond; 12225 RHS=I->Low; 12226 MHS = nullptr; 12227 } else { 12228 // Check I->Low <= Cond <= I->High. 12229 CC = ISD::SETLE; 12230 LHS = I->Low; 12231 MHS = Cond; 12232 RHS = I->High; 12233 } 12234 12235 // If Fallthrough is unreachable, fold away the comparison. 12236 if (FallthroughUnreachable) 12237 CC = ISD::SETTRUE; 12238 12239 // The false probability is the sum of all unhandled cases. 12240 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 12241 getCurSDLoc(), I->Prob, UnhandledProbs); 12242 12243 if (CurMBB == SwitchMBB) 12244 visitSwitchCase(CB, SwitchMBB); 12245 else 12246 SL->SwitchCases.push_back(CB); 12247 12248 break; 12249 } 12250 } 12251 CurMBB = Fallthrough; 12252 } 12253 } 12254 12255 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 12256 const SwitchWorkListItem &W, 12257 Value *Cond, 12258 MachineBasicBlock *SwitchMBB) { 12259 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 12260 "Clusters not sorted?"); 12261 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 12262 12263 auto [LastLeft, FirstRight, LeftProb, RightProb] = 12264 SL->computeSplitWorkItemInfo(W); 12265 12266 // Use the first element on the right as pivot since we will make less-than 12267 // comparisons against it. 12268 CaseClusterIt PivotCluster = FirstRight; 12269 assert(PivotCluster > W.FirstCluster); 12270 assert(PivotCluster <= W.LastCluster); 12271 12272 CaseClusterIt FirstLeft = W.FirstCluster; 12273 CaseClusterIt LastRight = W.LastCluster; 12274 12275 const ConstantInt *Pivot = PivotCluster->Low; 12276 12277 // New blocks will be inserted immediately after the current one. 12278 MachineFunction::iterator BBI(W.MBB); 12279 ++BBI; 12280 12281 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 12282 // we can branch to its destination directly if it's squeezed exactly in 12283 // between the known lower bound and Pivot - 1. 12284 MachineBasicBlock *LeftMBB; 12285 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 12286 FirstLeft->Low == W.GE && 12287 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12288 LeftMBB = FirstLeft->MBB; 12289 } else { 12290 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12291 FuncInfo.MF->insert(BBI, LeftMBB); 12292 WorkList.push_back( 12293 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12294 // Put Cond in a virtual register to make it available from the new blocks. 12295 ExportFromCurrentBlock(Cond); 12296 } 12297 12298 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12299 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12300 // directly if RHS.High equals the current upper bound. 12301 MachineBasicBlock *RightMBB; 12302 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12303 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12304 RightMBB = FirstRight->MBB; 12305 } else { 12306 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12307 FuncInfo.MF->insert(BBI, RightMBB); 12308 WorkList.push_back( 12309 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12310 // Put Cond in a virtual register to make it available from the new blocks. 12311 ExportFromCurrentBlock(Cond); 12312 } 12313 12314 // Create the CaseBlock record that will be used to lower the branch. 12315 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12316 getCurSDLoc(), LeftProb, RightProb); 12317 12318 if (W.MBB == SwitchMBB) 12319 visitSwitchCase(CB, SwitchMBB); 12320 else 12321 SL->SwitchCases.push_back(CB); 12322 } 12323 12324 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12325 // from the swith statement. 12326 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12327 BranchProbability PeeledCaseProb) { 12328 if (PeeledCaseProb == BranchProbability::getOne()) 12329 return BranchProbability::getZero(); 12330 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12331 12332 uint32_t Numerator = CaseProb.getNumerator(); 12333 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12334 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12335 } 12336 12337 // Try to peel the top probability case if it exceeds the threshold. 12338 // Return current MachineBasicBlock for the switch statement if the peeling 12339 // does not occur. 12340 // If the peeling is performed, return the newly created MachineBasicBlock 12341 // for the peeled switch statement. Also update Clusters to remove the peeled 12342 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12343 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12344 const SwitchInst &SI, CaseClusterVector &Clusters, 12345 BranchProbability &PeeledCaseProb) { 12346 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12347 // Don't perform if there is only one cluster or optimizing for size. 12348 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12349 TM.getOptLevel() == CodeGenOptLevel::None || 12350 SwitchMBB->getParent()->getFunction().hasMinSize()) 12351 return SwitchMBB; 12352 12353 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12354 unsigned PeeledCaseIndex = 0; 12355 bool SwitchPeeled = false; 12356 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12357 CaseCluster &CC = Clusters[Index]; 12358 if (CC.Prob < TopCaseProb) 12359 continue; 12360 TopCaseProb = CC.Prob; 12361 PeeledCaseIndex = Index; 12362 SwitchPeeled = true; 12363 } 12364 if (!SwitchPeeled) 12365 return SwitchMBB; 12366 12367 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12368 << TopCaseProb << "\n"); 12369 12370 // Record the MBB for the peeled switch statement. 12371 MachineFunction::iterator BBI(SwitchMBB); 12372 ++BBI; 12373 MachineBasicBlock *PeeledSwitchMBB = 12374 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12375 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12376 12377 ExportFromCurrentBlock(SI.getCondition()); 12378 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12379 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12380 nullptr, nullptr, TopCaseProb.getCompl()}; 12381 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12382 12383 Clusters.erase(PeeledCaseIt); 12384 for (CaseCluster &CC : Clusters) { 12385 LLVM_DEBUG( 12386 dbgs() << "Scale the probablity for one cluster, before scaling: " 12387 << CC.Prob << "\n"); 12388 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12389 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12390 } 12391 PeeledCaseProb = TopCaseProb; 12392 return PeeledSwitchMBB; 12393 } 12394 12395 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12396 // Extract cases from the switch. 12397 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12398 CaseClusterVector Clusters; 12399 Clusters.reserve(SI.getNumCases()); 12400 for (auto I : SI.cases()) { 12401 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor()); 12402 const ConstantInt *CaseVal = I.getCaseValue(); 12403 BranchProbability Prob = 12404 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12405 : BranchProbability(1, SI.getNumCases() + 1); 12406 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12407 } 12408 12409 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest()); 12410 12411 // Cluster adjacent cases with the same destination. We do this at all 12412 // optimization levels because it's cheap to do and will make codegen faster 12413 // if there are many clusters. 12414 sortAndRangeify(Clusters); 12415 12416 // The branch probablity of the peeled case. 12417 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12418 MachineBasicBlock *PeeledSwitchMBB = 12419 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12420 12421 // If there is only the default destination, jump there directly. 12422 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12423 if (Clusters.empty()) { 12424 assert(PeeledSwitchMBB == SwitchMBB); 12425 SwitchMBB->addSuccessor(DefaultMBB); 12426 if (DefaultMBB != NextBlock(SwitchMBB)) { 12427 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12428 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12429 } 12430 return; 12431 } 12432 12433 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12434 DAG.getBFI()); 12435 SL->findBitTestClusters(Clusters, &SI); 12436 12437 LLVM_DEBUG({ 12438 dbgs() << "Case clusters: "; 12439 for (const CaseCluster &C : Clusters) { 12440 if (C.Kind == CC_JumpTable) 12441 dbgs() << "JT:"; 12442 if (C.Kind == CC_BitTests) 12443 dbgs() << "BT:"; 12444 12445 C.Low->getValue().print(dbgs(), true); 12446 if (C.Low != C.High) { 12447 dbgs() << '-'; 12448 C.High->getValue().print(dbgs(), true); 12449 } 12450 dbgs() << ' '; 12451 } 12452 dbgs() << '\n'; 12453 }); 12454 12455 assert(!Clusters.empty()); 12456 SwitchWorkList WorkList; 12457 CaseClusterIt First = Clusters.begin(); 12458 CaseClusterIt Last = Clusters.end() - 1; 12459 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12460 // Scale the branchprobability for DefaultMBB if the peel occurs and 12461 // DefaultMBB is not replaced. 12462 if (PeeledCaseProb != BranchProbability::getZero() && 12463 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest())) 12464 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12465 WorkList.push_back( 12466 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12467 12468 while (!WorkList.empty()) { 12469 SwitchWorkListItem W = WorkList.pop_back_val(); 12470 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12471 12472 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12473 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12474 // For optimized builds, lower large range as a balanced binary tree. 12475 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12476 continue; 12477 } 12478 12479 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12480 } 12481 } 12482 12483 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12484 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12485 auto DL = getCurSDLoc(); 12486 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12487 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12488 } 12489 12490 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12491 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12492 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12493 12494 SDLoc DL = getCurSDLoc(); 12495 SDValue V = getValue(I.getOperand(0)); 12496 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12497 12498 if (VT.isScalableVector()) { 12499 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12500 return; 12501 } 12502 12503 // Use VECTOR_SHUFFLE for the fixed-length vector 12504 // to maintain existing behavior. 12505 SmallVector<int, 8> Mask; 12506 unsigned NumElts = VT.getVectorMinNumElements(); 12507 for (unsigned i = 0; i != NumElts; ++i) 12508 Mask.push_back(NumElts - 1 - i); 12509 12510 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12511 } 12512 12513 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12514 auto DL = getCurSDLoc(); 12515 SDValue InVec = getValue(I.getOperand(0)); 12516 EVT OutVT = 12517 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12518 12519 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12520 12521 // ISD Node needs the input vectors split into two equal parts 12522 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12523 DAG.getVectorIdxConstant(0, DL)); 12524 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12525 DAG.getVectorIdxConstant(OutNumElts, DL)); 12526 12527 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12528 // legalisation and combines. 12529 if (OutVT.isFixedLengthVector()) { 12530 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12531 createStrideMask(0, 2, OutNumElts)); 12532 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12533 createStrideMask(1, 2, OutNumElts)); 12534 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12535 setValue(&I, Res); 12536 return; 12537 } 12538 12539 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12540 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12541 setValue(&I, Res); 12542 } 12543 12544 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12545 auto DL = getCurSDLoc(); 12546 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12547 SDValue InVec0 = getValue(I.getOperand(0)); 12548 SDValue InVec1 = getValue(I.getOperand(1)); 12549 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12550 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12551 12552 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12553 // legalisation and combines. 12554 if (OutVT.isFixedLengthVector()) { 12555 unsigned NumElts = InVT.getVectorMinNumElements(); 12556 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12557 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12558 createInterleaveMask(NumElts, 2))); 12559 return; 12560 } 12561 12562 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12563 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12564 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12565 Res.getValue(1)); 12566 setValue(&I, Res); 12567 } 12568 12569 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12570 SmallVector<EVT, 4> ValueVTs; 12571 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12572 ValueVTs); 12573 unsigned NumValues = ValueVTs.size(); 12574 if (NumValues == 0) return; 12575 12576 SmallVector<SDValue, 4> Values(NumValues); 12577 SDValue Op = getValue(I.getOperand(0)); 12578 12579 for (unsigned i = 0; i != NumValues; ++i) 12580 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12581 SDValue(Op.getNode(), Op.getResNo() + i)); 12582 12583 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12584 DAG.getVTList(ValueVTs), Values)); 12585 } 12586 12587 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12589 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12590 12591 SDLoc DL = getCurSDLoc(); 12592 SDValue V1 = getValue(I.getOperand(0)); 12593 SDValue V2 = getValue(I.getOperand(1)); 12594 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12595 12596 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12597 if (VT.isScalableVector()) { 12598 setValue( 12599 &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12600 DAG.getSignedConstant( 12601 Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 12602 return; 12603 } 12604 12605 unsigned NumElts = VT.getVectorNumElements(); 12606 12607 uint64_t Idx = (NumElts + Imm) % NumElts; 12608 12609 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12610 SmallVector<int, 8> Mask; 12611 for (unsigned i = 0; i < NumElts; ++i) 12612 Mask.push_back(Idx + i); 12613 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12614 } 12615 12616 // Consider the following MIR after SelectionDAG, which produces output in 12617 // phyregs in the first case or virtregs in the second case. 12618 // 12619 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12620 // %5:gr32 = COPY $ebx 12621 // %6:gr32 = COPY $edx 12622 // %1:gr32 = COPY %6:gr32 12623 // %0:gr32 = COPY %5:gr32 12624 // 12625 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12626 // %1:gr32 = COPY %6:gr32 12627 // %0:gr32 = COPY %5:gr32 12628 // 12629 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12630 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12631 // 12632 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12633 // to a single virtreg (such as %0). The remaining outputs monotonically 12634 // increase in virtreg number from there. If a callbr has no outputs, then it 12635 // should not have a corresponding callbr landingpad; in fact, the callbr 12636 // landingpad would not even be able to refer to such a callbr. 12637 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12638 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12639 // There is definitely at least one copy. 12640 assert(MI->getOpcode() == TargetOpcode::COPY && 12641 "start of copy chain MUST be COPY"); 12642 Reg = MI->getOperand(1).getReg(); 12643 MI = MRI.def_begin(Reg)->getParent(); 12644 // There may be an optional second copy. 12645 if (MI->getOpcode() == TargetOpcode::COPY) { 12646 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12647 Reg = MI->getOperand(1).getReg(); 12648 assert(Reg.isPhysical() && "expected COPY of physical register"); 12649 MI = MRI.def_begin(Reg)->getParent(); 12650 } 12651 // The start of the chain must be an INLINEASM_BR. 12652 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12653 "end of copy chain MUST be INLINEASM_BR"); 12654 return Reg; 12655 } 12656 12657 // We must do this walk rather than the simpler 12658 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12659 // otherwise we will end up with copies of virtregs only valid along direct 12660 // edges. 12661 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12662 SmallVector<EVT, 8> ResultVTs; 12663 SmallVector<SDValue, 8> ResultValues; 12664 const auto *CBR = 12665 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12666 12667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12668 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12669 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12670 12671 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12672 SDValue Chain = DAG.getRoot(); 12673 12674 // Re-parse the asm constraints string. 12675 TargetLowering::AsmOperandInfoVector TargetConstraints = 12676 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12677 for (auto &T : TargetConstraints) { 12678 SDISelAsmOperandInfo OpInfo(T); 12679 if (OpInfo.Type != InlineAsm::isOutput) 12680 continue; 12681 12682 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12683 // individual constraint. 12684 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12685 12686 switch (OpInfo.ConstraintType) { 12687 case TargetLowering::C_Register: 12688 case TargetLowering::C_RegisterClass: { 12689 // Fill in OpInfo.AssignedRegs.Regs. 12690 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12691 12692 // getRegistersForValue may produce 1 to many registers based on whether 12693 // the OpInfo.ConstraintVT is legal on the target or not. 12694 for (Register &Reg : OpInfo.AssignedRegs.Regs) { 12695 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12696 if (Register::isPhysicalRegister(OriginalDef)) 12697 FuncInfo.MBB->addLiveIn(OriginalDef); 12698 // Update the assigned registers to use the original defs. 12699 Reg = OriginalDef; 12700 } 12701 12702 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12703 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12704 ResultValues.push_back(V); 12705 ResultVTs.push_back(OpInfo.ConstraintVT); 12706 break; 12707 } 12708 case TargetLowering::C_Other: { 12709 SDValue Flag; 12710 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12711 OpInfo, DAG); 12712 ++InitialDef; 12713 ResultValues.push_back(V); 12714 ResultVTs.push_back(OpInfo.ConstraintVT); 12715 break; 12716 } 12717 default: 12718 break; 12719 } 12720 } 12721 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12722 DAG.getVTList(ResultVTs), ResultValues); 12723 setValue(&I, V); 12724 } 12725