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/RuntimeLibcalls.h" 48 #include "llvm/CodeGen/SelectionDAG.h" 49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 50 #include "llvm/CodeGen/StackMaps.h" 51 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 52 #include "llvm/CodeGen/TargetFrameLowering.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetOpcodes.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/TargetSubtargetInfo.h" 57 #include "llvm/CodeGen/WinEHFuncInfo.h" 58 #include "llvm/IR/Argument.h" 59 #include "llvm/IR/Attributes.h" 60 #include "llvm/IR/BasicBlock.h" 61 #include "llvm/IR/CFG.h" 62 #include "llvm/IR/CallingConv.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/ConstantRange.h" 65 #include "llvm/IR/Constants.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DebugInfo.h" 68 #include "llvm/IR/DebugInfoMetadata.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/DiagnosticInfo.h" 71 #include "llvm/IR/EHPersonalities.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsAMDGPU.h" 81 #include "llvm/IR/IntrinsicsWebAssembly.h" 82 #include "llvm/IR/LLVMContext.h" 83 #include "llvm/IR/MemoryModelRelaxationAnnotations.h" 84 #include "llvm/IR/Metadata.h" 85 #include "llvm/IR/Module.h" 86 #include "llvm/IR/Operator.h" 87 #include "llvm/IR/PatternMatch.h" 88 #include "llvm/IR/Statepoint.h" 89 #include "llvm/IR/Type.h" 90 #include "llvm/IR/User.h" 91 #include "llvm/IR/Value.h" 92 #include "llvm/MC/MCContext.h" 93 #include "llvm/Support/AtomicOrdering.h" 94 #include "llvm/Support/Casting.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/InstructionCost.h" 99 #include "llvm/Support/MathExtras.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include "llvm/Target/TargetIntrinsicInfo.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include "llvm/TargetParser/Triple.h" 105 #include "llvm/Transforms/Utils/Local.h" 106 #include <cstddef> 107 #include <iterator> 108 #include <limits> 109 #include <optional> 110 #include <tuple> 111 112 using namespace llvm; 113 using namespace PatternMatch; 114 using namespace SwitchCG; 115 116 #define DEBUG_TYPE "isel" 117 118 /// LimitFloatPrecision - Generate low-precision inline sequences for 119 /// some float libcalls (6, 8 or 12 bits). 120 static unsigned LimitFloatPrecision; 121 122 static cl::opt<bool> 123 InsertAssertAlign("insert-assert-align", cl::init(true), 124 cl::desc("Insert the experimental `assertalign` node."), 125 cl::ReallyHidden); 126 127 static cl::opt<unsigned, true> 128 LimitFPPrecision("limit-float-precision", 129 cl::desc("Generate low-precision inline sequences " 130 "for some float libcalls"), 131 cl::location(LimitFloatPrecision), cl::Hidden, 132 cl::init(0)); 133 134 static cl::opt<unsigned> SwitchPeelThreshold( 135 "switch-peel-threshold", cl::Hidden, cl::init(66), 136 cl::desc("Set the case probability threshold for peeling the case from a " 137 "switch statement. A value greater than 100 will void this " 138 "optimization")); 139 140 // Limit the width of DAG chains. This is important in general to prevent 141 // DAG-based analysis from blowing up. For example, alias analysis and 142 // load clustering may not complete in reasonable time. It is difficult to 143 // recognize and avoid this situation within each individual analysis, and 144 // future analyses are likely to have the same behavior. Limiting DAG width is 145 // the safe approach and will be especially important with global DAGs. 146 // 147 // MaxParallelChains default is arbitrarily high to avoid affecting 148 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 149 // sequence over this should have been converted to llvm.memcpy by the 150 // frontend. It is easy to induce this behavior with .ll code such as: 151 // %buffer = alloca [4096 x i8] 152 // %data = load [4096 x i8]* %argPtr 153 // store [4096 x i8] %data, [4096 x i8]* %buffer 154 static const unsigned MaxParallelChains = 64; 155 156 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 157 const SDValue *Parts, unsigned NumParts, 158 MVT PartVT, EVT ValueVT, const Value *V, 159 SDValue InChain, 160 std::optional<CallingConv::ID> CC); 161 162 /// getCopyFromParts - Create a value that contains the specified legal parts 163 /// combined into the value they represent. If the parts combine to a type 164 /// larger than ValueVT then AssertOp can be used to specify whether the extra 165 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 166 /// (ISD::AssertSext). 167 static SDValue 168 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 169 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 170 SDValue InChain, 171 std::optional<CallingConv::ID> CC = std::nullopt, 172 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 173 // Let the target assemble the parts if it wants to 174 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 175 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 176 PartVT, ValueVT, CC)) 177 return Val; 178 179 if (ValueVT.isVector()) 180 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 181 InChain, CC); 182 183 assert(NumParts > 0 && "No parts to assemble!"); 184 SDValue Val = Parts[0]; 185 186 if (NumParts > 1) { 187 // Assemble the value from multiple parts. 188 if (ValueVT.isInteger()) { 189 unsigned PartBits = PartVT.getSizeInBits(); 190 unsigned ValueBits = ValueVT.getSizeInBits(); 191 192 // Assemble the power of 2 part. 193 unsigned RoundParts = llvm::bit_floor(NumParts); 194 unsigned RoundBits = PartBits * RoundParts; 195 EVT RoundVT = RoundBits == ValueBits ? 196 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 197 SDValue Lo, Hi; 198 199 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 200 201 if (RoundParts > 2) { 202 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 203 InChain); 204 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 205 PartVT, HalfVT, V, InChain); 206 } else { 207 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 208 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 209 } 210 211 if (DAG.getDataLayout().isBigEndian()) 212 std::swap(Lo, Hi); 213 214 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 215 216 if (RoundParts < NumParts) { 217 // Assemble the trailing non-power-of-2 part. 218 unsigned OddParts = NumParts - RoundParts; 219 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 220 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 221 OddVT, V, InChain, CC); 222 223 // Combine the round and odd parts. 224 Lo = Val; 225 if (DAG.getDataLayout().isBigEndian()) 226 std::swap(Lo, Hi); 227 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 228 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 229 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 230 DAG.getConstant(Lo.getValueSizeInBits(), DL, 231 TLI.getShiftAmountTy( 232 TotalVT, DAG.getDataLayout()))); 233 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 234 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 235 } 236 } else if (PartVT.isFloatingPoint()) { 237 // FP split into multiple FP parts (for ppcf128) 238 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 239 "Unexpected split"); 240 SDValue Lo, Hi; 241 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 242 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 243 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 244 std::swap(Lo, Hi); 245 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 246 } else { 247 // FP split into integer parts (soft fp) 248 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 249 !PartVT.isVector() && "Unexpected split"); 250 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 251 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 252 InChain, CC); 253 } 254 } 255 256 // There is now one part, held in Val. Correct it to match ValueVT. 257 // PartEVT is the type of the register class that holds the value. 258 // ValueVT is the type of the inline asm operation. 259 EVT PartEVT = Val.getValueType(); 260 261 if (PartEVT == ValueVT) 262 return Val; 263 264 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 265 ValueVT.bitsLT(PartEVT)) { 266 // For an FP value in an integer part, we need to truncate to the right 267 // width first. 268 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 269 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 270 } 271 272 // Handle types that have the same size. 273 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 274 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 275 276 // Handle types with different sizes. 277 if (PartEVT.isInteger() && ValueVT.isInteger()) { 278 if (ValueVT.bitsLT(PartEVT)) { 279 // For a truncate, see if we have any information to 280 // indicate whether the truncated bits will always be 281 // zero or sign-extension. 282 if (AssertOp) 283 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 284 DAG.getValueType(ValueVT)); 285 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 286 } 287 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 288 } 289 290 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 291 // FP_ROUND's are always exact here. 292 if (ValueVT.bitsLT(Val.getValueType())) { 293 294 SDValue NoChange = 295 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 296 297 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 298 llvm::Attribute::StrictFP)) { 299 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 300 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 301 NoChange); 302 } 303 304 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 305 } 306 307 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 308 } 309 310 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 311 // then truncating. 312 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 313 ValueVT.bitsLT(PartEVT)) { 314 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 315 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 316 } 317 318 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 319 } 320 321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 322 const Twine &ErrMsg) { 323 const Instruction *I = dyn_cast_or_null<Instruction>(V); 324 if (!V) 325 return Ctx.emitError(ErrMsg); 326 327 const char *AsmError = ", possible invalid constraint for vector type"; 328 if (const CallInst *CI = dyn_cast<CallInst>(I)) 329 if (CI->isInlineAsm()) 330 return Ctx.emitError(I, ErrMsg + AsmError); 331 332 return Ctx.emitError(I, ErrMsg); 333 } 334 335 /// getCopyFromPartsVector - Create a value that contains the specified legal 336 /// parts combined into the value they represent. If the parts combine to a 337 /// type larger than ValueVT then AssertOp can be used to specify whether the 338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 339 /// ValueVT (ISD::AssertSext). 340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 341 const SDValue *Parts, unsigned NumParts, 342 MVT PartVT, EVT ValueVT, const Value *V, 343 SDValue InChain, 344 std::optional<CallingConv::ID> CallConv) { 345 assert(ValueVT.isVector() && "Not a vector value"); 346 assert(NumParts > 0 && "No parts to assemble!"); 347 const bool IsABIRegCopy = CallConv.has_value(); 348 349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 350 SDValue Val = Parts[0]; 351 352 // Handle a multi-element vector. 353 if (NumParts > 1) { 354 EVT IntermediateVT; 355 MVT RegisterVT; 356 unsigned NumIntermediates; 357 unsigned NumRegs; 358 359 if (IsABIRegCopy) { 360 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 361 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 362 NumIntermediates, RegisterVT); 363 } else { 364 NumRegs = 365 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 366 NumIntermediates, RegisterVT); 367 } 368 369 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 370 NumParts = NumRegs; // Silence a compiler warning. 371 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 372 assert(RegisterVT.getSizeInBits() == 373 Parts[0].getSimpleValueType().getSizeInBits() && 374 "Part type sizes don't match!"); 375 376 // Assemble the parts into intermediate operands. 377 SmallVector<SDValue, 8> Ops(NumIntermediates); 378 if (NumIntermediates == NumParts) { 379 // If the register was not expanded, truncate or copy the value, 380 // as appropriate. 381 for (unsigned i = 0; i != NumParts; ++i) 382 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 383 V, InChain, CallConv); 384 } else if (NumParts > 0) { 385 // If the intermediate type was expanded, build the intermediate 386 // operands from the parts. 387 assert(NumParts % NumIntermediates == 0 && 388 "Must expand into a divisible number of parts!"); 389 unsigned Factor = NumParts / NumIntermediates; 390 for (unsigned i = 0; i != NumIntermediates; ++i) 391 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 392 IntermediateVT, V, InChain, CallConv); 393 } 394 395 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 396 // intermediate operands. 397 EVT BuiltVectorTy = 398 IntermediateVT.isVector() 399 ? EVT::getVectorVT( 400 *DAG.getContext(), IntermediateVT.getScalarType(), 401 IntermediateVT.getVectorElementCount() * NumParts) 402 : EVT::getVectorVT(*DAG.getContext(), 403 IntermediateVT.getScalarType(), 404 NumIntermediates); 405 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 406 : ISD::BUILD_VECTOR, 407 DL, BuiltVectorTy, Ops); 408 } 409 410 // There is now one part, held in Val. Correct it to match ValueVT. 411 EVT PartEVT = Val.getValueType(); 412 413 if (PartEVT == ValueVT) 414 return Val; 415 416 if (PartEVT.isVector()) { 417 // Vector/Vector bitcast. 418 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 421 // If the parts vector has more elements than the value vector, then we 422 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 423 // Extract the elements we want. 424 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 425 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 426 ValueVT.getVectorElementCount().getKnownMinValue()) && 427 (PartEVT.getVectorElementCount().isScalable() == 428 ValueVT.getVectorElementCount().isScalable()) && 429 "Cannot narrow, it would be a lossy transformation"); 430 PartEVT = 431 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 432 ValueVT.getVectorElementCount()); 433 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 434 DAG.getVectorIdxConstant(0, DL)); 435 if (PartEVT == ValueVT) 436 return Val; 437 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 438 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 439 440 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 443 } 444 445 // Promoted vector extract 446 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 447 } 448 449 // Trivial bitcast if the types are the same size and the destination 450 // vector type is legal. 451 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 452 TLI.isTypeLegal(ValueVT)) 453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 454 455 if (ValueVT.getVectorNumElements() != 1) { 456 // Certain ABIs require that vectors are passed as integers. For vectors 457 // are the same size, this is an obvious bitcast. 458 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 459 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 460 } else if (ValueVT.bitsLT(PartEVT)) { 461 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 462 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 463 // Drop the extra bits. 464 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 465 return DAG.getBitcast(ValueVT, Val); 466 } 467 468 diagnosePossiblyInvalidConstraint( 469 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 470 return DAG.getUNDEF(ValueVT); 471 } 472 473 // Handle cases such as i8 -> <1 x i1> 474 EVT ValueSVT = ValueVT.getVectorElementType(); 475 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 476 unsigned ValueSize = ValueSVT.getSizeInBits(); 477 if (ValueSize == PartEVT.getSizeInBits()) { 478 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 479 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 480 // It's possible a scalar floating point type gets softened to integer and 481 // then promoted to a larger integer. If PartEVT is the larger integer 482 // we need to truncate it and then bitcast to the FP type. 483 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 484 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 485 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 486 Val = DAG.getBitcast(ValueSVT, Val); 487 } else { 488 Val = ValueVT.isFloatingPoint() 489 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 490 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 491 } 492 } 493 494 return DAG.getBuildVector(ValueVT, DL, Val); 495 } 496 497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 498 SDValue Val, SDValue *Parts, unsigned NumParts, 499 MVT PartVT, const Value *V, 500 std::optional<CallingConv::ID> CallConv); 501 502 /// getCopyToParts - Create a series of nodes that contain the specified value 503 /// split into legal parts. If the parts contain more bits than Val, then, for 504 /// integers, ExtendKind can be used to specify how to generate the extra bits. 505 static void 506 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 507 unsigned NumParts, MVT PartVT, const Value *V, 508 std::optional<CallingConv::ID> CallConv = std::nullopt, 509 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 510 // Let the target split the parts if it wants to 511 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 512 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 513 CallConv)) 514 return; 515 EVT ValueVT = Val.getValueType(); 516 517 // Handle the vector case separately. 518 if (ValueVT.isVector()) 519 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 520 CallConv); 521 522 unsigned OrigNumParts = NumParts; 523 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 524 "Copying to an illegal type!"); 525 526 if (NumParts == 0) 527 return; 528 529 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 530 EVT PartEVT = PartVT; 531 if (PartEVT == ValueVT) { 532 assert(NumParts == 1 && "No-op copy with multiple parts!"); 533 Parts[0] = Val; 534 return; 535 } 536 537 unsigned PartBits = PartVT.getSizeInBits(); 538 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 539 // If the parts cover more bits than the value has, promote the value. 540 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 541 assert(NumParts == 1 && "Do not know what to promote to!"); 542 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 543 } else { 544 if (ValueVT.isFloatingPoint()) { 545 // FP values need to be bitcast, then extended if they are being put 546 // into a larger container. 547 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 548 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 549 } 550 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 551 ValueVT.isInteger() && 552 "Unknown mismatch!"); 553 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 554 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 555 if (PartVT == MVT::x86mmx) 556 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 557 } 558 } else if (PartBits == ValueVT.getSizeInBits()) { 559 // Different types of the same size. 560 assert(NumParts == 1 && PartEVT != ValueVT); 561 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 562 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 563 // If the parts cover less bits than value has, truncate the value. 564 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 565 ValueVT.isInteger() && 566 "Unknown mismatch!"); 567 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 568 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 569 if (PartVT == MVT::x86mmx) 570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 571 } 572 573 // The value may have changed - recompute ValueVT. 574 ValueVT = Val.getValueType(); 575 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 576 "Failed to tile the value with PartVT!"); 577 578 if (NumParts == 1) { 579 if (PartEVT != ValueVT) { 580 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 581 "scalar-to-vector conversion failed"); 582 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 583 } 584 585 Parts[0] = Val; 586 return; 587 } 588 589 // Expand the value into multiple parts. 590 if (NumParts & (NumParts - 1)) { 591 // The number of parts is not a power of 2. Split off and copy the tail. 592 assert(PartVT.isInteger() && ValueVT.isInteger() && 593 "Do not know what to expand to!"); 594 unsigned RoundParts = llvm::bit_floor(NumParts); 595 unsigned RoundBits = RoundParts * PartBits; 596 unsigned OddParts = NumParts - RoundParts; 597 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 598 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 599 600 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 601 CallConv); 602 603 if (DAG.getDataLayout().isBigEndian()) 604 // The odd parts were reversed by getCopyToParts - unreverse them. 605 std::reverse(Parts + RoundParts, Parts + NumParts); 606 607 NumParts = RoundParts; 608 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 609 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 610 } 611 612 // The number of parts is a power of 2. Repeatedly bisect the value using 613 // EXTRACT_ELEMENT. 614 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 615 EVT::getIntegerVT(*DAG.getContext(), 616 ValueVT.getSizeInBits()), 617 Val); 618 619 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 620 for (unsigned i = 0; i < NumParts; i += StepSize) { 621 unsigned ThisBits = StepSize * PartBits / 2; 622 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 623 SDValue &Part0 = Parts[i]; 624 SDValue &Part1 = Parts[i+StepSize/2]; 625 626 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 627 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 628 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 629 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 630 631 if (ThisBits == PartBits && ThisVT != PartVT) { 632 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 633 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 634 } 635 } 636 } 637 638 if (DAG.getDataLayout().isBigEndian()) 639 std::reverse(Parts, Parts + OrigNumParts); 640 } 641 642 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 643 const SDLoc &DL, EVT PartVT) { 644 if (!PartVT.isVector()) 645 return SDValue(); 646 647 EVT ValueVT = Val.getValueType(); 648 EVT PartEVT = PartVT.getVectorElementType(); 649 EVT ValueEVT = ValueVT.getVectorElementType(); 650 ElementCount PartNumElts = PartVT.getVectorElementCount(); 651 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 652 653 // We only support widening vectors with equivalent element types and 654 // fixed/scalable properties. If a target needs to widen a fixed-length type 655 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 656 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 657 PartNumElts.isScalable() != ValueNumElts.isScalable()) 658 return SDValue(); 659 660 // Have a try for bf16 because some targets share its ABI with fp16. 661 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 662 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 663 "Cannot widen to illegal type"); 664 Val = DAG.getNode(ISD::BITCAST, DL, 665 ValueVT.changeVectorElementType(MVT::f16), Val); 666 } else if (PartEVT != ValueEVT) { 667 return SDValue(); 668 } 669 670 // Widening a scalable vector to another scalable vector is done by inserting 671 // the vector into a larger undef one. 672 if (PartNumElts.isScalable()) 673 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 674 Val, DAG.getVectorIdxConstant(0, DL)); 675 676 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 677 // undef elements. 678 SmallVector<SDValue, 16> Ops; 679 DAG.ExtractVectorElements(Val, Ops); 680 SDValue EltUndef = DAG.getUNDEF(PartEVT); 681 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 682 683 // FIXME: Use CONCAT for 2x -> 4x. 684 return DAG.getBuildVector(PartVT, DL, Ops); 685 } 686 687 /// getCopyToPartsVector - Create a series of nodes that contain the specified 688 /// value split into legal parts. 689 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 690 SDValue Val, SDValue *Parts, unsigned NumParts, 691 MVT PartVT, const Value *V, 692 std::optional<CallingConv::ID> CallConv) { 693 EVT ValueVT = Val.getValueType(); 694 assert(ValueVT.isVector() && "Not a vector"); 695 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 696 const bool IsABIRegCopy = CallConv.has_value(); 697 698 if (NumParts == 1) { 699 EVT PartEVT = PartVT; 700 if (PartEVT == ValueVT) { 701 // Nothing to do. 702 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 703 // Bitconvert vector->vector case. 704 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 705 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 706 Val = Widened; 707 } else if (PartVT.isVector() && 708 PartEVT.getVectorElementType().bitsGE( 709 ValueVT.getVectorElementType()) && 710 PartEVT.getVectorElementCount() == 711 ValueVT.getVectorElementCount()) { 712 713 // Promoted vector extract 714 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 715 } else if (PartEVT.isVector() && 716 PartEVT.getVectorElementType() != 717 ValueVT.getVectorElementType() && 718 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 719 TargetLowering::TypeWidenVector) { 720 // Combination of widening and promotion. 721 EVT WidenVT = 722 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 723 PartVT.getVectorElementCount()); 724 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 725 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 726 } else { 727 // Don't extract an integer from a float vector. This can happen if the 728 // FP type gets softened to integer and then promoted. The promotion 729 // prevents it from being picked up by the earlier bitcast case. 730 if (ValueVT.getVectorElementCount().isScalar() && 731 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 732 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 733 DAG.getVectorIdxConstant(0, DL)); 734 } else { 735 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 736 assert(PartVT.getFixedSizeInBits() > ValueSize && 737 "lossy conversion of vector to scalar type"); 738 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 739 Val = DAG.getBitcast(IntermediateType, Val); 740 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 741 } 742 } 743 744 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 745 Parts[0] = Val; 746 return; 747 } 748 749 // Handle a multi-element vector. 750 EVT IntermediateVT; 751 MVT RegisterVT; 752 unsigned NumIntermediates; 753 unsigned NumRegs; 754 if (IsABIRegCopy) { 755 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 756 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 757 RegisterVT); 758 } else { 759 NumRegs = 760 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 761 NumIntermediates, RegisterVT); 762 } 763 764 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 765 NumParts = NumRegs; // Silence a compiler warning. 766 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 767 768 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 769 "Mixing scalable and fixed vectors when copying in parts"); 770 771 std::optional<ElementCount> DestEltCnt; 772 773 if (IntermediateVT.isVector()) 774 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 775 else 776 DestEltCnt = ElementCount::getFixed(NumIntermediates); 777 778 EVT BuiltVectorTy = EVT::getVectorVT( 779 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 780 781 if (ValueVT == BuiltVectorTy) { 782 // Nothing to do. 783 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 784 // Bitconvert vector->vector case. 785 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 786 } else { 787 if (BuiltVectorTy.getVectorElementType().bitsGT( 788 ValueVT.getVectorElementType())) { 789 // Integer promotion. 790 ValueVT = EVT::getVectorVT(*DAG.getContext(), 791 BuiltVectorTy.getVectorElementType(), 792 ValueVT.getVectorElementCount()); 793 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 794 } 795 796 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 797 Val = Widened; 798 } 799 } 800 801 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 802 803 // Split the vector into intermediate operands. 804 SmallVector<SDValue, 8> Ops(NumIntermediates); 805 for (unsigned i = 0; i != NumIntermediates; ++i) { 806 if (IntermediateVT.isVector()) { 807 // This does something sensible for scalable vectors - see the 808 // definition of EXTRACT_SUBVECTOR for further details. 809 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 810 Ops[i] = 811 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 812 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 813 } else { 814 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 815 DAG.getVectorIdxConstant(i, DL)); 816 } 817 } 818 819 // Split the intermediate operands into legal parts. 820 if (NumParts == NumIntermediates) { 821 // If the register was not expanded, promote or copy the value, 822 // as appropriate. 823 for (unsigned i = 0; i != NumParts; ++i) 824 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 825 } else if (NumParts > 0) { 826 // If the intermediate type was expanded, split each the value into 827 // legal parts. 828 assert(NumIntermediates != 0 && "division by zero"); 829 assert(NumParts % NumIntermediates == 0 && 830 "Must expand into a divisible number of parts!"); 831 unsigned Factor = NumParts / NumIntermediates; 832 for (unsigned i = 0; i != NumIntermediates; ++i) 833 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 834 CallConv); 835 } 836 } 837 838 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 839 EVT valuevt, std::optional<CallingConv::ID> CC) 840 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 841 RegCount(1, regs.size()), CallConv(CC) {} 842 843 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 844 const DataLayout &DL, unsigned Reg, Type *Ty, 845 std::optional<CallingConv::ID> CC) { 846 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 847 848 CallConv = CC; 849 850 for (EVT ValueVT : ValueVTs) { 851 unsigned NumRegs = 852 isABIMangled() 853 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 854 : TLI.getNumRegisters(Context, ValueVT); 855 MVT RegisterVT = 856 isABIMangled() 857 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 858 : TLI.getRegisterType(Context, ValueVT); 859 for (unsigned i = 0; i != NumRegs; ++i) 860 Regs.push_back(Reg + i); 861 RegVTs.push_back(RegisterVT); 862 RegCount.push_back(NumRegs); 863 Reg += NumRegs; 864 } 865 } 866 867 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 868 FunctionLoweringInfo &FuncInfo, 869 const SDLoc &dl, SDValue &Chain, 870 SDValue *Glue, const Value *V) const { 871 // A Value with type {} or [0 x %t] needs no registers. 872 if (ValueVTs.empty()) 873 return SDValue(); 874 875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 876 877 // Assemble the legal parts into the final values. 878 SmallVector<SDValue, 4> Values(ValueVTs.size()); 879 SmallVector<SDValue, 8> Parts; 880 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 881 // Copy the legal parts from the registers. 882 EVT ValueVT = ValueVTs[Value]; 883 unsigned NumRegs = RegCount[Value]; 884 MVT RegisterVT = isABIMangled() 885 ? TLI.getRegisterTypeForCallingConv( 886 *DAG.getContext(), *CallConv, RegVTs[Value]) 887 : RegVTs[Value]; 888 889 Parts.resize(NumRegs); 890 for (unsigned i = 0; i != NumRegs; ++i) { 891 SDValue P; 892 if (!Glue) { 893 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 894 } else { 895 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 896 *Glue = P.getValue(2); 897 } 898 899 Chain = P.getValue(1); 900 Parts[i] = P; 901 902 // If the source register was virtual and if we know something about it, 903 // add an assert node. 904 if (!Register::isVirtualRegister(Regs[Part + i]) || 905 !RegisterVT.isInteger()) 906 continue; 907 908 const FunctionLoweringInfo::LiveOutInfo *LOI = 909 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 910 if (!LOI) 911 continue; 912 913 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 914 unsigned NumSignBits = LOI->NumSignBits; 915 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 916 917 if (NumZeroBits == RegSize) { 918 // The current value is a zero. 919 // Explicitly express that as it would be easier for 920 // optimizations to kick in. 921 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 922 continue; 923 } 924 925 // FIXME: We capture more information than the dag can represent. For 926 // now, just use the tightest assertzext/assertsext possible. 927 bool isSExt; 928 EVT FromVT(MVT::Other); 929 if (NumZeroBits) { 930 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 931 isSExt = false; 932 } else if (NumSignBits > 1) { 933 FromVT = 934 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 935 isSExt = true; 936 } else { 937 continue; 938 } 939 // Add an assertion node. 940 assert(FromVT != MVT::Other); 941 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 942 RegisterVT, P, DAG.getValueType(FromVT)); 943 } 944 945 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 946 RegisterVT, ValueVT, V, Chain, CallConv); 947 Part += NumRegs; 948 Parts.clear(); 949 } 950 951 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 952 } 953 954 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 955 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 956 const Value *V, 957 ISD::NodeType PreferredExtendType) const { 958 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 959 ISD::NodeType ExtendKind = PreferredExtendType; 960 961 // Get the list of the values's legal parts. 962 unsigned NumRegs = Regs.size(); 963 SmallVector<SDValue, 8> Parts(NumRegs); 964 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 965 unsigned NumParts = RegCount[Value]; 966 967 MVT RegisterVT = isABIMangled() 968 ? TLI.getRegisterTypeForCallingConv( 969 *DAG.getContext(), *CallConv, RegVTs[Value]) 970 : RegVTs[Value]; 971 972 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 973 ExtendKind = ISD::ZERO_EXTEND; 974 975 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 976 NumParts, RegisterVT, V, CallConv, ExtendKind); 977 Part += NumParts; 978 } 979 980 // Copy the parts into the registers. 981 SmallVector<SDValue, 8> Chains(NumRegs); 982 for (unsigned i = 0; i != NumRegs; ++i) { 983 SDValue Part; 984 if (!Glue) { 985 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 986 } else { 987 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 988 *Glue = Part.getValue(1); 989 } 990 991 Chains[i] = Part.getValue(0); 992 } 993 994 if (NumRegs == 1 || Glue) 995 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 996 // flagged to it. That is the CopyToReg nodes and the user are considered 997 // a single scheduling unit. If we create a TokenFactor and return it as 998 // chain, then the TokenFactor is both a predecessor (operand) of the 999 // user as well as a successor (the TF operands are flagged to the user). 1000 // c1, f1 = CopyToReg 1001 // c2, f2 = CopyToReg 1002 // c3 = TokenFactor c1, c2 1003 // ... 1004 // = op c3, ..., f2 1005 Chain = Chains[NumRegs-1]; 1006 else 1007 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1008 } 1009 1010 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1011 unsigned MatchingIdx, const SDLoc &dl, 1012 SelectionDAG &DAG, 1013 std::vector<SDValue> &Ops) const { 1014 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1015 1016 InlineAsm::Flag Flag(Code, Regs.size()); 1017 if (HasMatching) 1018 Flag.setMatchingOp(MatchingIdx); 1019 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1020 // Put the register class of the virtual registers in the flag word. That 1021 // way, later passes can recompute register class constraints for inline 1022 // assembly as well as normal instructions. 1023 // Don't do this for tied operands that can use the regclass information 1024 // from the def. 1025 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1026 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1027 Flag.setRegClass(RC->getID()); 1028 } 1029 1030 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1031 Ops.push_back(Res); 1032 1033 if (Code == InlineAsm::Kind::Clobber) { 1034 // Clobbers should always have a 1:1 mapping with registers, and may 1035 // reference registers that have illegal (e.g. vector) types. Hence, we 1036 // shouldn't try to apply any sort of splitting logic to them. 1037 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1038 "No 1:1 mapping from clobbers to regs?"); 1039 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1040 (void)SP; 1041 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1042 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1043 assert( 1044 (Regs[I] != SP || 1045 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1046 "If we clobbered the stack pointer, MFI should know about it."); 1047 } 1048 return; 1049 } 1050 1051 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1052 MVT RegisterVT = RegVTs[Value]; 1053 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1054 RegisterVT); 1055 for (unsigned i = 0; i != NumRegs; ++i) { 1056 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1057 unsigned TheReg = Regs[Reg++]; 1058 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1059 } 1060 } 1061 } 1062 1063 SmallVector<std::pair<unsigned, TypeSize>, 4> 1064 RegsForValue::getRegsAndSizes() const { 1065 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1066 unsigned I = 0; 1067 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1068 unsigned RegCount = std::get<0>(CountAndVT); 1069 MVT RegisterVT = std::get<1>(CountAndVT); 1070 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1071 for (unsigned E = I + RegCount; I != E; ++I) 1072 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1073 } 1074 return OutVec; 1075 } 1076 1077 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1078 AssumptionCache *ac, 1079 const TargetLibraryInfo *li) { 1080 AA = aa; 1081 AC = ac; 1082 GFI = gfi; 1083 LibInfo = li; 1084 Context = DAG.getContext(); 1085 LPadToCallSiteMap.clear(); 1086 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1087 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1088 *DAG.getMachineFunction().getFunction().getParent()); 1089 } 1090 1091 void SelectionDAGBuilder::clear() { 1092 NodeMap.clear(); 1093 UnusedArgNodeMap.clear(); 1094 PendingLoads.clear(); 1095 PendingExports.clear(); 1096 PendingConstrainedFP.clear(); 1097 PendingConstrainedFPStrict.clear(); 1098 CurInst = nullptr; 1099 HasTailCall = false; 1100 SDNodeOrder = LowestSDNodeOrder; 1101 StatepointLowering.clear(); 1102 } 1103 1104 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1105 DanglingDebugInfoMap.clear(); 1106 } 1107 1108 // Update DAG root to include dependencies on Pending chains. 1109 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1110 SDValue Root = DAG.getRoot(); 1111 1112 if (Pending.empty()) 1113 return Root; 1114 1115 // Add current root to PendingChains, unless we already indirectly 1116 // depend on it. 1117 if (Root.getOpcode() != ISD::EntryToken) { 1118 unsigned i = 0, e = Pending.size(); 1119 for (; i != e; ++i) { 1120 assert(Pending[i].getNode()->getNumOperands() > 1); 1121 if (Pending[i].getNode()->getOperand(0) == Root) 1122 break; // Don't add the root if we already indirectly depend on it. 1123 } 1124 1125 if (i == e) 1126 Pending.push_back(Root); 1127 } 1128 1129 if (Pending.size() == 1) 1130 Root = Pending[0]; 1131 else 1132 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1133 1134 DAG.setRoot(Root); 1135 Pending.clear(); 1136 return Root; 1137 } 1138 1139 SDValue SelectionDAGBuilder::getMemoryRoot() { 1140 return updateRoot(PendingLoads); 1141 } 1142 1143 SDValue SelectionDAGBuilder::getRoot() { 1144 // Chain up all pending constrained intrinsics together with all 1145 // pending loads, by simply appending them to PendingLoads and 1146 // then calling getMemoryRoot(). 1147 PendingLoads.reserve(PendingLoads.size() + 1148 PendingConstrainedFP.size() + 1149 PendingConstrainedFPStrict.size()); 1150 PendingLoads.append(PendingConstrainedFP.begin(), 1151 PendingConstrainedFP.end()); 1152 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1153 PendingConstrainedFPStrict.end()); 1154 PendingConstrainedFP.clear(); 1155 PendingConstrainedFPStrict.clear(); 1156 return getMemoryRoot(); 1157 } 1158 1159 SDValue SelectionDAGBuilder::getControlRoot() { 1160 // We need to emit pending fpexcept.strict constrained intrinsics, 1161 // so append them to the PendingExports list. 1162 PendingExports.append(PendingConstrainedFPStrict.begin(), 1163 PendingConstrainedFPStrict.end()); 1164 PendingConstrainedFPStrict.clear(); 1165 return updateRoot(PendingExports); 1166 } 1167 1168 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1169 DILocalVariable *Variable, 1170 DIExpression *Expression, 1171 DebugLoc DL) { 1172 assert(Variable && "Missing variable"); 1173 1174 // Check if address has undef value. 1175 if (!Address || isa<UndefValue>(Address) || 1176 (Address->use_empty() && !isa<Argument>(Address))) { 1177 LLVM_DEBUG( 1178 dbgs() 1179 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1180 return; 1181 } 1182 1183 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1184 1185 SDValue &N = NodeMap[Address]; 1186 if (!N.getNode() && isa<Argument>(Address)) 1187 // Check unused arguments map. 1188 N = UnusedArgNodeMap[Address]; 1189 SDDbgValue *SDV; 1190 if (N.getNode()) { 1191 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1192 Address = BCI->getOperand(0); 1193 // Parameters are handled specially. 1194 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1195 if (IsParameter && FINode) { 1196 // Byval parameter. We have a frame index at this point. 1197 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1198 /*IsIndirect*/ true, DL, SDNodeOrder); 1199 } else if (isa<Argument>(Address)) { 1200 // Address is an argument, so try to emit its dbg value using 1201 // virtual register info from the FuncInfo.ValueMap. 1202 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1203 FuncArgumentDbgValueKind::Declare, N); 1204 return; 1205 } else { 1206 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1207 true, DL, SDNodeOrder); 1208 } 1209 DAG.AddDbgValue(SDV, IsParameter); 1210 } else { 1211 // If Address is an argument then try to emit its dbg value using 1212 // virtual register info from the FuncInfo.ValueMap. 1213 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1214 FuncArgumentDbgValueKind::Declare, N)) { 1215 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1216 << " (could not emit func-arg dbg_value)\n"); 1217 } 1218 } 1219 return; 1220 } 1221 1222 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1223 // Add SDDbgValue nodes for any var locs here. Do so before updating 1224 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1225 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1226 // Add SDDbgValue nodes for any var locs here. Do so before updating 1227 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1228 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1229 It != End; ++It) { 1230 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1231 dropDanglingDebugInfo(Var, It->Expr); 1232 if (It->Values.isKillLocation(It->Expr)) { 1233 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1234 continue; 1235 } 1236 SmallVector<Value *> Values(It->Values.location_ops()); 1237 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1238 It->Values.hasArgList())) { 1239 SmallVector<Value *, 4> Vals; 1240 for (Value *V : It->Values.location_ops()) 1241 Vals.push_back(V); 1242 addDanglingDebugInfo(Vals, 1243 FnVarLocs->getDILocalVariable(It->VariableID), 1244 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1245 } 1246 } 1247 } 1248 1249 // We must skip DbgVariableRecords if they've already been processed above as 1250 // we have just emitted the debug values resulting from assignment tracking 1251 // analysis, making any existing DbgVariableRecords redundant (and probably 1252 // less correct). We still need to process DbgLabelRecords. This does sink 1253 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't 1254 // be important as it does so deterministcally and ordering between 1255 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR 1256 // printing). 1257 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs(); 1258 // Is there is any debug-info attached to this instruction, in the form of 1259 // DbgRecord non-instruction debug-info records. 1260 for (DbgRecord &DR : I.getDbgRecordRange()) { 1261 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) { 1262 assert(DLR->getLabel() && "Missing label"); 1263 SDDbgLabel *SDV = 1264 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder); 1265 DAG.AddDbgLabel(SDV); 1266 continue; 1267 } 1268 1269 if (SkipDbgVariableRecords) 1270 continue; 1271 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR); 1272 DILocalVariable *Variable = DVR.getVariable(); 1273 DIExpression *Expression = DVR.getExpression(); 1274 dropDanglingDebugInfo(Variable, Expression); 1275 1276 if (DVR.getType() == DbgVariableRecord::LocationType::Declare) { 1277 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR)) 1278 continue; 1279 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR 1280 << "\n"); 1281 handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression, 1282 DVR.getDebugLoc()); 1283 continue; 1284 } 1285 1286 // A DbgVariableRecord with no locations is a kill location. 1287 SmallVector<Value *, 4> Values(DVR.location_ops()); 1288 if (Values.empty()) { 1289 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1290 SDNodeOrder); 1291 continue; 1292 } 1293 1294 // A DbgVariableRecord with an undef or absent location is also a kill 1295 // location. 1296 if (llvm::any_of(Values, 1297 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1298 handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(), 1299 SDNodeOrder); 1300 continue; 1301 } 1302 1303 bool IsVariadic = DVR.hasArgList(); 1304 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(), 1305 SDNodeOrder, IsVariadic)) { 1306 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1307 DVR.getDebugLoc(), SDNodeOrder); 1308 } 1309 } 1310 } 1311 1312 void SelectionDAGBuilder::visit(const Instruction &I) { 1313 visitDbgInfo(I); 1314 1315 // Set up outgoing PHI node register values before emitting the terminator. 1316 if (I.isTerminator()) { 1317 HandlePHINodesInSuccessorBlocks(I.getParent()); 1318 } 1319 1320 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1321 if (!isa<DbgInfoIntrinsic>(I)) 1322 ++SDNodeOrder; 1323 1324 CurInst = &I; 1325 1326 // Set inserted listener only if required. 1327 bool NodeInserted = false; 1328 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1329 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1330 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra); 1331 if (PCSectionsMD || MMRA) { 1332 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1333 DAG, [&](SDNode *) { NodeInserted = true; }); 1334 } 1335 1336 visit(I.getOpcode(), I); 1337 1338 if (!I.isTerminator() && !HasTailCall && 1339 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1340 CopyToExportRegsIfNeeded(&I); 1341 1342 // Handle metadata. 1343 if (PCSectionsMD || MMRA) { 1344 auto It = NodeMap.find(&I); 1345 if (It != NodeMap.end()) { 1346 if (PCSectionsMD) 1347 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1348 if (MMRA) 1349 DAG.addMMRAMetadata(It->second.getNode(), MMRA); 1350 } else if (NodeInserted) { 1351 // This should not happen; if it does, don't let it go unnoticed so we can 1352 // fix it. Relevant visit*() function is probably missing a setValue(). 1353 errs() << "warning: loosing !pcsections and/or !mmra metadata [" 1354 << I.getModule()->getName() << "]\n"; 1355 LLVM_DEBUG(I.dump()); 1356 assert(false); 1357 } 1358 } 1359 1360 CurInst = nullptr; 1361 } 1362 1363 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1364 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1365 } 1366 1367 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1368 // Note: this doesn't use InstVisitor, because it has to work with 1369 // ConstantExpr's in addition to instructions. 1370 switch (Opcode) { 1371 default: llvm_unreachable("Unknown instruction type encountered!"); 1372 // Build the switch statement using the Instruction.def file. 1373 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1374 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1375 #include "llvm/IR/Instruction.def" 1376 } 1377 } 1378 1379 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1380 DILocalVariable *Variable, 1381 DebugLoc DL, unsigned Order, 1382 SmallVectorImpl<Value *> &Values, 1383 DIExpression *Expression) { 1384 // For variadic dbg_values we will now insert an undef. 1385 // FIXME: We can potentially recover these! 1386 SmallVector<SDDbgOperand, 2> Locs; 1387 for (const Value *V : Values) { 1388 auto *Undef = UndefValue::get(V->getType()); 1389 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1390 } 1391 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1392 /*IsIndirect=*/false, DL, Order, 1393 /*IsVariadic=*/true); 1394 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1395 return true; 1396 } 1397 1398 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1399 DILocalVariable *Var, 1400 DIExpression *Expr, 1401 bool IsVariadic, DebugLoc DL, 1402 unsigned Order) { 1403 if (IsVariadic) { 1404 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1405 return; 1406 } 1407 // TODO: Dangling debug info will eventually either be resolved or produce 1408 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1409 // between the original dbg.value location and its resolved DBG_VALUE, 1410 // which we should ideally fill with an extra Undef DBG_VALUE. 1411 assert(Values.size() == 1); 1412 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1413 } 1414 1415 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1416 const DIExpression *Expr) { 1417 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1418 DIVariable *DanglingVariable = DDI.getVariable(); 1419 DIExpression *DanglingExpr = DDI.getExpression(); 1420 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1421 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1422 << printDDI(nullptr, DDI) << "\n"); 1423 return true; 1424 } 1425 return false; 1426 }; 1427 1428 for (auto &DDIMI : DanglingDebugInfoMap) { 1429 DanglingDebugInfoVector &DDIV = DDIMI.second; 1430 1431 // If debug info is to be dropped, run it through final checks to see 1432 // whether it can be salvaged. 1433 for (auto &DDI : DDIV) 1434 if (isMatchingDbgValue(DDI)) 1435 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1436 1437 erase_if(DDIV, isMatchingDbgValue); 1438 } 1439 } 1440 1441 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1442 // generate the debug data structures now that we've seen its definition. 1443 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1444 SDValue Val) { 1445 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1446 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1447 return; 1448 1449 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1450 for (auto &DDI : DDIV) { 1451 DebugLoc DL = DDI.getDebugLoc(); 1452 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1453 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1454 DILocalVariable *Variable = DDI.getVariable(); 1455 DIExpression *Expr = DDI.getExpression(); 1456 assert(Variable->isValidLocationForIntrinsic(DL) && 1457 "Expected inlined-at fields to agree"); 1458 SDDbgValue *SDV; 1459 if (Val.getNode()) { 1460 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1461 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1462 // we couldn't resolve it directly when examining the DbgValue intrinsic 1463 // in the first place we should not be more successful here). Unless we 1464 // have some test case that prove this to be correct we should avoid 1465 // calling EmitFuncArgumentDbgValue here. 1466 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1467 FuncArgumentDbgValueKind::Value, Val)) { 1468 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1469 << printDDI(V, DDI) << "\n"); 1470 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1471 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1472 // inserted after the definition of Val when emitting the instructions 1473 // after ISel. An alternative could be to teach 1474 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1475 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1476 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1477 << ValSDNodeOrder << "\n"); 1478 SDV = getDbgValue(Val, Variable, Expr, DL, 1479 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1480 DAG.AddDbgValue(SDV, false); 1481 } else 1482 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1483 << printDDI(V, DDI) 1484 << " in EmitFuncArgumentDbgValue\n"); 1485 } else { 1486 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1487 << "\n"); 1488 auto Undef = UndefValue::get(V->getType()); 1489 auto SDV = 1490 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1491 DAG.AddDbgValue(SDV, false); 1492 } 1493 } 1494 DDIV.clear(); 1495 } 1496 1497 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1498 DanglingDebugInfo &DDI) { 1499 // TODO: For the variadic implementation, instead of only checking the fail 1500 // state of `handleDebugValue`, we need know specifically which values were 1501 // invalid, so that we attempt to salvage only those values when processing 1502 // a DIArgList. 1503 const Value *OrigV = V; 1504 DILocalVariable *Var = DDI.getVariable(); 1505 DIExpression *Expr = DDI.getExpression(); 1506 DebugLoc DL = DDI.getDebugLoc(); 1507 unsigned SDOrder = DDI.getSDNodeOrder(); 1508 1509 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1510 // that DW_OP_stack_value is desired. 1511 bool StackValue = true; 1512 1513 // Can this Value can be encoded without any further work? 1514 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1515 return; 1516 1517 // Attempt to salvage back through as many instructions as possible. Bail if 1518 // a non-instruction is seen, such as a constant expression or global 1519 // variable. FIXME: Further work could recover those too. 1520 while (isa<Instruction>(V)) { 1521 const Instruction &VAsInst = *cast<const Instruction>(V); 1522 // Temporary "0", awaiting real implementation. 1523 SmallVector<uint64_t, 16> Ops; 1524 SmallVector<Value *, 4> AdditionalValues; 1525 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1526 Expr->getNumLocationOperands(), Ops, 1527 AdditionalValues); 1528 // If we cannot salvage any further, and haven't yet found a suitable debug 1529 // expression, bail out. 1530 if (!V) 1531 break; 1532 1533 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1534 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1535 // here for variadic dbg_values, remove that condition. 1536 if (!AdditionalValues.empty()) 1537 break; 1538 1539 // New value and expr now represent this debuginfo. 1540 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1541 1542 // Some kind of simplification occurred: check whether the operand of the 1543 // salvaged debug expression can be encoded in this DAG. 1544 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1545 LLVM_DEBUG( 1546 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1547 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1548 return; 1549 } 1550 } 1551 1552 // This was the final opportunity to salvage this debug information, and it 1553 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1554 // any earlier variable location. 1555 assert(OrigV && "V shouldn't be null"); 1556 auto *Undef = UndefValue::get(OrigV->getType()); 1557 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1558 DAG.AddDbgValue(SDV, false); 1559 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1560 << printDDI(OrigV, DDI) << "\n"); 1561 } 1562 1563 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1564 DIExpression *Expr, 1565 DebugLoc DbgLoc, 1566 unsigned Order) { 1567 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1568 DIExpression *NewExpr = 1569 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1570 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1571 /*IsVariadic*/ false); 1572 } 1573 1574 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1575 DILocalVariable *Var, 1576 DIExpression *Expr, DebugLoc DbgLoc, 1577 unsigned Order, bool IsVariadic) { 1578 if (Values.empty()) 1579 return true; 1580 1581 // Filter EntryValue locations out early. 1582 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1583 return true; 1584 1585 SmallVector<SDDbgOperand> LocationOps; 1586 SmallVector<SDNode *> Dependencies; 1587 for (const Value *V : Values) { 1588 // Constant value. 1589 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1590 isa<ConstantPointerNull>(V)) { 1591 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1592 continue; 1593 } 1594 1595 // Look through IntToPtr constants. 1596 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1597 if (CE->getOpcode() == Instruction::IntToPtr) { 1598 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1599 continue; 1600 } 1601 1602 // If the Value is a frame index, we can create a FrameIndex debug value 1603 // without relying on the DAG at all. 1604 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1605 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1606 if (SI != FuncInfo.StaticAllocaMap.end()) { 1607 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1608 continue; 1609 } 1610 } 1611 1612 // Do not use getValue() in here; we don't want to generate code at 1613 // this point if it hasn't been done yet. 1614 SDValue N = NodeMap[V]; 1615 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1616 N = UnusedArgNodeMap[V]; 1617 if (N.getNode()) { 1618 // Only emit func arg dbg value for non-variadic dbg.values for now. 1619 if (!IsVariadic && 1620 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1621 FuncArgumentDbgValueKind::Value, N)) 1622 return true; 1623 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1624 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1625 // describe stack slot locations. 1626 // 1627 // Consider "int x = 0; int *px = &x;". There are two kinds of 1628 // interesting debug values here after optimization: 1629 // 1630 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1631 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1632 // 1633 // Both describe the direct values of their associated variables. 1634 Dependencies.push_back(N.getNode()); 1635 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1636 continue; 1637 } 1638 LocationOps.emplace_back( 1639 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1640 continue; 1641 } 1642 1643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1644 // Special rules apply for the first dbg.values of parameter variables in a 1645 // function. Identify them by the fact they reference Argument Values, that 1646 // they're parameters, and they are parameters of the current function. We 1647 // need to let them dangle until they get an SDNode. 1648 bool IsParamOfFunc = 1649 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1650 if (IsParamOfFunc) 1651 return false; 1652 1653 // The value is not used in this block yet (or it would have an SDNode). 1654 // We still want the value to appear for the user if possible -- if it has 1655 // an associated VReg, we can refer to that instead. 1656 auto VMI = FuncInfo.ValueMap.find(V); 1657 if (VMI != FuncInfo.ValueMap.end()) { 1658 unsigned Reg = VMI->second; 1659 // If this is a PHI node, it may be split up into several MI PHI nodes 1660 // (in FunctionLoweringInfo::set). 1661 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1662 V->getType(), std::nullopt); 1663 if (RFV.occupiesMultipleRegs()) { 1664 // FIXME: We could potentially support variadic dbg_values here. 1665 if (IsVariadic) 1666 return false; 1667 unsigned Offset = 0; 1668 unsigned BitsToDescribe = 0; 1669 if (auto VarSize = Var->getSizeInBits()) 1670 BitsToDescribe = *VarSize; 1671 if (auto Fragment = Expr->getFragmentInfo()) 1672 BitsToDescribe = Fragment->SizeInBits; 1673 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1674 // Bail out if all bits are described already. 1675 if (Offset >= BitsToDescribe) 1676 break; 1677 // TODO: handle scalable vectors. 1678 unsigned RegisterSize = RegAndSize.second; 1679 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1680 ? BitsToDescribe - Offset 1681 : RegisterSize; 1682 auto FragmentExpr = DIExpression::createFragmentExpression( 1683 Expr, Offset, FragmentSize); 1684 if (!FragmentExpr) 1685 continue; 1686 SDDbgValue *SDV = DAG.getVRegDbgValue( 1687 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1688 DAG.AddDbgValue(SDV, false); 1689 Offset += RegisterSize; 1690 } 1691 return true; 1692 } 1693 // We can use simple vreg locations for variadic dbg_values as well. 1694 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1695 continue; 1696 } 1697 // We failed to create a SDDbgOperand for V. 1698 return false; 1699 } 1700 1701 // We have created a SDDbgOperand for each Value in Values. 1702 // Should use Order instead of SDNodeOrder? 1703 assert(!LocationOps.empty()); 1704 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1705 /*IsIndirect=*/false, DbgLoc, 1706 SDNodeOrder, IsVariadic); 1707 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1708 return true; 1709 } 1710 1711 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1712 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1713 for (auto &Pair : DanglingDebugInfoMap) 1714 for (auto &DDI : Pair.second) 1715 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1716 clearDanglingDebugInfo(); 1717 } 1718 1719 /// getCopyFromRegs - If there was virtual register allocated for the value V 1720 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1721 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1722 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1723 SDValue Result; 1724 1725 if (It != FuncInfo.ValueMap.end()) { 1726 Register InReg = It->second; 1727 1728 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1729 DAG.getDataLayout(), InReg, Ty, 1730 std::nullopt); // This is not an ABI copy. 1731 SDValue Chain = DAG.getEntryNode(); 1732 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1733 V); 1734 resolveDanglingDebugInfo(V, Result); 1735 } 1736 1737 return Result; 1738 } 1739 1740 /// getValue - Return an SDValue for the given Value. 1741 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1742 // If we already have an SDValue for this value, use it. It's important 1743 // to do this first, so that we don't create a CopyFromReg if we already 1744 // have a regular SDValue. 1745 SDValue &N = NodeMap[V]; 1746 if (N.getNode()) return N; 1747 1748 // If there's a virtual register allocated and initialized for this 1749 // value, use it. 1750 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1751 return copyFromReg; 1752 1753 // Otherwise create a new SDValue and remember it. 1754 SDValue Val = getValueImpl(V); 1755 NodeMap[V] = Val; 1756 resolveDanglingDebugInfo(V, Val); 1757 return Val; 1758 } 1759 1760 /// getNonRegisterValue - Return an SDValue for the given Value, but 1761 /// don't look in FuncInfo.ValueMap for a virtual register. 1762 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1763 // If we already have an SDValue for this value, use it. 1764 SDValue &N = NodeMap[V]; 1765 if (N.getNode()) { 1766 if (isIntOrFPConstant(N)) { 1767 // Remove the debug location from the node as the node is about to be used 1768 // in a location which may differ from the original debug location. This 1769 // is relevant to Constant and ConstantFP nodes because they can appear 1770 // as constant expressions inside PHI nodes. 1771 N->setDebugLoc(DebugLoc()); 1772 } 1773 return N; 1774 } 1775 1776 // Otherwise create a new SDValue and remember it. 1777 SDValue Val = getValueImpl(V); 1778 NodeMap[V] = Val; 1779 resolveDanglingDebugInfo(V, Val); 1780 return Val; 1781 } 1782 1783 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1784 /// Create an SDValue for the given value. 1785 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1787 1788 if (const Constant *C = dyn_cast<Constant>(V)) { 1789 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1790 1791 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1792 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1793 1794 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1795 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1796 1797 if (isa<ConstantPointerNull>(C)) { 1798 unsigned AS = V->getType()->getPointerAddressSpace(); 1799 return DAG.getConstant(0, getCurSDLoc(), 1800 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1801 } 1802 1803 if (match(C, m_VScale())) 1804 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1805 1806 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1807 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1808 1809 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1810 return DAG.getUNDEF(VT); 1811 1812 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1813 visit(CE->getOpcode(), *CE); 1814 SDValue N1 = NodeMap[V]; 1815 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1816 return N1; 1817 } 1818 1819 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1820 SmallVector<SDValue, 4> Constants; 1821 for (const Use &U : C->operands()) { 1822 SDNode *Val = getValue(U).getNode(); 1823 // If the operand is an empty aggregate, there are no values. 1824 if (!Val) continue; 1825 // Add each leaf value from the operand to the Constants list 1826 // to form a flattened list of all the values. 1827 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1828 Constants.push_back(SDValue(Val, i)); 1829 } 1830 1831 return DAG.getMergeValues(Constants, getCurSDLoc()); 1832 } 1833 1834 if (const ConstantDataSequential *CDS = 1835 dyn_cast<ConstantDataSequential>(C)) { 1836 SmallVector<SDValue, 4> Ops; 1837 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1838 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1839 // Add each leaf value from the operand to the Constants list 1840 // to form a flattened list of all the values. 1841 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1842 Ops.push_back(SDValue(Val, i)); 1843 } 1844 1845 if (isa<ArrayType>(CDS->getType())) 1846 return DAG.getMergeValues(Ops, getCurSDLoc()); 1847 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1848 } 1849 1850 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1851 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1852 "Unknown struct or array constant!"); 1853 1854 SmallVector<EVT, 4> ValueVTs; 1855 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1856 unsigned NumElts = ValueVTs.size(); 1857 if (NumElts == 0) 1858 return SDValue(); // empty struct 1859 SmallVector<SDValue, 4> Constants(NumElts); 1860 for (unsigned i = 0; i != NumElts; ++i) { 1861 EVT EltVT = ValueVTs[i]; 1862 if (isa<UndefValue>(C)) 1863 Constants[i] = DAG.getUNDEF(EltVT); 1864 else if (EltVT.isFloatingPoint()) 1865 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1866 else 1867 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1868 } 1869 1870 return DAG.getMergeValues(Constants, getCurSDLoc()); 1871 } 1872 1873 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1874 return DAG.getBlockAddress(BA, VT); 1875 1876 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1877 return getValue(Equiv->getGlobalValue()); 1878 1879 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1880 return getValue(NC->getGlobalValue()); 1881 1882 if (VT == MVT::aarch64svcount) { 1883 assert(C->isNullValue() && "Can only zero this target type!"); 1884 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1885 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1886 } 1887 1888 VectorType *VecTy = cast<VectorType>(V->getType()); 1889 1890 // Now that we know the number and type of the elements, get that number of 1891 // elements into the Ops array based on what kind of constant it is. 1892 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1893 SmallVector<SDValue, 16> Ops; 1894 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1895 for (unsigned i = 0; i != NumElements; ++i) 1896 Ops.push_back(getValue(CV->getOperand(i))); 1897 1898 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1899 } 1900 1901 if (isa<ConstantAggregateZero>(C)) { 1902 EVT EltVT = 1903 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1904 1905 SDValue Op; 1906 if (EltVT.isFloatingPoint()) 1907 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1908 else 1909 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1910 1911 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1912 } 1913 1914 llvm_unreachable("Unknown vector constant"); 1915 } 1916 1917 // If this is a static alloca, generate it as the frameindex instead of 1918 // computation. 1919 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1920 DenseMap<const AllocaInst*, int>::iterator SI = 1921 FuncInfo.StaticAllocaMap.find(AI); 1922 if (SI != FuncInfo.StaticAllocaMap.end()) 1923 return DAG.getFrameIndex( 1924 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1925 } 1926 1927 // If this is an instruction which fast-isel has deferred, select it now. 1928 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1929 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1930 1931 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1932 Inst->getType(), std::nullopt); 1933 SDValue Chain = DAG.getEntryNode(); 1934 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1935 } 1936 1937 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1938 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1939 1940 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1941 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1942 1943 llvm_unreachable("Can't get register for value!"); 1944 } 1945 1946 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1947 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1948 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1949 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1950 bool IsSEH = isAsynchronousEHPersonality(Pers); 1951 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1952 if (!IsSEH) 1953 CatchPadMBB->setIsEHScopeEntry(); 1954 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1955 if (IsMSVCCXX || IsCoreCLR) 1956 CatchPadMBB->setIsEHFuncletEntry(); 1957 } 1958 1959 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1960 // Update machine-CFG edge. 1961 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1962 FuncInfo.MBB->addSuccessor(TargetMBB); 1963 TargetMBB->setIsEHCatchretTarget(true); 1964 DAG.getMachineFunction().setHasEHCatchret(true); 1965 1966 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1967 bool IsSEH = isAsynchronousEHPersonality(Pers); 1968 if (IsSEH) { 1969 // If this is not a fall-through branch or optimizations are switched off, 1970 // emit the branch. 1971 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1972 TM.getOptLevel() == CodeGenOptLevel::None) 1973 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1974 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1975 return; 1976 } 1977 1978 // Figure out the funclet membership for the catchret's successor. 1979 // This will be used by the FuncletLayout pass to determine how to order the 1980 // BB's. 1981 // A 'catchret' returns to the outer scope's color. 1982 Value *ParentPad = I.getCatchSwitchParentPad(); 1983 const BasicBlock *SuccessorColor; 1984 if (isa<ConstantTokenNone>(ParentPad)) 1985 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1986 else 1987 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1988 assert(SuccessorColor && "No parent funclet for catchret!"); 1989 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1990 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1991 1992 // Create the terminator node. 1993 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1994 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1995 DAG.getBasicBlock(SuccessorColorMBB)); 1996 DAG.setRoot(Ret); 1997 } 1998 1999 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 2000 // Don't emit any special code for the cleanuppad instruction. It just marks 2001 // the start of an EH scope/funclet. 2002 FuncInfo.MBB->setIsEHScopeEntry(); 2003 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2004 if (Pers != EHPersonality::Wasm_CXX) { 2005 FuncInfo.MBB->setIsEHFuncletEntry(); 2006 FuncInfo.MBB->setIsCleanupFuncletEntry(); 2007 } 2008 } 2009 2010 // In wasm EH, even though a catchpad may not catch an exception if a tag does 2011 // not match, it is OK to add only the first unwind destination catchpad to the 2012 // successors, because there will be at least one invoke instruction within the 2013 // catch scope that points to the next unwind destination, if one exists, so 2014 // CFGSort cannot mess up with BB sorting order. 2015 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 2016 // call within them, and catchpads only consisting of 'catch (...)' have a 2017 // '__cxa_end_catch' call within them, both of which generate invokes in case 2018 // the next unwind destination exists, i.e., the next unwind destination is not 2019 // the caller.) 2020 // 2021 // Having at most one EH pad successor is also simpler and helps later 2022 // transformations. 2023 // 2024 // For example, 2025 // current: 2026 // invoke void @foo to ... unwind label %catch.dispatch 2027 // catch.dispatch: 2028 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2029 // catch.start: 2030 // ... 2031 // ... in this BB or some other child BB dominated by this BB there will be an 2032 // invoke that points to 'next' BB as an unwind destination 2033 // 2034 // next: ; We don't need to add this to 'current' BB's successor 2035 // ... 2036 static void findWasmUnwindDestinations( 2037 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2038 BranchProbability Prob, 2039 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2040 &UnwindDests) { 2041 while (EHPadBB) { 2042 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2043 if (isa<CleanupPadInst>(Pad)) { 2044 // Stop on cleanup pads. 2045 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2046 UnwindDests.back().first->setIsEHScopeEntry(); 2047 break; 2048 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2049 // Add the catchpad handlers to the possible destinations. We don't 2050 // continue to the unwind destination of the catchswitch for wasm. 2051 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2052 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2053 UnwindDests.back().first->setIsEHScopeEntry(); 2054 } 2055 break; 2056 } else { 2057 continue; 2058 } 2059 } 2060 } 2061 2062 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2063 /// many places it could ultimately go. In the IR, we have a single unwind 2064 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2065 /// This function skips over imaginary basic blocks that hold catchswitch 2066 /// instructions, and finds all the "real" machine 2067 /// basic block destinations. As those destinations may not be successors of 2068 /// EHPadBB, here we also calculate the edge probability to those destinations. 2069 /// The passed-in Prob is the edge probability to EHPadBB. 2070 static void findUnwindDestinations( 2071 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2072 BranchProbability Prob, 2073 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2074 &UnwindDests) { 2075 EHPersonality Personality = 2076 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2077 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2078 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2079 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2080 bool IsSEH = isAsynchronousEHPersonality(Personality); 2081 2082 if (IsWasmCXX) { 2083 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2084 assert(UnwindDests.size() <= 1 && 2085 "There should be at most one unwind destination for wasm"); 2086 return; 2087 } 2088 2089 while (EHPadBB) { 2090 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2091 BasicBlock *NewEHPadBB = nullptr; 2092 if (isa<LandingPadInst>(Pad)) { 2093 // Stop on landingpads. They are not funclets. 2094 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2095 break; 2096 } else if (isa<CleanupPadInst>(Pad)) { 2097 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2098 // personalities. 2099 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2100 UnwindDests.back().first->setIsEHScopeEntry(); 2101 UnwindDests.back().first->setIsEHFuncletEntry(); 2102 break; 2103 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2104 // Add the catchpad handlers to the possible destinations. 2105 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2106 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2107 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2108 if (IsMSVCCXX || IsCoreCLR) 2109 UnwindDests.back().first->setIsEHFuncletEntry(); 2110 if (!IsSEH) 2111 UnwindDests.back().first->setIsEHScopeEntry(); 2112 } 2113 NewEHPadBB = CatchSwitch->getUnwindDest(); 2114 } else { 2115 continue; 2116 } 2117 2118 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2119 if (BPI && NewEHPadBB) 2120 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2121 EHPadBB = NewEHPadBB; 2122 } 2123 } 2124 2125 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2126 // Update successor info. 2127 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2128 auto UnwindDest = I.getUnwindDest(); 2129 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2130 BranchProbability UnwindDestProb = 2131 (BPI && UnwindDest) 2132 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2133 : BranchProbability::getZero(); 2134 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2135 for (auto &UnwindDest : UnwindDests) { 2136 UnwindDest.first->setIsEHPad(); 2137 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2138 } 2139 FuncInfo.MBB->normalizeSuccProbs(); 2140 2141 // Create the terminator node. 2142 SDValue Ret = 2143 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2144 DAG.setRoot(Ret); 2145 } 2146 2147 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2148 report_fatal_error("visitCatchSwitch not yet implemented!"); 2149 } 2150 2151 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2152 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2153 auto &DL = DAG.getDataLayout(); 2154 SDValue Chain = getControlRoot(); 2155 SmallVector<ISD::OutputArg, 8> Outs; 2156 SmallVector<SDValue, 8> OutVals; 2157 2158 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2159 // lower 2160 // 2161 // %val = call <ty> @llvm.experimental.deoptimize() 2162 // ret <ty> %val 2163 // 2164 // differently. 2165 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2166 LowerDeoptimizingReturn(); 2167 return; 2168 } 2169 2170 if (!FuncInfo.CanLowerReturn) { 2171 unsigned DemoteReg = FuncInfo.DemoteRegister; 2172 const Function *F = I.getParent()->getParent(); 2173 2174 // Emit a store of the return value through the virtual register. 2175 // Leave Outs empty so that LowerReturn won't try to load return 2176 // registers the usual way. 2177 SmallVector<EVT, 1> PtrValueVTs; 2178 ComputeValueVTs(TLI, DL, 2179 PointerType::get(F->getContext(), 2180 DAG.getDataLayout().getAllocaAddrSpace()), 2181 PtrValueVTs); 2182 2183 SDValue RetPtr = 2184 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2185 SDValue RetOp = getValue(I.getOperand(0)); 2186 2187 SmallVector<EVT, 4> ValueVTs, MemVTs; 2188 SmallVector<uint64_t, 4> Offsets; 2189 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2190 &Offsets, 0); 2191 unsigned NumValues = ValueVTs.size(); 2192 2193 SmallVector<SDValue, 4> Chains(NumValues); 2194 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2195 for (unsigned i = 0; i != NumValues; ++i) { 2196 // An aggregate return value cannot wrap around the address space, so 2197 // offsets to its parts don't wrap either. 2198 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2199 TypeSize::getFixed(Offsets[i])); 2200 2201 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2202 if (MemVTs[i] != ValueVTs[i]) 2203 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2204 Chains[i] = DAG.getStore( 2205 Chain, getCurSDLoc(), Val, 2206 // FIXME: better loc info would be nice. 2207 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2208 commonAlignment(BaseAlign, Offsets[i])); 2209 } 2210 2211 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2212 MVT::Other, Chains); 2213 } else if (I.getNumOperands() != 0) { 2214 SmallVector<EVT, 4> ValueVTs; 2215 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2216 unsigned NumValues = ValueVTs.size(); 2217 if (NumValues) { 2218 SDValue RetOp = getValue(I.getOperand(0)); 2219 2220 const Function *F = I.getParent()->getParent(); 2221 2222 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2223 I.getOperand(0)->getType(), F->getCallingConv(), 2224 /*IsVarArg*/ false, DL); 2225 2226 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2227 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2228 ExtendKind = ISD::SIGN_EXTEND; 2229 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2230 ExtendKind = ISD::ZERO_EXTEND; 2231 2232 LLVMContext &Context = F->getContext(); 2233 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2234 2235 for (unsigned j = 0; j != NumValues; ++j) { 2236 EVT VT = ValueVTs[j]; 2237 2238 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2239 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2240 2241 CallingConv::ID CC = F->getCallingConv(); 2242 2243 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2244 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2245 SmallVector<SDValue, 4> Parts(NumParts); 2246 getCopyToParts(DAG, getCurSDLoc(), 2247 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2248 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2249 2250 // 'inreg' on function refers to return value 2251 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2252 if (RetInReg) 2253 Flags.setInReg(); 2254 2255 if (I.getOperand(0)->getType()->isPointerTy()) { 2256 Flags.setPointer(); 2257 Flags.setPointerAddrSpace( 2258 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2259 } 2260 2261 if (NeedsRegBlock) { 2262 Flags.setInConsecutiveRegs(); 2263 if (j == NumValues - 1) 2264 Flags.setInConsecutiveRegsLast(); 2265 } 2266 2267 // Propagate extension type if any 2268 if (ExtendKind == ISD::SIGN_EXTEND) 2269 Flags.setSExt(); 2270 else if (ExtendKind == ISD::ZERO_EXTEND) 2271 Flags.setZExt(); 2272 2273 for (unsigned i = 0; i < NumParts; ++i) { 2274 Outs.push_back(ISD::OutputArg(Flags, 2275 Parts[i].getValueType().getSimpleVT(), 2276 VT, /*isfixed=*/true, 0, 0)); 2277 OutVals.push_back(Parts[i]); 2278 } 2279 } 2280 } 2281 } 2282 2283 // Push in swifterror virtual register as the last element of Outs. This makes 2284 // sure swifterror virtual register will be returned in the swifterror 2285 // physical register. 2286 const Function *F = I.getParent()->getParent(); 2287 if (TLI.supportSwiftError() && 2288 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2289 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2290 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2291 Flags.setSwiftError(); 2292 Outs.push_back(ISD::OutputArg( 2293 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2294 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2295 // Create SDNode for the swifterror virtual register. 2296 OutVals.push_back( 2297 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2298 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2299 EVT(TLI.getPointerTy(DL)))); 2300 } 2301 2302 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2303 CallingConv::ID CallConv = 2304 DAG.getMachineFunction().getFunction().getCallingConv(); 2305 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2306 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2307 2308 // Verify that the target's LowerReturn behaved as expected. 2309 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2310 "LowerReturn didn't return a valid chain!"); 2311 2312 // Update the DAG with the new chain value resulting from return lowering. 2313 DAG.setRoot(Chain); 2314 } 2315 2316 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2317 /// created for it, emit nodes to copy the value into the virtual 2318 /// registers. 2319 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2320 // Skip empty types 2321 if (V->getType()->isEmptyTy()) 2322 return; 2323 2324 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2325 if (VMI != FuncInfo.ValueMap.end()) { 2326 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2327 "Unused value assigned virtual registers!"); 2328 CopyValueToVirtualRegister(V, VMI->second); 2329 } 2330 } 2331 2332 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2333 /// the current basic block, add it to ValueMap now so that we'll get a 2334 /// CopyTo/FromReg. 2335 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2336 // No need to export constants. 2337 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2338 2339 // Already exported? 2340 if (FuncInfo.isExportedInst(V)) return; 2341 2342 Register Reg = FuncInfo.InitializeRegForValue(V); 2343 CopyValueToVirtualRegister(V, Reg); 2344 } 2345 2346 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2347 const BasicBlock *FromBB) { 2348 // The operands of the setcc have to be in this block. We don't know 2349 // how to export them from some other block. 2350 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2351 // Can export from current BB. 2352 if (VI->getParent() == FromBB) 2353 return true; 2354 2355 // Is already exported, noop. 2356 return FuncInfo.isExportedInst(V); 2357 } 2358 2359 // If this is an argument, we can export it if the BB is the entry block or 2360 // if it is already exported. 2361 if (isa<Argument>(V)) { 2362 if (FromBB->isEntryBlock()) 2363 return true; 2364 2365 // Otherwise, can only export this if it is already exported. 2366 return FuncInfo.isExportedInst(V); 2367 } 2368 2369 // Otherwise, constants can always be exported. 2370 return true; 2371 } 2372 2373 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2374 BranchProbability 2375 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2376 const MachineBasicBlock *Dst) const { 2377 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2378 const BasicBlock *SrcBB = Src->getBasicBlock(); 2379 const BasicBlock *DstBB = Dst->getBasicBlock(); 2380 if (!BPI) { 2381 // If BPI is not available, set the default probability as 1 / N, where N is 2382 // the number of successors. 2383 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2384 return BranchProbability(1, SuccSize); 2385 } 2386 return BPI->getEdgeProbability(SrcBB, DstBB); 2387 } 2388 2389 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2390 MachineBasicBlock *Dst, 2391 BranchProbability Prob) { 2392 if (!FuncInfo.BPI) 2393 Src->addSuccessorWithoutProb(Dst); 2394 else { 2395 if (Prob.isUnknown()) 2396 Prob = getEdgeProbability(Src, Dst); 2397 Src->addSuccessor(Dst, Prob); 2398 } 2399 } 2400 2401 static bool InBlock(const Value *V, const BasicBlock *BB) { 2402 if (const Instruction *I = dyn_cast<Instruction>(V)) 2403 return I->getParent() == BB; 2404 return true; 2405 } 2406 2407 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2408 /// This function emits a branch and is used at the leaves of an OR or an 2409 /// AND operator tree. 2410 void 2411 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2412 MachineBasicBlock *TBB, 2413 MachineBasicBlock *FBB, 2414 MachineBasicBlock *CurBB, 2415 MachineBasicBlock *SwitchBB, 2416 BranchProbability TProb, 2417 BranchProbability FProb, 2418 bool InvertCond) { 2419 const BasicBlock *BB = CurBB->getBasicBlock(); 2420 2421 // If the leaf of the tree is a comparison, merge the condition into 2422 // the caseblock. 2423 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2424 // The operands of the cmp have to be in this block. We don't know 2425 // how to export them from some other block. If this is the first block 2426 // of the sequence, no exporting is needed. 2427 if (CurBB == SwitchBB || 2428 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2429 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2430 ISD::CondCode Condition; 2431 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2432 ICmpInst::Predicate Pred = 2433 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2434 Condition = getICmpCondCode(Pred); 2435 } else { 2436 const FCmpInst *FC = cast<FCmpInst>(Cond); 2437 FCmpInst::Predicate Pred = 2438 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2439 Condition = getFCmpCondCode(Pred); 2440 if (TM.Options.NoNaNsFPMath) 2441 Condition = getFCmpCodeWithoutNaN(Condition); 2442 } 2443 2444 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2445 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2446 SL->SwitchCases.push_back(CB); 2447 return; 2448 } 2449 } 2450 2451 // Create a CaseBlock record representing this branch. 2452 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2453 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2454 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2455 SL->SwitchCases.push_back(CB); 2456 } 2457 2458 // Collect dependencies on V recursively. This is used for the cost analysis in 2459 // `shouldKeepJumpConditionsTogether`. 2460 static bool collectInstructionDeps( 2461 SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V, 2462 SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr, 2463 unsigned Depth = 0) { 2464 // Return false if we have an incomplete count. 2465 if (Depth >= SelectionDAG::MaxRecursionDepth) 2466 return false; 2467 2468 auto *I = dyn_cast<Instruction>(V); 2469 if (I == nullptr) 2470 return true; 2471 2472 if (Necessary != nullptr) { 2473 // This instruction is necessary for the other side of the condition so 2474 // don't count it. 2475 if (Necessary->contains(I)) 2476 return true; 2477 } 2478 2479 // Already added this dep. 2480 if (!Deps->try_emplace(I, false).second) 2481 return true; 2482 2483 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx) 2484 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary, 2485 Depth + 1)) 2486 return false; 2487 return true; 2488 } 2489 2490 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether( 2491 const FunctionLoweringInfo &FuncInfo, const BranchInst &I, 2492 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, 2493 TargetLoweringBase::CondMergingParams Params) const { 2494 if (I.getNumSuccessors() != 2) 2495 return false; 2496 2497 if (!I.isConditional()) 2498 return false; 2499 2500 if (Params.BaseCost < 0) 2501 return false; 2502 2503 // Baseline cost. 2504 InstructionCost CostThresh = Params.BaseCost; 2505 2506 BranchProbabilityInfo *BPI = nullptr; 2507 if (Params.LikelyBias || Params.UnlikelyBias) 2508 BPI = FuncInfo.BPI; 2509 if (BPI != nullptr) { 2510 // See if we are either likely to get an early out or compute both lhs/rhs 2511 // of the condition. 2512 BasicBlock *IfFalse = I.getSuccessor(0); 2513 BasicBlock *IfTrue = I.getSuccessor(1); 2514 2515 std::optional<bool> Likely; 2516 if (BPI->isEdgeHot(I.getParent(), IfTrue)) 2517 Likely = true; 2518 else if (BPI->isEdgeHot(I.getParent(), IfFalse)) 2519 Likely = false; 2520 2521 if (Likely) { 2522 if (Opc == (*Likely ? Instruction::And : Instruction::Or)) 2523 // Its likely we will have to compute both lhs and rhs of condition 2524 CostThresh += Params.LikelyBias; 2525 else { 2526 if (Params.UnlikelyBias < 0) 2527 return false; 2528 // Its likely we will get an early out. 2529 CostThresh -= Params.UnlikelyBias; 2530 } 2531 } 2532 } 2533 2534 if (CostThresh <= 0) 2535 return false; 2536 2537 // Collect "all" instructions that lhs condition is dependent on. 2538 // Use map for stable iteration (to avoid non-determanism of iteration of 2539 // SmallPtrSet). The `bool` value is just a dummy. 2540 SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps; 2541 collectInstructionDeps(&LhsDeps, Lhs); 2542 // Collect "all" instructions that rhs condition is dependent on AND are 2543 // dependencies of lhs. This gives us an estimate on which instructions we 2544 // stand to save by splitting the condition. 2545 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps)) 2546 return false; 2547 // Add the compare instruction itself unless its a dependency on the LHS. 2548 if (const auto *RhsI = dyn_cast<Instruction>(Rhs)) 2549 if (!LhsDeps.contains(RhsI)) 2550 RhsDeps.try_emplace(RhsI, false); 2551 2552 const auto &TLI = DAG.getTargetLoweringInfo(); 2553 const auto &TTI = 2554 TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction()); 2555 2556 InstructionCost CostOfIncluding = 0; 2557 // See if this instruction will need to computed independently of whether RHS 2558 // is. 2559 Value *BrCond = I.getCondition(); 2560 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) { 2561 for (const auto *U : Ins->users()) { 2562 // If user is independent of RHS calculation we don't need to count it. 2563 if (auto *UIns = dyn_cast<Instruction>(U)) 2564 if (UIns != BrCond && !RhsDeps.contains(UIns)) 2565 return false; 2566 } 2567 return true; 2568 }; 2569 2570 // Prune instructions from RHS Deps that are dependencies of unrelated 2571 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly 2572 // arbitrary and just meant to cap the how much time we spend in the pruning 2573 // loop. Its highly unlikely to come into affect. 2574 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth; 2575 // Stop after a certain point. No incorrectness from including too many 2576 // instructions. 2577 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) { 2578 const Instruction *ToDrop = nullptr; 2579 for (const auto &InsPair : RhsDeps) { 2580 if (!ShouldCountInsn(InsPair.first)) { 2581 ToDrop = InsPair.first; 2582 break; 2583 } 2584 } 2585 if (ToDrop == nullptr) 2586 break; 2587 RhsDeps.erase(ToDrop); 2588 } 2589 2590 for (const auto &InsPair : RhsDeps) { 2591 // Finally accumulate latency that we can only attribute to computing the 2592 // RHS condition. Use latency because we are essentially trying to calculate 2593 // the cost of the dependency chain. 2594 // Possible TODO: We could try to estimate ILP and make this more precise. 2595 CostOfIncluding += 2596 TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency); 2597 2598 if (CostOfIncluding > CostThresh) 2599 return false; 2600 } 2601 return true; 2602 } 2603 2604 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2605 MachineBasicBlock *TBB, 2606 MachineBasicBlock *FBB, 2607 MachineBasicBlock *CurBB, 2608 MachineBasicBlock *SwitchBB, 2609 Instruction::BinaryOps Opc, 2610 BranchProbability TProb, 2611 BranchProbability FProb, 2612 bool InvertCond) { 2613 // Skip over not part of the tree and remember to invert op and operands at 2614 // next level. 2615 Value *NotCond; 2616 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2617 InBlock(NotCond, CurBB->getBasicBlock())) { 2618 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2619 !InvertCond); 2620 return; 2621 } 2622 2623 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2624 const Value *BOpOp0, *BOpOp1; 2625 // Compute the effective opcode for Cond, taking into account whether it needs 2626 // to be inverted, e.g. 2627 // and (not (or A, B)), C 2628 // gets lowered as 2629 // and (and (not A, not B), C) 2630 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2631 if (BOp) { 2632 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2633 ? Instruction::And 2634 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2635 ? Instruction::Or 2636 : (Instruction::BinaryOps)0); 2637 if (InvertCond) { 2638 if (BOpc == Instruction::And) 2639 BOpc = Instruction::Or; 2640 else if (BOpc == Instruction::Or) 2641 BOpc = Instruction::And; 2642 } 2643 } 2644 2645 // If this node is not part of the or/and tree, emit it as a branch. 2646 // Note that all nodes in the tree should have same opcode. 2647 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2648 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2649 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2650 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2651 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2652 TProb, FProb, InvertCond); 2653 return; 2654 } 2655 2656 // Create TmpBB after CurBB. 2657 MachineFunction::iterator BBI(CurBB); 2658 MachineFunction &MF = DAG.getMachineFunction(); 2659 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2660 CurBB->getParent()->insert(++BBI, TmpBB); 2661 2662 if (Opc == Instruction::Or) { 2663 // Codegen X | Y as: 2664 // BB1: 2665 // jmp_if_X TBB 2666 // jmp TmpBB 2667 // TmpBB: 2668 // jmp_if_Y TBB 2669 // jmp FBB 2670 // 2671 2672 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2673 // The requirement is that 2674 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2675 // = TrueProb for original BB. 2676 // Assuming the original probabilities are A and B, one choice is to set 2677 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2678 // A/(1+B) and 2B/(1+B). This choice assumes that 2679 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2680 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2681 // TmpBB, but the math is more complicated. 2682 2683 auto NewTrueProb = TProb / 2; 2684 auto NewFalseProb = TProb / 2 + FProb; 2685 // Emit the LHS condition. 2686 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2687 NewFalseProb, InvertCond); 2688 2689 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2690 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2691 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2692 // Emit the RHS condition into TmpBB. 2693 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2694 Probs[1], InvertCond); 2695 } else { 2696 assert(Opc == Instruction::And && "Unknown merge op!"); 2697 // Codegen X & Y as: 2698 // BB1: 2699 // jmp_if_X TmpBB 2700 // jmp FBB 2701 // TmpBB: 2702 // jmp_if_Y TBB 2703 // jmp FBB 2704 // 2705 // This requires creation of TmpBB after CurBB. 2706 2707 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2708 // The requirement is that 2709 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2710 // = FalseProb for original BB. 2711 // Assuming the original probabilities are A and B, one choice is to set 2712 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2713 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2714 // TrueProb for BB1 * FalseProb for TmpBB. 2715 2716 auto NewTrueProb = TProb + FProb / 2; 2717 auto NewFalseProb = FProb / 2; 2718 // Emit the LHS condition. 2719 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2720 NewFalseProb, InvertCond); 2721 2722 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2723 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2724 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2725 // Emit the RHS condition into TmpBB. 2726 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2727 Probs[1], InvertCond); 2728 } 2729 } 2730 2731 /// If the set of cases should be emitted as a series of branches, return true. 2732 /// If we should emit this as a bunch of and/or'd together conditions, return 2733 /// false. 2734 bool 2735 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2736 if (Cases.size() != 2) return true; 2737 2738 // If this is two comparisons of the same values or'd or and'd together, they 2739 // will get folded into a single comparison, so don't emit two blocks. 2740 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2741 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2742 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2743 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2744 return false; 2745 } 2746 2747 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2748 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2749 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2750 Cases[0].CC == Cases[1].CC && 2751 isa<Constant>(Cases[0].CmpRHS) && 2752 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2753 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2754 return false; 2755 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2756 return false; 2757 } 2758 2759 return true; 2760 } 2761 2762 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2763 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2764 2765 // Update machine-CFG edges. 2766 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2767 2768 if (I.isUnconditional()) { 2769 // Update machine-CFG edges. 2770 BrMBB->addSuccessor(Succ0MBB); 2771 2772 // If this is not a fall-through branch or optimizations are switched off, 2773 // emit the branch. 2774 if (Succ0MBB != NextBlock(BrMBB) || 2775 TM.getOptLevel() == CodeGenOptLevel::None) { 2776 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2777 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2778 setValue(&I, Br); 2779 DAG.setRoot(Br); 2780 } 2781 2782 return; 2783 } 2784 2785 // If this condition is one of the special cases we handle, do special stuff 2786 // now. 2787 const Value *CondVal = I.getCondition(); 2788 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2789 2790 // If this is a series of conditions that are or'd or and'd together, emit 2791 // this as a sequence of branches instead of setcc's with and/or operations. 2792 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2793 // unpredictable branches, and vector extracts because those jumps are likely 2794 // expensive for any target), this should improve performance. 2795 // For example, instead of something like: 2796 // cmp A, B 2797 // C = seteq 2798 // cmp D, E 2799 // F = setle 2800 // or C, F 2801 // jnz foo 2802 // Emit: 2803 // cmp A, B 2804 // je foo 2805 // cmp D, E 2806 // jle foo 2807 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2808 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2809 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2810 Value *Vec; 2811 const Value *BOp0, *BOp1; 2812 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2813 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2814 Opcode = Instruction::And; 2815 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2816 Opcode = Instruction::Or; 2817 2818 if (Opcode && 2819 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2820 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) && 2821 !shouldKeepJumpConditionsTogether( 2822 FuncInfo, I, Opcode, BOp0, BOp1, 2823 DAG.getTargetLoweringInfo().getJumpConditionMergingParams( 2824 Opcode, BOp0, BOp1))) { 2825 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2826 getEdgeProbability(BrMBB, Succ0MBB), 2827 getEdgeProbability(BrMBB, Succ1MBB), 2828 /*InvertCond=*/false); 2829 // If the compares in later blocks need to use values not currently 2830 // exported from this block, export them now. This block should always 2831 // be the first entry. 2832 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2833 2834 // Allow some cases to be rejected. 2835 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2836 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2837 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2838 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2839 } 2840 2841 // Emit the branch for this block. 2842 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2843 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2844 return; 2845 } 2846 2847 // Okay, we decided not to do this, remove any inserted MBB's and clear 2848 // SwitchCases. 2849 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2850 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2851 2852 SL->SwitchCases.clear(); 2853 } 2854 } 2855 2856 // Create a CaseBlock record representing this branch. 2857 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2858 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2859 2860 // Use visitSwitchCase to actually insert the fast branch sequence for this 2861 // cond branch. 2862 visitSwitchCase(CB, BrMBB); 2863 } 2864 2865 /// visitSwitchCase - Emits the necessary code to represent a single node in 2866 /// the binary search tree resulting from lowering a switch instruction. 2867 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2868 MachineBasicBlock *SwitchBB) { 2869 SDValue Cond; 2870 SDValue CondLHS = getValue(CB.CmpLHS); 2871 SDLoc dl = CB.DL; 2872 2873 if (CB.CC == ISD::SETTRUE) { 2874 // Branch or fall through to TrueBB. 2875 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2876 SwitchBB->normalizeSuccProbs(); 2877 if (CB.TrueBB != NextBlock(SwitchBB)) { 2878 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2879 DAG.getBasicBlock(CB.TrueBB))); 2880 } 2881 return; 2882 } 2883 2884 auto &TLI = DAG.getTargetLoweringInfo(); 2885 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2886 2887 // Build the setcc now. 2888 if (!CB.CmpMHS) { 2889 // Fold "(X == true)" to X and "(X == false)" to !X to 2890 // handle common cases produced by branch lowering. 2891 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2892 CB.CC == ISD::SETEQ) 2893 Cond = CondLHS; 2894 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2895 CB.CC == ISD::SETEQ) { 2896 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2897 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2898 } else { 2899 SDValue CondRHS = getValue(CB.CmpRHS); 2900 2901 // If a pointer's DAG type is larger than its memory type then the DAG 2902 // values are zero-extended. This breaks signed comparisons so truncate 2903 // back to the underlying type before doing the compare. 2904 if (CondLHS.getValueType() != MemVT) { 2905 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2906 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2907 } 2908 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2909 } 2910 } else { 2911 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2912 2913 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2914 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2915 2916 SDValue CmpOp = getValue(CB.CmpMHS); 2917 EVT VT = CmpOp.getValueType(); 2918 2919 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2920 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2921 ISD::SETLE); 2922 } else { 2923 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2924 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2925 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2926 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2927 } 2928 } 2929 2930 // Update successor info 2931 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2932 // TrueBB and FalseBB are always different unless the incoming IR is 2933 // degenerate. This only happens when running llc on weird IR. 2934 if (CB.TrueBB != CB.FalseBB) 2935 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2936 SwitchBB->normalizeSuccProbs(); 2937 2938 // If the lhs block is the next block, invert the condition so that we can 2939 // fall through to the lhs instead of the rhs block. 2940 if (CB.TrueBB == NextBlock(SwitchBB)) { 2941 std::swap(CB.TrueBB, CB.FalseBB); 2942 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2943 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2944 } 2945 2946 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2947 MVT::Other, getControlRoot(), Cond, 2948 DAG.getBasicBlock(CB.TrueBB)); 2949 2950 setValue(CurInst, BrCond); 2951 2952 // Insert the false branch. Do this even if it's a fall through branch, 2953 // this makes it easier to do DAG optimizations which require inverting 2954 // the branch condition. 2955 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2956 DAG.getBasicBlock(CB.FalseBB)); 2957 2958 DAG.setRoot(BrCond); 2959 } 2960 2961 /// visitJumpTable - Emit JumpTable node in the current MBB 2962 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2963 // Emit the code for the jump table 2964 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2965 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2966 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2967 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2968 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2969 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2970 Index.getValue(1), Table, Index); 2971 DAG.setRoot(BrJumpTable); 2972 } 2973 2974 /// visitJumpTableHeader - This function emits necessary code to produce index 2975 /// in the JumpTable from switch case. 2976 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2977 JumpTableHeader &JTH, 2978 MachineBasicBlock *SwitchBB) { 2979 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2980 const SDLoc &dl = *JT.SL; 2981 2982 // Subtract the lowest switch case value from the value being switched on. 2983 SDValue SwitchOp = getValue(JTH.SValue); 2984 EVT VT = SwitchOp.getValueType(); 2985 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2986 DAG.getConstant(JTH.First, dl, VT)); 2987 2988 // The SDNode we just created, which holds the value being switched on minus 2989 // the smallest case value, needs to be copied to a virtual register so it 2990 // can be used as an index into the jump table in a subsequent basic block. 2991 // This value may be smaller or larger than the target's pointer type, and 2992 // therefore require extension or truncating. 2993 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2994 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2995 2996 unsigned JumpTableReg = 2997 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2998 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2999 JumpTableReg, SwitchOp); 3000 JT.Reg = JumpTableReg; 3001 3002 if (!JTH.FallthroughUnreachable) { 3003 // Emit the range check for the jump table, and branch to the default block 3004 // for the switch statement if the value being switched on exceeds the 3005 // largest case in the switch. 3006 SDValue CMP = DAG.getSetCC( 3007 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3008 Sub.getValueType()), 3009 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 3010 3011 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3012 MVT::Other, CopyTo, CMP, 3013 DAG.getBasicBlock(JT.Default)); 3014 3015 // Avoid emitting unnecessary branches to the next block. 3016 if (JT.MBB != NextBlock(SwitchBB)) 3017 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 3018 DAG.getBasicBlock(JT.MBB)); 3019 3020 DAG.setRoot(BrCond); 3021 } else { 3022 // Avoid emitting unnecessary branches to the next block. 3023 if (JT.MBB != NextBlock(SwitchBB)) 3024 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 3025 DAG.getBasicBlock(JT.MBB))); 3026 else 3027 DAG.setRoot(CopyTo); 3028 } 3029 } 3030 3031 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 3032 /// variable if there exists one. 3033 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 3034 SDValue &Chain) { 3035 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3036 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3037 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3038 MachineFunction &MF = DAG.getMachineFunction(); 3039 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 3040 MachineSDNode *Node = 3041 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 3042 if (Global) { 3043 MachinePointerInfo MPInfo(Global); 3044 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 3045 MachineMemOperand::MODereferenceable; 3046 MachineMemOperand *MemRef = MF.getMachineMemOperand( 3047 MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8), 3048 DAG.getEVTAlign(PtrTy)); 3049 DAG.setNodeMemRefs(Node, {MemRef}); 3050 } 3051 if (PtrTy != PtrMemTy) 3052 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 3053 return SDValue(Node, 0); 3054 } 3055 3056 /// Codegen a new tail for a stack protector check ParentMBB which has had its 3057 /// tail spliced into a stack protector check success bb. 3058 /// 3059 /// For a high level explanation of how this fits into the stack protector 3060 /// generation see the comment on the declaration of class 3061 /// StackProtectorDescriptor. 3062 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 3063 MachineBasicBlock *ParentBB) { 3064 3065 // First create the loads to the guard/stack slot for the comparison. 3066 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3067 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 3068 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 3069 3070 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 3071 int FI = MFI.getStackProtectorIndex(); 3072 3073 SDValue Guard; 3074 SDLoc dl = getCurSDLoc(); 3075 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 3076 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 3077 Align Align = 3078 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 3079 3080 // Generate code to load the content of the guard slot. 3081 SDValue GuardVal = DAG.getLoad( 3082 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 3083 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 3084 MachineMemOperand::MOVolatile); 3085 3086 if (TLI.useStackGuardXorFP()) 3087 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 3088 3089 // Retrieve guard check function, nullptr if instrumentation is inlined. 3090 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 3091 // The target provides a guard check function to validate the guard value. 3092 // Generate a call to that function with the content of the guard slot as 3093 // argument. 3094 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 3095 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 3096 3097 TargetLowering::ArgListTy Args; 3098 TargetLowering::ArgListEntry Entry; 3099 Entry.Node = GuardVal; 3100 Entry.Ty = FnTy->getParamType(0); 3101 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 3102 Entry.IsInReg = true; 3103 Args.push_back(Entry); 3104 3105 TargetLowering::CallLoweringInfo CLI(DAG); 3106 CLI.setDebugLoc(getCurSDLoc()) 3107 .setChain(DAG.getEntryNode()) 3108 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 3109 getValue(GuardCheckFn), std::move(Args)); 3110 3111 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 3112 DAG.setRoot(Result.second); 3113 return; 3114 } 3115 3116 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 3117 // Otherwise, emit a volatile load to retrieve the stack guard value. 3118 SDValue Chain = DAG.getEntryNode(); 3119 if (TLI.useLoadStackGuardNode()) { 3120 Guard = getLoadStackGuard(DAG, dl, Chain); 3121 } else { 3122 const Value *IRGuard = TLI.getSDagStackGuard(M); 3123 SDValue GuardPtr = getValue(IRGuard); 3124 3125 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 3126 MachinePointerInfo(IRGuard, 0), Align, 3127 MachineMemOperand::MOVolatile); 3128 } 3129 3130 // Perform the comparison via a getsetcc. 3131 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 3132 *DAG.getContext(), 3133 Guard.getValueType()), 3134 Guard, GuardVal, ISD::SETNE); 3135 3136 // If the guard/stackslot do not equal, branch to failure MBB. 3137 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 3138 MVT::Other, GuardVal.getOperand(0), 3139 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 3140 // Otherwise branch to success MBB. 3141 SDValue Br = DAG.getNode(ISD::BR, dl, 3142 MVT::Other, BrCond, 3143 DAG.getBasicBlock(SPD.getSuccessMBB())); 3144 3145 DAG.setRoot(Br); 3146 } 3147 3148 /// Codegen the failure basic block for a stack protector check. 3149 /// 3150 /// A failure stack protector machine basic block consists simply of a call to 3151 /// __stack_chk_fail(). 3152 /// 3153 /// For a high level explanation of how this fits into the stack protector 3154 /// generation see the comment on the declaration of class 3155 /// StackProtectorDescriptor. 3156 void 3157 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 3158 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3159 TargetLowering::MakeLibCallOptions CallOptions; 3160 CallOptions.setDiscardResult(true); 3161 SDValue Chain = 3162 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 3163 std::nullopt, CallOptions, getCurSDLoc()) 3164 .second; 3165 // On PS4/PS5, the "return address" must still be within the calling 3166 // function, even if it's at the very end, so emit an explicit TRAP here. 3167 // Passing 'true' for doesNotReturn above won't generate the trap for us. 3168 if (TM.getTargetTriple().isPS()) 3169 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3170 // WebAssembly needs an unreachable instruction after a non-returning call, 3171 // because the function return type can be different from __stack_chk_fail's 3172 // return type (void). 3173 if (TM.getTargetTriple().isWasm()) 3174 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3175 3176 DAG.setRoot(Chain); 3177 } 3178 3179 /// visitBitTestHeader - This function emits necessary code to produce value 3180 /// suitable for "bit tests" 3181 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3182 MachineBasicBlock *SwitchBB) { 3183 SDLoc dl = getCurSDLoc(); 3184 3185 // Subtract the minimum value. 3186 SDValue SwitchOp = getValue(B.SValue); 3187 EVT VT = SwitchOp.getValueType(); 3188 SDValue RangeSub = 3189 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3190 3191 // Determine the type of the test operands. 3192 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3193 bool UsePtrType = false; 3194 if (!TLI.isTypeLegal(VT)) { 3195 UsePtrType = true; 3196 } else { 3197 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3198 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3199 // Switch table case range are encoded into series of masks. 3200 // Just use pointer type, it's guaranteed to fit. 3201 UsePtrType = true; 3202 break; 3203 } 3204 } 3205 SDValue Sub = RangeSub; 3206 if (UsePtrType) { 3207 VT = TLI.getPointerTy(DAG.getDataLayout()); 3208 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3209 } 3210 3211 B.RegVT = VT.getSimpleVT(); 3212 B.Reg = FuncInfo.CreateReg(B.RegVT); 3213 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3214 3215 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3216 3217 if (!B.FallthroughUnreachable) 3218 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3219 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3220 SwitchBB->normalizeSuccProbs(); 3221 3222 SDValue Root = CopyTo; 3223 if (!B.FallthroughUnreachable) { 3224 // Conditional branch to the default block. 3225 SDValue RangeCmp = DAG.getSetCC(dl, 3226 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3227 RangeSub.getValueType()), 3228 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3229 ISD::SETUGT); 3230 3231 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3232 DAG.getBasicBlock(B.Default)); 3233 } 3234 3235 // Avoid emitting unnecessary branches to the next block. 3236 if (MBB != NextBlock(SwitchBB)) 3237 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3238 3239 DAG.setRoot(Root); 3240 } 3241 3242 /// visitBitTestCase - this function produces one "bit test" 3243 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3244 MachineBasicBlock* NextMBB, 3245 BranchProbability BranchProbToNext, 3246 unsigned Reg, 3247 BitTestCase &B, 3248 MachineBasicBlock *SwitchBB) { 3249 SDLoc dl = getCurSDLoc(); 3250 MVT VT = BB.RegVT; 3251 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3252 SDValue Cmp; 3253 unsigned PopCount = llvm::popcount(B.Mask); 3254 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3255 if (PopCount == 1) { 3256 // Testing for a single bit; just compare the shift count with what it 3257 // would need to be to shift a 1 bit in that position. 3258 Cmp = DAG.getSetCC( 3259 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3260 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3261 ISD::SETEQ); 3262 } else if (PopCount == BB.Range) { 3263 // There is only one zero bit in the range, test for it directly. 3264 Cmp = DAG.getSetCC( 3265 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3266 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3267 } else { 3268 // Make desired shift 3269 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3270 DAG.getConstant(1, dl, VT), ShiftOp); 3271 3272 // Emit bit tests and jumps 3273 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3274 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3275 Cmp = DAG.getSetCC( 3276 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3277 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3278 } 3279 3280 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3281 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3282 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3283 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3284 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3285 // one as they are relative probabilities (and thus work more like weights), 3286 // and hence we need to normalize them to let the sum of them become one. 3287 SwitchBB->normalizeSuccProbs(); 3288 3289 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3290 MVT::Other, getControlRoot(), 3291 Cmp, DAG.getBasicBlock(B.TargetBB)); 3292 3293 // Avoid emitting unnecessary branches to the next block. 3294 if (NextMBB != NextBlock(SwitchBB)) 3295 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3296 DAG.getBasicBlock(NextMBB)); 3297 3298 DAG.setRoot(BrAnd); 3299 } 3300 3301 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3302 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3303 3304 // Retrieve successors. Look through artificial IR level blocks like 3305 // catchswitch for successors. 3306 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3307 const BasicBlock *EHPadBB = I.getSuccessor(1); 3308 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3309 3310 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3311 // have to do anything here to lower funclet bundles. 3312 assert(!I.hasOperandBundlesOtherThan( 3313 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3314 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3315 LLVMContext::OB_cfguardtarget, 3316 LLVMContext::OB_clang_arc_attachedcall}) && 3317 "Cannot lower invokes with arbitrary operand bundles yet!"); 3318 3319 const Value *Callee(I.getCalledOperand()); 3320 const Function *Fn = dyn_cast<Function>(Callee); 3321 if (isa<InlineAsm>(Callee)) 3322 visitInlineAsm(I, EHPadBB); 3323 else if (Fn && Fn->isIntrinsic()) { 3324 switch (Fn->getIntrinsicID()) { 3325 default: 3326 llvm_unreachable("Cannot invoke this intrinsic"); 3327 case Intrinsic::donothing: 3328 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3329 case Intrinsic::seh_try_begin: 3330 case Intrinsic::seh_scope_begin: 3331 case Intrinsic::seh_try_end: 3332 case Intrinsic::seh_scope_end: 3333 if (EHPadMBB) 3334 // a block referenced by EH table 3335 // so dtor-funclet not removed by opts 3336 EHPadMBB->setMachineBlockAddressTaken(); 3337 break; 3338 case Intrinsic::experimental_patchpoint_void: 3339 case Intrinsic::experimental_patchpoint: 3340 visitPatchpoint(I, EHPadBB); 3341 break; 3342 case Intrinsic::experimental_gc_statepoint: 3343 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3344 break; 3345 case Intrinsic::wasm_rethrow: { 3346 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3347 // special because it can be invoked, so we manually lower it to a DAG 3348 // node here. 3349 SmallVector<SDValue, 8> Ops; 3350 Ops.push_back(getRoot()); // inchain 3351 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3352 Ops.push_back( 3353 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3354 TLI.getPointerTy(DAG.getDataLayout()))); 3355 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3356 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3357 break; 3358 } 3359 } 3360 } else if (I.hasDeoptState()) { 3361 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3362 // Eventually we will support lowering the @llvm.experimental.deoptimize 3363 // intrinsic, and right now there are no plans to support other intrinsics 3364 // with deopt state. 3365 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3366 } else { 3367 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3368 } 3369 3370 // If the value of the invoke is used outside of its defining block, make it 3371 // available as a virtual register. 3372 // We already took care of the exported value for the statepoint instruction 3373 // during call to the LowerStatepoint. 3374 if (!isa<GCStatepointInst>(I)) { 3375 CopyToExportRegsIfNeeded(&I); 3376 } 3377 3378 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3379 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3380 BranchProbability EHPadBBProb = 3381 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3382 : BranchProbability::getZero(); 3383 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3384 3385 // Update successor info. 3386 addSuccessorWithProb(InvokeMBB, Return); 3387 for (auto &UnwindDest : UnwindDests) { 3388 UnwindDest.first->setIsEHPad(); 3389 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3390 } 3391 InvokeMBB->normalizeSuccProbs(); 3392 3393 // Drop into normal successor. 3394 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3395 DAG.getBasicBlock(Return))); 3396 } 3397 3398 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3399 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3400 3401 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3402 // have to do anything here to lower funclet bundles. 3403 assert(!I.hasOperandBundlesOtherThan( 3404 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3405 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3406 3407 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3408 visitInlineAsm(I); 3409 CopyToExportRegsIfNeeded(&I); 3410 3411 // Retrieve successors. 3412 SmallPtrSet<BasicBlock *, 8> Dests; 3413 Dests.insert(I.getDefaultDest()); 3414 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3415 3416 // Update successor info. 3417 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3418 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3419 BasicBlock *Dest = I.getIndirectDest(i); 3420 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3421 Target->setIsInlineAsmBrIndirectTarget(); 3422 Target->setMachineBlockAddressTaken(); 3423 Target->setLabelMustBeEmitted(); 3424 // Don't add duplicate machine successors. 3425 if (Dests.insert(Dest).second) 3426 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3427 } 3428 CallBrMBB->normalizeSuccProbs(); 3429 3430 // Drop into default successor. 3431 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3432 MVT::Other, getControlRoot(), 3433 DAG.getBasicBlock(Return))); 3434 } 3435 3436 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3437 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3438 } 3439 3440 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3441 assert(FuncInfo.MBB->isEHPad() && 3442 "Call to landingpad not in landing pad!"); 3443 3444 // If there aren't registers to copy the values into (e.g., during SjLj 3445 // exceptions), then don't bother to create these DAG nodes. 3446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3447 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3448 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3449 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3450 return; 3451 3452 // If landingpad's return type is token type, we don't create DAG nodes 3453 // for its exception pointer and selector value. The extraction of exception 3454 // pointer or selector value from token type landingpads is not currently 3455 // supported. 3456 if (LP.getType()->isTokenTy()) 3457 return; 3458 3459 SmallVector<EVT, 2> ValueVTs; 3460 SDLoc dl = getCurSDLoc(); 3461 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3462 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3463 3464 // Get the two live-in registers as SDValues. The physregs have already been 3465 // copied into virtual registers. 3466 SDValue Ops[2]; 3467 if (FuncInfo.ExceptionPointerVirtReg) { 3468 Ops[0] = DAG.getZExtOrTrunc( 3469 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3470 FuncInfo.ExceptionPointerVirtReg, 3471 TLI.getPointerTy(DAG.getDataLayout())), 3472 dl, ValueVTs[0]); 3473 } else { 3474 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3475 } 3476 Ops[1] = DAG.getZExtOrTrunc( 3477 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3478 FuncInfo.ExceptionSelectorVirtReg, 3479 TLI.getPointerTy(DAG.getDataLayout())), 3480 dl, ValueVTs[1]); 3481 3482 // Merge into one. 3483 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3484 DAG.getVTList(ValueVTs), Ops); 3485 setValue(&LP, Res); 3486 } 3487 3488 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3489 MachineBasicBlock *Last) { 3490 // Update JTCases. 3491 for (JumpTableBlock &JTB : SL->JTCases) 3492 if (JTB.first.HeaderBB == First) 3493 JTB.first.HeaderBB = Last; 3494 3495 // Update BitTestCases. 3496 for (BitTestBlock &BTB : SL->BitTestCases) 3497 if (BTB.Parent == First) 3498 BTB.Parent = Last; 3499 } 3500 3501 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3502 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3503 3504 // Update machine-CFG edges with unique successors. 3505 SmallSet<BasicBlock*, 32> Done; 3506 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3507 BasicBlock *BB = I.getSuccessor(i); 3508 bool Inserted = Done.insert(BB).second; 3509 if (!Inserted) 3510 continue; 3511 3512 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3513 addSuccessorWithProb(IndirectBrMBB, Succ); 3514 } 3515 IndirectBrMBB->normalizeSuccProbs(); 3516 3517 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3518 MVT::Other, getControlRoot(), 3519 getValue(I.getAddress()))); 3520 } 3521 3522 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3523 if (!DAG.getTarget().Options.TrapUnreachable) 3524 return; 3525 3526 // We may be able to ignore unreachable behind a noreturn call. 3527 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3528 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3529 if (Call->doesNotReturn()) 3530 return; 3531 } 3532 } 3533 3534 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3535 } 3536 3537 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3538 SDNodeFlags Flags; 3539 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3540 Flags.copyFMF(*FPOp); 3541 3542 SDValue Op = getValue(I.getOperand(0)); 3543 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3544 Op, Flags); 3545 setValue(&I, UnNodeValue); 3546 } 3547 3548 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3549 SDNodeFlags Flags; 3550 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3551 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3552 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3553 } 3554 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3555 Flags.setExact(ExactOp->isExact()); 3556 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3557 Flags.setDisjoint(DisjointOp->isDisjoint()); 3558 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3559 Flags.copyFMF(*FPOp); 3560 3561 SDValue Op1 = getValue(I.getOperand(0)); 3562 SDValue Op2 = getValue(I.getOperand(1)); 3563 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3564 Op1, Op2, Flags); 3565 setValue(&I, BinNodeValue); 3566 } 3567 3568 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3569 SDValue Op1 = getValue(I.getOperand(0)); 3570 SDValue Op2 = getValue(I.getOperand(1)); 3571 3572 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3573 Op1.getValueType(), DAG.getDataLayout()); 3574 3575 // Coerce the shift amount to the right type if we can. This exposes the 3576 // truncate or zext to optimization early. 3577 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3578 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3579 "Unexpected shift type"); 3580 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3581 } 3582 3583 bool nuw = false; 3584 bool nsw = false; 3585 bool exact = false; 3586 3587 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3588 3589 if (const OverflowingBinaryOperator *OFBinOp = 3590 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3591 nuw = OFBinOp->hasNoUnsignedWrap(); 3592 nsw = OFBinOp->hasNoSignedWrap(); 3593 } 3594 if (const PossiblyExactOperator *ExactOp = 3595 dyn_cast<const PossiblyExactOperator>(&I)) 3596 exact = ExactOp->isExact(); 3597 } 3598 SDNodeFlags Flags; 3599 Flags.setExact(exact); 3600 Flags.setNoSignedWrap(nsw); 3601 Flags.setNoUnsignedWrap(nuw); 3602 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3603 Flags); 3604 setValue(&I, Res); 3605 } 3606 3607 void SelectionDAGBuilder::visitSDiv(const User &I) { 3608 SDValue Op1 = getValue(I.getOperand(0)); 3609 SDValue Op2 = getValue(I.getOperand(1)); 3610 3611 SDNodeFlags Flags; 3612 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3613 cast<PossiblyExactOperator>(&I)->isExact()); 3614 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3615 Op2, Flags)); 3616 } 3617 3618 void SelectionDAGBuilder::visitICmp(const User &I) { 3619 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3620 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3621 predicate = IC->getPredicate(); 3622 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3623 predicate = ICmpInst::Predicate(IC->getPredicate()); 3624 SDValue Op1 = getValue(I.getOperand(0)); 3625 SDValue Op2 = getValue(I.getOperand(1)); 3626 ISD::CondCode Opcode = getICmpCondCode(predicate); 3627 3628 auto &TLI = DAG.getTargetLoweringInfo(); 3629 EVT MemVT = 3630 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3631 3632 // If a pointer's DAG type is larger than its memory type then the DAG values 3633 // are zero-extended. This breaks signed comparisons so truncate back to the 3634 // underlying type before doing the compare. 3635 if (Op1.getValueType() != MemVT) { 3636 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3637 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3638 } 3639 3640 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3641 I.getType()); 3642 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3643 } 3644 3645 void SelectionDAGBuilder::visitFCmp(const User &I) { 3646 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3647 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3648 predicate = FC->getPredicate(); 3649 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3650 predicate = FCmpInst::Predicate(FC->getPredicate()); 3651 SDValue Op1 = getValue(I.getOperand(0)); 3652 SDValue Op2 = getValue(I.getOperand(1)); 3653 3654 ISD::CondCode Condition = getFCmpCondCode(predicate); 3655 auto *FPMO = cast<FPMathOperator>(&I); 3656 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3657 Condition = getFCmpCodeWithoutNaN(Condition); 3658 3659 SDNodeFlags Flags; 3660 Flags.copyFMF(*FPMO); 3661 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3662 3663 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3664 I.getType()); 3665 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3666 } 3667 3668 // Check if the condition of the select has one use or two users that are both 3669 // selects with the same condition. 3670 static bool hasOnlySelectUsers(const Value *Cond) { 3671 return llvm::all_of(Cond->users(), [](const Value *V) { 3672 return isa<SelectInst>(V); 3673 }); 3674 } 3675 3676 void SelectionDAGBuilder::visitSelect(const User &I) { 3677 SmallVector<EVT, 4> ValueVTs; 3678 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3679 ValueVTs); 3680 unsigned NumValues = ValueVTs.size(); 3681 if (NumValues == 0) return; 3682 3683 SmallVector<SDValue, 4> Values(NumValues); 3684 SDValue Cond = getValue(I.getOperand(0)); 3685 SDValue LHSVal = getValue(I.getOperand(1)); 3686 SDValue RHSVal = getValue(I.getOperand(2)); 3687 SmallVector<SDValue, 1> BaseOps(1, Cond); 3688 ISD::NodeType OpCode = 3689 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3690 3691 bool IsUnaryAbs = false; 3692 bool Negate = false; 3693 3694 SDNodeFlags Flags; 3695 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3696 Flags.copyFMF(*FPOp); 3697 3698 Flags.setUnpredictable( 3699 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3700 3701 // Min/max matching is only viable if all output VTs are the same. 3702 if (all_equal(ValueVTs)) { 3703 EVT VT = ValueVTs[0]; 3704 LLVMContext &Ctx = *DAG.getContext(); 3705 auto &TLI = DAG.getTargetLoweringInfo(); 3706 3707 // We care about the legality of the operation after it has been type 3708 // legalized. 3709 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3710 VT = TLI.getTypeToTransformTo(Ctx, VT); 3711 3712 // If the vselect is legal, assume we want to leave this as a vector setcc + 3713 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3714 // min/max is legal on the scalar type. 3715 bool UseScalarMinMax = VT.isVector() && 3716 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3717 3718 // ValueTracking's select pattern matching does not account for -0.0, 3719 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3720 // -0.0 is less than +0.0. 3721 Value *LHS, *RHS; 3722 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3723 ISD::NodeType Opc = ISD::DELETED_NODE; 3724 switch (SPR.Flavor) { 3725 case SPF_UMAX: Opc = ISD::UMAX; break; 3726 case SPF_UMIN: Opc = ISD::UMIN; break; 3727 case SPF_SMAX: Opc = ISD::SMAX; break; 3728 case SPF_SMIN: Opc = ISD::SMIN; break; 3729 case SPF_FMINNUM: 3730 switch (SPR.NaNBehavior) { 3731 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3732 case SPNB_RETURNS_NAN: break; 3733 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3734 case SPNB_RETURNS_ANY: 3735 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3736 (UseScalarMinMax && 3737 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3738 Opc = ISD::FMINNUM; 3739 break; 3740 } 3741 break; 3742 case SPF_FMAXNUM: 3743 switch (SPR.NaNBehavior) { 3744 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3745 case SPNB_RETURNS_NAN: break; 3746 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3747 case SPNB_RETURNS_ANY: 3748 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3749 (UseScalarMinMax && 3750 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3751 Opc = ISD::FMAXNUM; 3752 break; 3753 } 3754 break; 3755 case SPF_NABS: 3756 Negate = true; 3757 [[fallthrough]]; 3758 case SPF_ABS: 3759 IsUnaryAbs = true; 3760 Opc = ISD::ABS; 3761 break; 3762 default: break; 3763 } 3764 3765 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3766 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3767 (UseScalarMinMax && 3768 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3769 // If the underlying comparison instruction is used by any other 3770 // instruction, the consumed instructions won't be destroyed, so it is 3771 // not profitable to convert to a min/max. 3772 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3773 OpCode = Opc; 3774 LHSVal = getValue(LHS); 3775 RHSVal = getValue(RHS); 3776 BaseOps.clear(); 3777 } 3778 3779 if (IsUnaryAbs) { 3780 OpCode = Opc; 3781 LHSVal = getValue(LHS); 3782 BaseOps.clear(); 3783 } 3784 } 3785 3786 if (IsUnaryAbs) { 3787 for (unsigned i = 0; i != NumValues; ++i) { 3788 SDLoc dl = getCurSDLoc(); 3789 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3790 Values[i] = 3791 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3792 if (Negate) 3793 Values[i] = DAG.getNegative(Values[i], dl, VT); 3794 } 3795 } else { 3796 for (unsigned i = 0; i != NumValues; ++i) { 3797 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3798 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3799 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3800 Values[i] = DAG.getNode( 3801 OpCode, getCurSDLoc(), 3802 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3803 } 3804 } 3805 3806 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3807 DAG.getVTList(ValueVTs), Values)); 3808 } 3809 3810 void SelectionDAGBuilder::visitTrunc(const User &I) { 3811 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3812 SDValue N = getValue(I.getOperand(0)); 3813 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3814 I.getType()); 3815 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3816 } 3817 3818 void SelectionDAGBuilder::visitZExt(const User &I) { 3819 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3820 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3821 SDValue N = getValue(I.getOperand(0)); 3822 auto &TLI = DAG.getTargetLoweringInfo(); 3823 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3824 3825 SDNodeFlags Flags; 3826 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3827 Flags.setNonNeg(PNI->hasNonNeg()); 3828 3829 // Eagerly use nonneg information to canonicalize towards sign_extend if 3830 // that is the target's preference. 3831 // TODO: Let the target do this later. 3832 if (Flags.hasNonNeg() && 3833 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3834 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3835 return; 3836 } 3837 3838 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3839 } 3840 3841 void SelectionDAGBuilder::visitSExt(const User &I) { 3842 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3843 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3844 SDValue N = getValue(I.getOperand(0)); 3845 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3846 I.getType()); 3847 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3848 } 3849 3850 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3851 // FPTrunc is never a no-op cast, no need to check 3852 SDValue N = getValue(I.getOperand(0)); 3853 SDLoc dl = getCurSDLoc(); 3854 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3855 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3856 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3857 DAG.getTargetConstant( 3858 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3859 } 3860 3861 void SelectionDAGBuilder::visitFPExt(const User &I) { 3862 // FPExt is never a no-op cast, no need to check 3863 SDValue N = getValue(I.getOperand(0)); 3864 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3865 I.getType()); 3866 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3867 } 3868 3869 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3870 // FPToUI is never a no-op cast, no need to check 3871 SDValue N = getValue(I.getOperand(0)); 3872 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3873 I.getType()); 3874 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3875 } 3876 3877 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3878 // FPToSI is never a no-op cast, no need to check 3879 SDValue N = getValue(I.getOperand(0)); 3880 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3881 I.getType()); 3882 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3883 } 3884 3885 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3886 // UIToFP is never a no-op cast, no need to check 3887 SDValue N = getValue(I.getOperand(0)); 3888 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3889 I.getType()); 3890 SDNodeFlags Flags; 3891 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3892 Flags.setNonNeg(PNI->hasNonNeg()); 3893 3894 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags)); 3895 } 3896 3897 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3898 // SIToFP 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 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3903 } 3904 3905 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3906 // What to do depends on the size of the integer and the size of the pointer. 3907 // We can either truncate, zero extend, or no-op, accordingly. 3908 SDValue N = getValue(I.getOperand(0)); 3909 auto &TLI = DAG.getTargetLoweringInfo(); 3910 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3911 I.getType()); 3912 EVT PtrMemVT = 3913 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3914 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3915 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3916 setValue(&I, N); 3917 } 3918 3919 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3920 // What to do depends on the size of the integer and the size of the pointer. 3921 // We can either truncate, zero extend, or no-op, accordingly. 3922 SDValue N = getValue(I.getOperand(0)); 3923 auto &TLI = DAG.getTargetLoweringInfo(); 3924 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3925 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3926 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3927 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3928 setValue(&I, N); 3929 } 3930 3931 void SelectionDAGBuilder::visitBitCast(const User &I) { 3932 SDValue N = getValue(I.getOperand(0)); 3933 SDLoc dl = getCurSDLoc(); 3934 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3935 I.getType()); 3936 3937 // BitCast assures us that source and destination are the same size so this is 3938 // either a BITCAST or a no-op. 3939 if (DestVT != N.getValueType()) 3940 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3941 DestVT, N)); // convert types. 3942 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3943 // might fold any kind of constant expression to an integer constant and that 3944 // is not what we are looking for. Only recognize a bitcast of a genuine 3945 // constant integer as an opaque constant. 3946 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3947 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3948 /*isOpaque*/true)); 3949 else 3950 setValue(&I, N); // noop cast. 3951 } 3952 3953 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3955 const Value *SV = I.getOperand(0); 3956 SDValue N = getValue(SV); 3957 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3958 3959 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3960 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3961 3962 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3963 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3964 3965 setValue(&I, N); 3966 } 3967 3968 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3970 SDValue InVec = getValue(I.getOperand(0)); 3971 SDValue InVal = getValue(I.getOperand(1)); 3972 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3973 TLI.getVectorIdxTy(DAG.getDataLayout())); 3974 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3975 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3976 InVec, InVal, InIdx)); 3977 } 3978 3979 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3980 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3981 SDValue InVec = getValue(I.getOperand(0)); 3982 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3983 TLI.getVectorIdxTy(DAG.getDataLayout())); 3984 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3985 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3986 InVec, InIdx)); 3987 } 3988 3989 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3990 SDValue Src1 = getValue(I.getOperand(0)); 3991 SDValue Src2 = getValue(I.getOperand(1)); 3992 ArrayRef<int> Mask; 3993 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3994 Mask = SVI->getShuffleMask(); 3995 else 3996 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3997 SDLoc DL = getCurSDLoc(); 3998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3999 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4000 EVT SrcVT = Src1.getValueType(); 4001 4002 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 4003 VT.isScalableVector()) { 4004 // Canonical splat form of first element of first input vector. 4005 SDValue FirstElt = 4006 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 4007 DAG.getVectorIdxConstant(0, DL)); 4008 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 4009 return; 4010 } 4011 4012 // For now, we only handle splats for scalable vectors. 4013 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 4014 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 4015 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 4016 4017 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 4018 unsigned MaskNumElts = Mask.size(); 4019 4020 if (SrcNumElts == MaskNumElts) { 4021 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 4022 return; 4023 } 4024 4025 // Normalize the shuffle vector since mask and vector length don't match. 4026 if (SrcNumElts < MaskNumElts) { 4027 // Mask is longer than the source vectors. We can use concatenate vector to 4028 // make the mask and vectors lengths match. 4029 4030 if (MaskNumElts % SrcNumElts == 0) { 4031 // Mask length is a multiple of the source vector length. 4032 // Check if the shuffle is some kind of concatenation of the input 4033 // vectors. 4034 unsigned NumConcat = MaskNumElts / SrcNumElts; 4035 bool IsConcat = true; 4036 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 4037 for (unsigned i = 0; i != MaskNumElts; ++i) { 4038 int Idx = Mask[i]; 4039 if (Idx < 0) 4040 continue; 4041 // Ensure the indices in each SrcVT sized piece are sequential and that 4042 // the same source is used for the whole piece. 4043 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 4044 (ConcatSrcs[i / SrcNumElts] >= 0 && 4045 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 4046 IsConcat = false; 4047 break; 4048 } 4049 // Remember which source this index came from. 4050 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 4051 } 4052 4053 // The shuffle is concatenating multiple vectors together. Just emit 4054 // a CONCAT_VECTORS operation. 4055 if (IsConcat) { 4056 SmallVector<SDValue, 8> ConcatOps; 4057 for (auto Src : ConcatSrcs) { 4058 if (Src < 0) 4059 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 4060 else if (Src == 0) 4061 ConcatOps.push_back(Src1); 4062 else 4063 ConcatOps.push_back(Src2); 4064 } 4065 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 4066 return; 4067 } 4068 } 4069 4070 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 4071 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 4072 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 4073 PaddedMaskNumElts); 4074 4075 // Pad both vectors with undefs to make them the same length as the mask. 4076 SDValue UndefVal = DAG.getUNDEF(SrcVT); 4077 4078 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 4079 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 4080 MOps1[0] = Src1; 4081 MOps2[0] = Src2; 4082 4083 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 4084 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 4085 4086 // Readjust mask for new input vector length. 4087 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 4088 for (unsigned i = 0; i != MaskNumElts; ++i) { 4089 int Idx = Mask[i]; 4090 if (Idx >= (int)SrcNumElts) 4091 Idx -= SrcNumElts - PaddedMaskNumElts; 4092 MappedOps[i] = Idx; 4093 } 4094 4095 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 4096 4097 // If the concatenated vector was padded, extract a subvector with the 4098 // correct number of elements. 4099 if (MaskNumElts != PaddedMaskNumElts) 4100 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 4101 DAG.getVectorIdxConstant(0, DL)); 4102 4103 setValue(&I, Result); 4104 return; 4105 } 4106 4107 if (SrcNumElts > MaskNumElts) { 4108 // Analyze the access pattern of the vector to see if we can extract 4109 // two subvectors and do the shuffle. 4110 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 4111 bool CanExtract = true; 4112 for (int Idx : Mask) { 4113 unsigned Input = 0; 4114 if (Idx < 0) 4115 continue; 4116 4117 if (Idx >= (int)SrcNumElts) { 4118 Input = 1; 4119 Idx -= SrcNumElts; 4120 } 4121 4122 // If all the indices come from the same MaskNumElts sized portion of 4123 // the sources we can use extract. Also make sure the extract wouldn't 4124 // extract past the end of the source. 4125 int NewStartIdx = alignDown(Idx, MaskNumElts); 4126 if (NewStartIdx + MaskNumElts > SrcNumElts || 4127 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 4128 CanExtract = false; 4129 // Make sure we always update StartIdx as we use it to track if all 4130 // elements are undef. 4131 StartIdx[Input] = NewStartIdx; 4132 } 4133 4134 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 4135 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 4136 return; 4137 } 4138 if (CanExtract) { 4139 // Extract appropriate subvector and generate a vector shuffle 4140 for (unsigned Input = 0; Input < 2; ++Input) { 4141 SDValue &Src = Input == 0 ? Src1 : Src2; 4142 if (StartIdx[Input] < 0) 4143 Src = DAG.getUNDEF(VT); 4144 else { 4145 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 4146 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 4147 } 4148 } 4149 4150 // Calculate new mask. 4151 SmallVector<int, 8> MappedOps(Mask); 4152 for (int &Idx : MappedOps) { 4153 if (Idx >= (int)SrcNumElts) 4154 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 4155 else if (Idx >= 0) 4156 Idx -= StartIdx[0]; 4157 } 4158 4159 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 4160 return; 4161 } 4162 } 4163 4164 // We can't use either concat vectors or extract subvectors so fall back to 4165 // replacing the shuffle with extract and build vector. 4166 // to insert and build vector. 4167 EVT EltVT = VT.getVectorElementType(); 4168 SmallVector<SDValue,8> Ops; 4169 for (int Idx : Mask) { 4170 SDValue Res; 4171 4172 if (Idx < 0) { 4173 Res = DAG.getUNDEF(EltVT); 4174 } else { 4175 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 4176 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 4177 4178 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4179 DAG.getVectorIdxConstant(Idx, DL)); 4180 } 4181 4182 Ops.push_back(Res); 4183 } 4184 4185 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4186 } 4187 4188 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4189 ArrayRef<unsigned> Indices = I.getIndices(); 4190 const Value *Op0 = I.getOperand(0); 4191 const Value *Op1 = I.getOperand(1); 4192 Type *AggTy = I.getType(); 4193 Type *ValTy = Op1->getType(); 4194 bool IntoUndef = isa<UndefValue>(Op0); 4195 bool FromUndef = isa<UndefValue>(Op1); 4196 4197 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4198 4199 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4200 SmallVector<EVT, 4> AggValueVTs; 4201 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4202 SmallVector<EVT, 4> ValValueVTs; 4203 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4204 4205 unsigned NumAggValues = AggValueVTs.size(); 4206 unsigned NumValValues = ValValueVTs.size(); 4207 SmallVector<SDValue, 4> Values(NumAggValues); 4208 4209 // Ignore an insertvalue that produces an empty object 4210 if (!NumAggValues) { 4211 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4212 return; 4213 } 4214 4215 SDValue Agg = getValue(Op0); 4216 unsigned i = 0; 4217 // Copy the beginning value(s) from the original aggregate. 4218 for (; i != LinearIndex; ++i) 4219 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4220 SDValue(Agg.getNode(), Agg.getResNo() + i); 4221 // Copy values from the inserted value(s). 4222 if (NumValValues) { 4223 SDValue Val = getValue(Op1); 4224 for (; i != LinearIndex + NumValValues; ++i) 4225 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4226 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4227 } 4228 // Copy remaining value(s) from the original aggregate. 4229 for (; i != NumAggValues; ++i) 4230 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4231 SDValue(Agg.getNode(), Agg.getResNo() + i); 4232 4233 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4234 DAG.getVTList(AggValueVTs), Values)); 4235 } 4236 4237 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4238 ArrayRef<unsigned> Indices = I.getIndices(); 4239 const Value *Op0 = I.getOperand(0); 4240 Type *AggTy = Op0->getType(); 4241 Type *ValTy = I.getType(); 4242 bool OutOfUndef = isa<UndefValue>(Op0); 4243 4244 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4245 4246 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4247 SmallVector<EVT, 4> ValValueVTs; 4248 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4249 4250 unsigned NumValValues = ValValueVTs.size(); 4251 4252 // Ignore a extractvalue that produces an empty object 4253 if (!NumValValues) { 4254 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4255 return; 4256 } 4257 4258 SmallVector<SDValue, 4> Values(NumValValues); 4259 4260 SDValue Agg = getValue(Op0); 4261 // Copy out the selected value(s). 4262 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4263 Values[i - LinearIndex] = 4264 OutOfUndef ? 4265 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4266 SDValue(Agg.getNode(), Agg.getResNo() + i); 4267 4268 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4269 DAG.getVTList(ValValueVTs), Values)); 4270 } 4271 4272 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4273 Value *Op0 = I.getOperand(0); 4274 // Note that the pointer operand may be a vector of pointers. Take the scalar 4275 // element which holds a pointer. 4276 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4277 SDValue N = getValue(Op0); 4278 SDLoc dl = getCurSDLoc(); 4279 auto &TLI = DAG.getTargetLoweringInfo(); 4280 4281 // Normalize Vector GEP - all scalar operands should be converted to the 4282 // splat vector. 4283 bool IsVectorGEP = I.getType()->isVectorTy(); 4284 ElementCount VectorElementCount = 4285 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4286 : ElementCount::getFixed(0); 4287 4288 if (IsVectorGEP && !N.getValueType().isVector()) { 4289 LLVMContext &Context = *DAG.getContext(); 4290 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4291 N = DAG.getSplat(VT, dl, N); 4292 } 4293 4294 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4295 GTI != E; ++GTI) { 4296 const Value *Idx = GTI.getOperand(); 4297 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4298 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4299 if (Field) { 4300 // N = N + Offset 4301 uint64_t Offset = 4302 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4303 4304 // In an inbounds GEP with an offset that is nonnegative even when 4305 // interpreted as signed, assume there is no unsigned overflow. 4306 SDNodeFlags Flags; 4307 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4308 Flags.setNoUnsignedWrap(true); 4309 4310 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4311 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4312 } 4313 } else { 4314 // IdxSize is the width of the arithmetic according to IR semantics. 4315 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4316 // (and fix up the result later). 4317 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4318 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4319 TypeSize ElementSize = 4320 GTI.getSequentialElementStride(DAG.getDataLayout()); 4321 // We intentionally mask away the high bits here; ElementSize may not 4322 // fit in IdxTy. 4323 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4324 bool ElementScalable = ElementSize.isScalable(); 4325 4326 // If this is a scalar constant or a splat vector of constants, 4327 // handle it quickly. 4328 const auto *C = dyn_cast<Constant>(Idx); 4329 if (C && isa<VectorType>(C->getType())) 4330 C = C->getSplatValue(); 4331 4332 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4333 if (CI && CI->isZero()) 4334 continue; 4335 if (CI && !ElementScalable) { 4336 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4337 LLVMContext &Context = *DAG.getContext(); 4338 SDValue OffsVal; 4339 if (IsVectorGEP) 4340 OffsVal = DAG.getConstant( 4341 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4342 else 4343 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4344 4345 // In an inbounds GEP with an offset that is nonnegative even when 4346 // interpreted as signed, assume there is no unsigned overflow. 4347 SDNodeFlags Flags; 4348 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4349 Flags.setNoUnsignedWrap(true); 4350 4351 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4352 4353 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4354 continue; 4355 } 4356 4357 // N = N + Idx * ElementMul; 4358 SDValue IdxN = getValue(Idx); 4359 4360 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4361 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4362 VectorElementCount); 4363 IdxN = DAG.getSplat(VT, dl, IdxN); 4364 } 4365 4366 // If the index is smaller or larger than intptr_t, truncate or extend 4367 // it. 4368 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4369 4370 if (ElementScalable) { 4371 EVT VScaleTy = N.getValueType().getScalarType(); 4372 SDValue VScale = DAG.getNode( 4373 ISD::VSCALE, dl, VScaleTy, 4374 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4375 if (IsVectorGEP) 4376 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4377 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4378 } else { 4379 // If this is a multiply by a power of two, turn it into a shl 4380 // immediately. This is a very common case. 4381 if (ElementMul != 1) { 4382 if (ElementMul.isPowerOf2()) { 4383 unsigned Amt = ElementMul.logBase2(); 4384 IdxN = DAG.getNode(ISD::SHL, dl, 4385 N.getValueType(), IdxN, 4386 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4387 } else { 4388 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4389 IdxN.getValueType()); 4390 IdxN = DAG.getNode(ISD::MUL, dl, 4391 N.getValueType(), IdxN, Scale); 4392 } 4393 } 4394 } 4395 4396 N = DAG.getNode(ISD::ADD, dl, 4397 N.getValueType(), N, IdxN); 4398 } 4399 } 4400 4401 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4402 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4403 if (IsVectorGEP) { 4404 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4405 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4406 } 4407 4408 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4409 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4410 4411 setValue(&I, N); 4412 } 4413 4414 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4415 // If this is a fixed sized alloca in the entry block of the function, 4416 // allocate it statically on the stack. 4417 if (FuncInfo.StaticAllocaMap.count(&I)) 4418 return; // getValue will auto-populate this. 4419 4420 SDLoc dl = getCurSDLoc(); 4421 Type *Ty = I.getAllocatedType(); 4422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4423 auto &DL = DAG.getDataLayout(); 4424 TypeSize TySize = DL.getTypeAllocSize(Ty); 4425 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4426 4427 SDValue AllocSize = getValue(I.getArraySize()); 4428 4429 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4430 if (AllocSize.getValueType() != IntPtr) 4431 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4432 4433 if (TySize.isScalable()) 4434 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4435 DAG.getVScale(dl, IntPtr, 4436 APInt(IntPtr.getScalarSizeInBits(), 4437 TySize.getKnownMinValue()))); 4438 else { 4439 SDValue TySizeValue = 4440 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4441 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4442 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4443 } 4444 4445 // Handle alignment. If the requested alignment is less than or equal to 4446 // the stack alignment, ignore it. If the size is greater than or equal to 4447 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4448 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4449 if (*Alignment <= StackAlign) 4450 Alignment = std::nullopt; 4451 4452 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4453 // Round the size of the allocation up to the stack alignment size 4454 // by add SA-1 to the size. This doesn't overflow because we're computing 4455 // an address inside an alloca. 4456 SDNodeFlags Flags; 4457 Flags.setNoUnsignedWrap(true); 4458 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4459 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4460 4461 // Mask out the low bits for alignment purposes. 4462 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4463 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4464 4465 SDValue Ops[] = { 4466 getRoot(), AllocSize, 4467 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4468 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4469 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4470 setValue(&I, DSA); 4471 DAG.setRoot(DSA.getValue(1)); 4472 4473 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4474 } 4475 4476 static const MDNode *getRangeMetadata(const Instruction &I) { 4477 // If !noundef is not present, then !range violation results in a poison 4478 // value rather than immediate undefined behavior. In theory, transferring 4479 // these annotations to SDAG is fine, but in practice there are key SDAG 4480 // transforms that are known not to be poison-safe, such as folding logical 4481 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4482 // also present. 4483 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4484 return nullptr; 4485 return I.getMetadata(LLVMContext::MD_range); 4486 } 4487 4488 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4489 if (I.isAtomic()) 4490 return visitAtomicLoad(I); 4491 4492 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4493 const Value *SV = I.getOperand(0); 4494 if (TLI.supportSwiftError()) { 4495 // Swifterror values can come from either a function parameter with 4496 // swifterror attribute or an alloca with swifterror attribute. 4497 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4498 if (Arg->hasSwiftErrorAttr()) 4499 return visitLoadFromSwiftError(I); 4500 } 4501 4502 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4503 if (Alloca->isSwiftError()) 4504 return visitLoadFromSwiftError(I); 4505 } 4506 } 4507 4508 SDValue Ptr = getValue(SV); 4509 4510 Type *Ty = I.getType(); 4511 SmallVector<EVT, 4> ValueVTs, MemVTs; 4512 SmallVector<TypeSize, 4> Offsets; 4513 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4514 unsigned NumValues = ValueVTs.size(); 4515 if (NumValues == 0) 4516 return; 4517 4518 Align Alignment = I.getAlign(); 4519 AAMDNodes AAInfo = I.getAAMetadata(); 4520 const MDNode *Ranges = getRangeMetadata(I); 4521 bool isVolatile = I.isVolatile(); 4522 MachineMemOperand::Flags MMOFlags = 4523 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4524 4525 SDValue Root; 4526 bool ConstantMemory = false; 4527 if (isVolatile) 4528 // Serialize volatile loads with other side effects. 4529 Root = getRoot(); 4530 else if (NumValues > MaxParallelChains) 4531 Root = getMemoryRoot(); 4532 else if (AA && 4533 AA->pointsToConstantMemory(MemoryLocation( 4534 SV, 4535 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4536 AAInfo))) { 4537 // Do not serialize (non-volatile) loads of constant memory with anything. 4538 Root = DAG.getEntryNode(); 4539 ConstantMemory = true; 4540 MMOFlags |= MachineMemOperand::MOInvariant; 4541 } else { 4542 // Do not serialize non-volatile loads against each other. 4543 Root = DAG.getRoot(); 4544 } 4545 4546 SDLoc dl = getCurSDLoc(); 4547 4548 if (isVolatile) 4549 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4550 4551 SmallVector<SDValue, 4> Values(NumValues); 4552 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4553 4554 unsigned ChainI = 0; 4555 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4556 // Serializing loads here may result in excessive register pressure, and 4557 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4558 // could recover a bit by hoisting nodes upward in the chain by recognizing 4559 // they are side-effect free or do not alias. The optimizer should really 4560 // avoid this case by converting large object/array copies to llvm.memcpy 4561 // (MaxParallelChains should always remain as failsafe). 4562 if (ChainI == MaxParallelChains) { 4563 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4564 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4565 ArrayRef(Chains.data(), ChainI)); 4566 Root = Chain; 4567 ChainI = 0; 4568 } 4569 4570 // TODO: MachinePointerInfo only supports a fixed length offset. 4571 MachinePointerInfo PtrInfo = 4572 !Offsets[i].isScalable() || Offsets[i].isZero() 4573 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4574 : MachinePointerInfo(); 4575 4576 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4577 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4578 MMOFlags, AAInfo, Ranges); 4579 Chains[ChainI] = L.getValue(1); 4580 4581 if (MemVTs[i] != ValueVTs[i]) 4582 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4583 4584 Values[i] = L; 4585 } 4586 4587 if (!ConstantMemory) { 4588 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4589 ArrayRef(Chains.data(), ChainI)); 4590 if (isVolatile) 4591 DAG.setRoot(Chain); 4592 else 4593 PendingLoads.push_back(Chain); 4594 } 4595 4596 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4597 DAG.getVTList(ValueVTs), Values)); 4598 } 4599 4600 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4601 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4602 "call visitStoreToSwiftError when backend supports swifterror"); 4603 4604 SmallVector<EVT, 4> ValueVTs; 4605 SmallVector<uint64_t, 4> Offsets; 4606 const Value *SrcV = I.getOperand(0); 4607 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4608 SrcV->getType(), ValueVTs, &Offsets, 0); 4609 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4610 "expect a single EVT for swifterror"); 4611 4612 SDValue Src = getValue(SrcV); 4613 // Create a virtual register, then update the virtual register. 4614 Register VReg = 4615 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4616 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4617 // Chain can be getRoot or getControlRoot. 4618 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4619 SDValue(Src.getNode(), Src.getResNo())); 4620 DAG.setRoot(CopyNode); 4621 } 4622 4623 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4624 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4625 "call visitLoadFromSwiftError when backend supports swifterror"); 4626 4627 assert(!I.isVolatile() && 4628 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4629 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4630 "Support volatile, non temporal, invariant for load_from_swift_error"); 4631 4632 const Value *SV = I.getOperand(0); 4633 Type *Ty = I.getType(); 4634 assert( 4635 (!AA || 4636 !AA->pointsToConstantMemory(MemoryLocation( 4637 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4638 I.getAAMetadata()))) && 4639 "load_from_swift_error should not be constant memory"); 4640 4641 SmallVector<EVT, 4> ValueVTs; 4642 SmallVector<uint64_t, 4> Offsets; 4643 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4644 ValueVTs, &Offsets, 0); 4645 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4646 "expect a single EVT for swifterror"); 4647 4648 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4649 SDValue L = DAG.getCopyFromReg( 4650 getRoot(), getCurSDLoc(), 4651 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4652 4653 setValue(&I, L); 4654 } 4655 4656 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4657 if (I.isAtomic()) 4658 return visitAtomicStore(I); 4659 4660 const Value *SrcV = I.getOperand(0); 4661 const Value *PtrV = I.getOperand(1); 4662 4663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4664 if (TLI.supportSwiftError()) { 4665 // Swifterror values can come from either a function parameter with 4666 // swifterror attribute or an alloca with swifterror attribute. 4667 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4668 if (Arg->hasSwiftErrorAttr()) 4669 return visitStoreToSwiftError(I); 4670 } 4671 4672 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4673 if (Alloca->isSwiftError()) 4674 return visitStoreToSwiftError(I); 4675 } 4676 } 4677 4678 SmallVector<EVT, 4> ValueVTs, MemVTs; 4679 SmallVector<TypeSize, 4> Offsets; 4680 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4681 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4682 unsigned NumValues = ValueVTs.size(); 4683 if (NumValues == 0) 4684 return; 4685 4686 // Get the lowered operands. Note that we do this after 4687 // checking if NumResults is zero, because with zero results 4688 // the operands won't have values in the map. 4689 SDValue Src = getValue(SrcV); 4690 SDValue Ptr = getValue(PtrV); 4691 4692 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4693 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4694 SDLoc dl = getCurSDLoc(); 4695 Align Alignment = I.getAlign(); 4696 AAMDNodes AAInfo = I.getAAMetadata(); 4697 4698 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4699 4700 unsigned ChainI = 0; 4701 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4702 // See visitLoad comments. 4703 if (ChainI == MaxParallelChains) { 4704 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4705 ArrayRef(Chains.data(), ChainI)); 4706 Root = Chain; 4707 ChainI = 0; 4708 } 4709 4710 // TODO: MachinePointerInfo only supports a fixed length offset. 4711 MachinePointerInfo PtrInfo = 4712 !Offsets[i].isScalable() || Offsets[i].isZero() 4713 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4714 : MachinePointerInfo(); 4715 4716 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4717 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4718 if (MemVTs[i] != ValueVTs[i]) 4719 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4720 SDValue St = 4721 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4722 Chains[ChainI] = St; 4723 } 4724 4725 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4726 ArrayRef(Chains.data(), ChainI)); 4727 setValue(&I, StoreNode); 4728 DAG.setRoot(StoreNode); 4729 } 4730 4731 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4732 bool IsCompressing) { 4733 SDLoc sdl = getCurSDLoc(); 4734 4735 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4736 Align &Alignment) { 4737 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4738 Src0 = I.getArgOperand(0); 4739 Ptr = I.getArgOperand(1); 4740 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue(); 4741 Mask = I.getArgOperand(3); 4742 }; 4743 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4744 Align &Alignment) { 4745 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4746 Src0 = I.getArgOperand(0); 4747 Ptr = I.getArgOperand(1); 4748 Mask = I.getArgOperand(2); 4749 Alignment = I.getParamAlign(1).valueOrOne(); 4750 }; 4751 4752 Value *PtrOperand, *MaskOperand, *Src0Operand; 4753 Align Alignment; 4754 if (IsCompressing) 4755 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4756 else 4757 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4758 4759 SDValue Ptr = getValue(PtrOperand); 4760 SDValue Src0 = getValue(Src0Operand); 4761 SDValue Mask = getValue(MaskOperand); 4762 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4763 4764 EVT VT = Src0.getValueType(); 4765 4766 auto MMOFlags = MachineMemOperand::MOStore; 4767 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4768 MMOFlags |= MachineMemOperand::MONonTemporal; 4769 4770 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4771 MachinePointerInfo(PtrOperand), MMOFlags, 4772 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4773 SDValue StoreNode = 4774 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4775 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4776 DAG.setRoot(StoreNode); 4777 setValue(&I, StoreNode); 4778 } 4779 4780 // Get a uniform base for the Gather/Scatter intrinsic. 4781 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4782 // We try to represent it as a base pointer + vector of indices. 4783 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4784 // The first operand of the GEP may be a single pointer or a vector of pointers 4785 // Example: 4786 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4787 // or 4788 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4789 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4790 // 4791 // When the first GEP operand is a single pointer - it is the uniform base we 4792 // are looking for. If first operand of the GEP is a splat vector - we 4793 // extract the splat value and use it as a uniform base. 4794 // In all other cases the function returns 'false'. 4795 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4796 ISD::MemIndexType &IndexType, SDValue &Scale, 4797 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4798 uint64_t ElemSize) { 4799 SelectionDAG& DAG = SDB->DAG; 4800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4801 const DataLayout &DL = DAG.getDataLayout(); 4802 4803 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4804 4805 // Handle splat constant pointer. 4806 if (auto *C = dyn_cast<Constant>(Ptr)) { 4807 C = C->getSplatValue(); 4808 if (!C) 4809 return false; 4810 4811 Base = SDB->getValue(C); 4812 4813 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4814 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4815 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4816 IndexType = ISD::SIGNED_SCALED; 4817 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4818 return true; 4819 } 4820 4821 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4822 if (!GEP || GEP->getParent() != CurBB) 4823 return false; 4824 4825 if (GEP->getNumOperands() != 2) 4826 return false; 4827 4828 const Value *BasePtr = GEP->getPointerOperand(); 4829 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4830 4831 // Make sure the base is scalar and the index is a vector. 4832 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4833 return false; 4834 4835 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4836 if (ScaleVal.isScalable()) 4837 return false; 4838 4839 // Target may not support the required addressing mode. 4840 if (ScaleVal != 1 && 4841 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4842 return false; 4843 4844 Base = SDB->getValue(BasePtr); 4845 Index = SDB->getValue(IndexVal); 4846 IndexType = ISD::SIGNED_SCALED; 4847 4848 Scale = 4849 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4850 return true; 4851 } 4852 4853 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4854 SDLoc sdl = getCurSDLoc(); 4855 4856 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4857 const Value *Ptr = I.getArgOperand(1); 4858 SDValue Src0 = getValue(I.getArgOperand(0)); 4859 SDValue Mask = getValue(I.getArgOperand(3)); 4860 EVT VT = Src0.getValueType(); 4861 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4862 ->getMaybeAlignValue() 4863 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4864 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4865 4866 SDValue Base; 4867 SDValue Index; 4868 ISD::MemIndexType IndexType; 4869 SDValue Scale; 4870 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4871 I.getParent(), VT.getScalarStoreSize()); 4872 4873 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4874 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4875 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4876 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata()); 4877 if (!UniformBase) { 4878 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4879 Index = getValue(Ptr); 4880 IndexType = ISD::SIGNED_SCALED; 4881 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4882 } 4883 4884 EVT IdxVT = Index.getValueType(); 4885 EVT EltTy = IdxVT.getVectorElementType(); 4886 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4887 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4888 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4889 } 4890 4891 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4892 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4893 Ops, MMO, IndexType, false); 4894 DAG.setRoot(Scatter); 4895 setValue(&I, Scatter); 4896 } 4897 4898 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4899 SDLoc sdl = getCurSDLoc(); 4900 4901 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4902 Align &Alignment) { 4903 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4904 Ptr = I.getArgOperand(0); 4905 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue(); 4906 Mask = I.getArgOperand(2); 4907 Src0 = I.getArgOperand(3); 4908 }; 4909 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4910 Align &Alignment) { 4911 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4912 Ptr = I.getArgOperand(0); 4913 Alignment = I.getParamAlign(0).valueOrOne(); 4914 Mask = I.getArgOperand(1); 4915 Src0 = I.getArgOperand(2); 4916 }; 4917 4918 Value *PtrOperand, *MaskOperand, *Src0Operand; 4919 Align Alignment; 4920 if (IsExpanding) 4921 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4922 else 4923 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4924 4925 SDValue Ptr = getValue(PtrOperand); 4926 SDValue Src0 = getValue(Src0Operand); 4927 SDValue Mask = getValue(MaskOperand); 4928 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4929 4930 EVT VT = Src0.getValueType(); 4931 AAMDNodes AAInfo = I.getAAMetadata(); 4932 const MDNode *Ranges = getRangeMetadata(I); 4933 4934 // Do not serialize masked loads of constant memory with anything. 4935 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4936 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4937 4938 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4939 4940 auto MMOFlags = MachineMemOperand::MOLoad; 4941 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4942 MMOFlags |= MachineMemOperand::MONonTemporal; 4943 4944 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4945 MachinePointerInfo(PtrOperand), MMOFlags, 4946 LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges); 4947 4948 SDValue Load = 4949 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4950 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4951 if (AddToChain) 4952 PendingLoads.push_back(Load.getValue(1)); 4953 setValue(&I, Load); 4954 } 4955 4956 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4957 SDLoc sdl = getCurSDLoc(); 4958 4959 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4960 const Value *Ptr = I.getArgOperand(0); 4961 SDValue Src0 = getValue(I.getArgOperand(3)); 4962 SDValue Mask = getValue(I.getArgOperand(2)); 4963 4964 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4965 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4966 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4967 ->getMaybeAlignValue() 4968 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4969 4970 const MDNode *Ranges = getRangeMetadata(I); 4971 4972 SDValue Root = DAG.getRoot(); 4973 SDValue Base; 4974 SDValue Index; 4975 ISD::MemIndexType IndexType; 4976 SDValue Scale; 4977 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4978 I.getParent(), VT.getScalarStoreSize()); 4979 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4980 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4981 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4982 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(), 4983 Ranges); 4984 4985 if (!UniformBase) { 4986 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4987 Index = getValue(Ptr); 4988 IndexType = ISD::SIGNED_SCALED; 4989 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4990 } 4991 4992 EVT IdxVT = Index.getValueType(); 4993 EVT EltTy = IdxVT.getVectorElementType(); 4994 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4995 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4996 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4997 } 4998 4999 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 5000 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 5001 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 5002 5003 PendingLoads.push_back(Gather.getValue(1)); 5004 setValue(&I, Gather); 5005 } 5006 5007 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 5008 SDLoc dl = getCurSDLoc(); 5009 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 5010 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 5011 SyncScope::ID SSID = I.getSyncScopeID(); 5012 5013 SDValue InChain = getRoot(); 5014 5015 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 5016 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 5017 5018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5019 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5020 5021 MachineFunction &MF = DAG.getMachineFunction(); 5022 MachineMemOperand *MMO = MF.getMachineMemOperand( 5023 MachinePointerInfo(I.getPointerOperand()), Flags, 5024 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5025 AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering); 5026 5027 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 5028 dl, MemVT, VTs, InChain, 5029 getValue(I.getPointerOperand()), 5030 getValue(I.getCompareOperand()), 5031 getValue(I.getNewValOperand()), MMO); 5032 5033 SDValue OutChain = L.getValue(2); 5034 5035 setValue(&I, L); 5036 DAG.setRoot(OutChain); 5037 } 5038 5039 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 5040 SDLoc dl = getCurSDLoc(); 5041 ISD::NodeType NT; 5042 switch (I.getOperation()) { 5043 default: llvm_unreachable("Unknown atomicrmw operation"); 5044 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 5045 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 5046 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 5047 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 5048 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 5049 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 5050 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 5051 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 5052 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 5053 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 5054 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 5055 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 5056 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 5057 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 5058 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 5059 case AtomicRMWInst::UIncWrap: 5060 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 5061 break; 5062 case AtomicRMWInst::UDecWrap: 5063 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 5064 break; 5065 } 5066 AtomicOrdering Ordering = I.getOrdering(); 5067 SyncScope::ID SSID = I.getSyncScopeID(); 5068 5069 SDValue InChain = getRoot(); 5070 5071 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 5072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5073 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 5074 5075 MachineFunction &MF = DAG.getMachineFunction(); 5076 MachineMemOperand *MMO = MF.getMachineMemOperand( 5077 MachinePointerInfo(I.getPointerOperand()), Flags, 5078 LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT), 5079 AAMDNodes(), nullptr, SSID, Ordering); 5080 5081 SDValue L = 5082 DAG.getAtomic(NT, dl, MemVT, InChain, 5083 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 5084 MMO); 5085 5086 SDValue OutChain = L.getValue(1); 5087 5088 setValue(&I, L); 5089 DAG.setRoot(OutChain); 5090 } 5091 5092 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 5093 SDLoc dl = getCurSDLoc(); 5094 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5095 SDValue Ops[3]; 5096 Ops[0] = getRoot(); 5097 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 5098 TLI.getFenceOperandTy(DAG.getDataLayout())); 5099 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 5100 TLI.getFenceOperandTy(DAG.getDataLayout())); 5101 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 5102 setValue(&I, N); 5103 DAG.setRoot(N); 5104 } 5105 5106 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 5107 SDLoc dl = getCurSDLoc(); 5108 AtomicOrdering Order = I.getOrdering(); 5109 SyncScope::ID SSID = I.getSyncScopeID(); 5110 5111 SDValue InChain = getRoot(); 5112 5113 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5114 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5115 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 5116 5117 if (!TLI.supportsUnalignedAtomics() && 5118 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5119 report_fatal_error("Cannot generate unaligned atomic load"); 5120 5121 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 5122 5123 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 5124 MachinePointerInfo(I.getPointerOperand()), Flags, 5125 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5126 nullptr, SSID, Order); 5127 5128 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 5129 5130 SDValue Ptr = getValue(I.getPointerOperand()); 5131 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 5132 Ptr, MMO); 5133 5134 SDValue OutChain = L.getValue(1); 5135 if (MemVT != VT) 5136 L = DAG.getPtrExtOrTrunc(L, dl, VT); 5137 5138 setValue(&I, L); 5139 DAG.setRoot(OutChain); 5140 } 5141 5142 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 5143 SDLoc dl = getCurSDLoc(); 5144 5145 AtomicOrdering Ordering = I.getOrdering(); 5146 SyncScope::ID SSID = I.getSyncScopeID(); 5147 5148 SDValue InChain = getRoot(); 5149 5150 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5151 EVT MemVT = 5152 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 5153 5154 if (!TLI.supportsUnalignedAtomics() && 5155 I.getAlign().value() < MemVT.getSizeInBits() / 8) 5156 report_fatal_error("Cannot generate unaligned atomic store"); 5157 5158 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 5159 5160 MachineFunction &MF = DAG.getMachineFunction(); 5161 MachineMemOperand *MMO = MF.getMachineMemOperand( 5162 MachinePointerInfo(I.getPointerOperand()), Flags, 5163 LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(), 5164 nullptr, SSID, Ordering); 5165 5166 SDValue Val = getValue(I.getValueOperand()); 5167 if (Val.getValueType() != MemVT) 5168 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 5169 SDValue Ptr = getValue(I.getPointerOperand()); 5170 5171 SDValue OutChain = 5172 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 5173 5174 setValue(&I, OutChain); 5175 DAG.setRoot(OutChain); 5176 } 5177 5178 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 5179 /// node. 5180 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5181 unsigned Intrinsic) { 5182 // Ignore the callsite's attributes. A specific call site may be marked with 5183 // readnone, but the lowering code will expect the chain based on the 5184 // definition. 5185 const Function *F = I.getCalledFunction(); 5186 bool HasChain = !F->doesNotAccessMemory(); 5187 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5188 5189 // Build the operand list. 5190 SmallVector<SDValue, 8> Ops; 5191 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5192 if (OnlyLoad) { 5193 // We don't need to serialize loads against other loads. 5194 Ops.push_back(DAG.getRoot()); 5195 } else { 5196 Ops.push_back(getRoot()); 5197 } 5198 } 5199 5200 // Info is set by getTgtMemIntrinsic 5201 TargetLowering::IntrinsicInfo Info; 5202 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5203 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5204 DAG.getMachineFunction(), 5205 Intrinsic); 5206 5207 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5208 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5209 Info.opc == ISD::INTRINSIC_W_CHAIN) 5210 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5211 TLI.getPointerTy(DAG.getDataLayout()))); 5212 5213 // Add all operands of the call to the operand list. 5214 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5215 const Value *Arg = I.getArgOperand(i); 5216 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5217 Ops.push_back(getValue(Arg)); 5218 continue; 5219 } 5220 5221 // Use TargetConstant instead of a regular constant for immarg. 5222 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5223 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5224 assert(CI->getBitWidth() <= 64 && 5225 "large intrinsic immediates not handled"); 5226 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5227 } else { 5228 Ops.push_back( 5229 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5230 } 5231 } 5232 5233 SmallVector<EVT, 4> ValueVTs; 5234 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5235 5236 if (HasChain) 5237 ValueVTs.push_back(MVT::Other); 5238 5239 SDVTList VTs = DAG.getVTList(ValueVTs); 5240 5241 // Propagate fast-math-flags from IR to node(s). 5242 SDNodeFlags Flags; 5243 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5244 Flags.copyFMF(*FPMO); 5245 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5246 5247 // Create the node. 5248 SDValue Result; 5249 5250 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5251 auto *Token = Bundle->Inputs[0].get(); 5252 SDValue ConvControlToken = getValue(Token); 5253 assert(Ops.back().getValueType() != MVT::Glue && 5254 "Did not expected another glue node here."); 5255 ConvControlToken = 5256 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5257 Ops.push_back(ConvControlToken); 5258 } 5259 5260 // In some cases, custom collection of operands from CallInst I may be needed. 5261 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5262 if (IsTgtIntrinsic) { 5263 // This is target intrinsic that touches memory 5264 // 5265 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5266 // didn't yield anything useful. 5267 MachinePointerInfo MPI; 5268 if (Info.ptrVal) 5269 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5270 else if (Info.fallbackAddressSpace) 5271 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5272 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5273 Info.memVT, MPI, Info.align, Info.flags, 5274 Info.size, I.getAAMetadata()); 5275 } else if (!HasChain) { 5276 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5277 } else if (!I.getType()->isVoidTy()) { 5278 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5279 } else { 5280 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5281 } 5282 5283 if (HasChain) { 5284 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5285 if (OnlyLoad) 5286 PendingLoads.push_back(Chain); 5287 else 5288 DAG.setRoot(Chain); 5289 } 5290 5291 if (!I.getType()->isVoidTy()) { 5292 if (!isa<VectorType>(I.getType())) 5293 Result = lowerRangeToAssertZExt(DAG, I, Result); 5294 5295 MaybeAlign Alignment = I.getRetAlign(); 5296 5297 // Insert `assertalign` node if there's an alignment. 5298 if (InsertAssertAlign && Alignment) { 5299 Result = 5300 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5301 } 5302 } 5303 5304 setValue(&I, Result); 5305 } 5306 5307 /// GetSignificand - Get the significand and build it into a floating-point 5308 /// number with exponent of 1: 5309 /// 5310 /// Op = (Op & 0x007fffff) | 0x3f800000; 5311 /// 5312 /// where Op is the hexadecimal representation of floating point value. 5313 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5314 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5315 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5316 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5317 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5318 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5319 } 5320 5321 /// GetExponent - Get the exponent: 5322 /// 5323 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5324 /// 5325 /// where Op is the hexadecimal representation of floating point value. 5326 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5327 const TargetLowering &TLI, const SDLoc &dl) { 5328 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5329 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5330 SDValue t1 = DAG.getNode( 5331 ISD::SRL, dl, MVT::i32, t0, 5332 DAG.getConstant(23, dl, 5333 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5334 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5335 DAG.getConstant(127, dl, MVT::i32)); 5336 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5337 } 5338 5339 /// getF32Constant - Get 32-bit floating point constant. 5340 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5341 const SDLoc &dl) { 5342 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5343 MVT::f32); 5344 } 5345 5346 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5347 SelectionDAG &DAG) { 5348 // TODO: What fast-math-flags should be set on the floating-point nodes? 5349 5350 // IntegerPartOfX = ((int32_t)(t0); 5351 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5352 5353 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5354 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5355 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5356 5357 // IntegerPartOfX <<= 23; 5358 IntegerPartOfX = 5359 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5360 DAG.getConstant(23, dl, 5361 DAG.getTargetLoweringInfo().getShiftAmountTy( 5362 MVT::i32, DAG.getDataLayout()))); 5363 5364 SDValue TwoToFractionalPartOfX; 5365 if (LimitFloatPrecision <= 6) { 5366 // For floating-point precision of 6: 5367 // 5368 // TwoToFractionalPartOfX = 5369 // 0.997535578f + 5370 // (0.735607626f + 0.252464424f * x) * x; 5371 // 5372 // error 0.0144103317, which is 6 bits 5373 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5374 getF32Constant(DAG, 0x3e814304, dl)); 5375 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5376 getF32Constant(DAG, 0x3f3c50c8, dl)); 5377 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5378 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5379 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5380 } else if (LimitFloatPrecision <= 12) { 5381 // For floating-point precision of 12: 5382 // 5383 // TwoToFractionalPartOfX = 5384 // 0.999892986f + 5385 // (0.696457318f + 5386 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5387 // 5388 // error 0.000107046256, which is 13 to 14 bits 5389 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5390 getF32Constant(DAG, 0x3da235e3, dl)); 5391 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5392 getF32Constant(DAG, 0x3e65b8f3, dl)); 5393 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5394 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5395 getF32Constant(DAG, 0x3f324b07, dl)); 5396 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5397 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5398 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5399 } else { // LimitFloatPrecision <= 18 5400 // For floating-point precision of 18: 5401 // 5402 // TwoToFractionalPartOfX = 5403 // 0.999999982f + 5404 // (0.693148872f + 5405 // (0.240227044f + 5406 // (0.554906021e-1f + 5407 // (0.961591928e-2f + 5408 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5409 // error 2.47208000*10^(-7), which is better than 18 bits 5410 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5411 getF32Constant(DAG, 0x3924b03e, dl)); 5412 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5413 getF32Constant(DAG, 0x3ab24b87, dl)); 5414 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5415 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5416 getF32Constant(DAG, 0x3c1d8c17, dl)); 5417 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5418 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5419 getF32Constant(DAG, 0x3d634a1d, dl)); 5420 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5421 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5422 getF32Constant(DAG, 0x3e75fe14, dl)); 5423 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5424 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5425 getF32Constant(DAG, 0x3f317234, dl)); 5426 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5427 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5428 getF32Constant(DAG, 0x3f800000, dl)); 5429 } 5430 5431 // Add the exponent into the result in integer domain. 5432 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5433 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5434 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5435 } 5436 5437 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5438 /// limited-precision mode. 5439 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5440 const TargetLowering &TLI, SDNodeFlags Flags) { 5441 if (Op.getValueType() == MVT::f32 && 5442 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5443 5444 // Put the exponent in the right bit position for later addition to the 5445 // final result: 5446 // 5447 // t0 = Op * log2(e) 5448 5449 // TODO: What fast-math-flags should be set here? 5450 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5451 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5452 return getLimitedPrecisionExp2(t0, dl, DAG); 5453 } 5454 5455 // No special expansion. 5456 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5457 } 5458 5459 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5460 /// limited-precision mode. 5461 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5462 const TargetLowering &TLI, SDNodeFlags Flags) { 5463 // TODO: What fast-math-flags should be set on the floating-point nodes? 5464 5465 if (Op.getValueType() == MVT::f32 && 5466 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5467 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5468 5469 // Scale the exponent by log(2). 5470 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5471 SDValue LogOfExponent = 5472 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5473 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5474 5475 // Get the significand and build it into a floating-point number with 5476 // exponent of 1. 5477 SDValue X = GetSignificand(DAG, Op1, dl); 5478 5479 SDValue LogOfMantissa; 5480 if (LimitFloatPrecision <= 6) { 5481 // For floating-point precision of 6: 5482 // 5483 // LogofMantissa = 5484 // -1.1609546f + 5485 // (1.4034025f - 0.23903021f * x) * x; 5486 // 5487 // error 0.0034276066, which is better than 8 bits 5488 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5489 getF32Constant(DAG, 0xbe74c456, dl)); 5490 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5491 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5492 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5493 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5494 getF32Constant(DAG, 0x3f949a29, dl)); 5495 } else if (LimitFloatPrecision <= 12) { 5496 // For floating-point precision of 12: 5497 // 5498 // LogOfMantissa = 5499 // -1.7417939f + 5500 // (2.8212026f + 5501 // (-1.4699568f + 5502 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5503 // 5504 // error 0.000061011436, which is 14 bits 5505 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5506 getF32Constant(DAG, 0xbd67b6d6, dl)); 5507 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5508 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5509 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5510 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5511 getF32Constant(DAG, 0x3fbc278b, dl)); 5512 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5513 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5514 getF32Constant(DAG, 0x40348e95, dl)); 5515 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5516 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5517 getF32Constant(DAG, 0x3fdef31a, dl)); 5518 } else { // LimitFloatPrecision <= 18 5519 // For floating-point precision of 18: 5520 // 5521 // LogOfMantissa = 5522 // -2.1072184f + 5523 // (4.2372794f + 5524 // (-3.7029485f + 5525 // (2.2781945f + 5526 // (-0.87823314f + 5527 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5528 // 5529 // error 0.0000023660568, which is better than 18 bits 5530 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5531 getF32Constant(DAG, 0xbc91e5ac, dl)); 5532 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5533 getF32Constant(DAG, 0x3e4350aa, dl)); 5534 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5535 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5536 getF32Constant(DAG, 0x3f60d3e3, dl)); 5537 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5538 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5539 getF32Constant(DAG, 0x4011cdf0, dl)); 5540 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5541 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5542 getF32Constant(DAG, 0x406cfd1c, dl)); 5543 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5544 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5545 getF32Constant(DAG, 0x408797cb, dl)); 5546 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5547 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5548 getF32Constant(DAG, 0x4006dcab, dl)); 5549 } 5550 5551 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5552 } 5553 5554 // No special expansion. 5555 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5556 } 5557 5558 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5559 /// limited-precision mode. 5560 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5561 const TargetLowering &TLI, SDNodeFlags Flags) { 5562 // TODO: What fast-math-flags should be set on the floating-point nodes? 5563 5564 if (Op.getValueType() == MVT::f32 && 5565 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5566 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5567 5568 // Get the exponent. 5569 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5570 5571 // Get the significand and build it into a floating-point number with 5572 // exponent of 1. 5573 SDValue X = GetSignificand(DAG, Op1, dl); 5574 5575 // Different possible minimax approximations of significand in 5576 // floating-point for various degrees of accuracy over [1,2]. 5577 SDValue Log2ofMantissa; 5578 if (LimitFloatPrecision <= 6) { 5579 // For floating-point precision of 6: 5580 // 5581 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5582 // 5583 // error 0.0049451742, which is more than 7 bits 5584 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5585 getF32Constant(DAG, 0xbeb08fe0, dl)); 5586 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5587 getF32Constant(DAG, 0x40019463, dl)); 5588 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5589 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5590 getF32Constant(DAG, 0x3fd6633d, dl)); 5591 } else if (LimitFloatPrecision <= 12) { 5592 // For floating-point precision of 12: 5593 // 5594 // Log2ofMantissa = 5595 // -2.51285454f + 5596 // (4.07009056f + 5597 // (-2.12067489f + 5598 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5599 // 5600 // error 0.0000876136000, which is better than 13 bits 5601 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5602 getF32Constant(DAG, 0xbda7262e, dl)); 5603 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5604 getF32Constant(DAG, 0x3f25280b, dl)); 5605 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5606 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5607 getF32Constant(DAG, 0x4007b923, dl)); 5608 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5609 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5610 getF32Constant(DAG, 0x40823e2f, dl)); 5611 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5612 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5613 getF32Constant(DAG, 0x4020d29c, dl)); 5614 } else { // LimitFloatPrecision <= 18 5615 // For floating-point precision of 18: 5616 // 5617 // Log2ofMantissa = 5618 // -3.0400495f + 5619 // (6.1129976f + 5620 // (-5.3420409f + 5621 // (3.2865683f + 5622 // (-1.2669343f + 5623 // (0.27515199f - 5624 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5625 // 5626 // error 0.0000018516, which is better than 18 bits 5627 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5628 getF32Constant(DAG, 0xbcd2769e, dl)); 5629 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5630 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5631 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5632 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5633 getF32Constant(DAG, 0x3fa22ae7, dl)); 5634 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5635 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5636 getF32Constant(DAG, 0x40525723, dl)); 5637 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5638 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5639 getF32Constant(DAG, 0x40aaf200, dl)); 5640 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5641 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5642 getF32Constant(DAG, 0x40c39dad, dl)); 5643 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5644 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5645 getF32Constant(DAG, 0x4042902c, dl)); 5646 } 5647 5648 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5649 } 5650 5651 // No special expansion. 5652 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5653 } 5654 5655 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5656 /// limited-precision mode. 5657 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5658 const TargetLowering &TLI, SDNodeFlags Flags) { 5659 // TODO: What fast-math-flags should be set on the floating-point nodes? 5660 5661 if (Op.getValueType() == MVT::f32 && 5662 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5663 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5664 5665 // Scale the exponent by log10(2) [0.30102999f]. 5666 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5667 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5668 getF32Constant(DAG, 0x3e9a209a, dl)); 5669 5670 // Get the significand and build it into a floating-point number with 5671 // exponent of 1. 5672 SDValue X = GetSignificand(DAG, Op1, dl); 5673 5674 SDValue Log10ofMantissa; 5675 if (LimitFloatPrecision <= 6) { 5676 // For floating-point precision of 6: 5677 // 5678 // Log10ofMantissa = 5679 // -0.50419619f + 5680 // (0.60948995f - 0.10380950f * x) * x; 5681 // 5682 // error 0.0014886165, which is 6 bits 5683 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5684 getF32Constant(DAG, 0xbdd49a13, dl)); 5685 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5686 getF32Constant(DAG, 0x3f1c0789, dl)); 5687 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5688 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5689 getF32Constant(DAG, 0x3f011300, dl)); 5690 } else if (LimitFloatPrecision <= 12) { 5691 // For floating-point precision of 12: 5692 // 5693 // Log10ofMantissa = 5694 // -0.64831180f + 5695 // (0.91751397f + 5696 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5697 // 5698 // error 0.00019228036, which is better than 12 bits 5699 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5700 getF32Constant(DAG, 0x3d431f31, dl)); 5701 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5702 getF32Constant(DAG, 0x3ea21fb2, dl)); 5703 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5704 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5705 getF32Constant(DAG, 0x3f6ae232, dl)); 5706 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5707 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5708 getF32Constant(DAG, 0x3f25f7c3, dl)); 5709 } else { // LimitFloatPrecision <= 18 5710 // For floating-point precision of 18: 5711 // 5712 // Log10ofMantissa = 5713 // -0.84299375f + 5714 // (1.5327582f + 5715 // (-1.0688956f + 5716 // (0.49102474f + 5717 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5718 // 5719 // error 0.0000037995730, which is better than 18 bits 5720 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5721 getF32Constant(DAG, 0x3c5d51ce, dl)); 5722 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5723 getF32Constant(DAG, 0x3e00685a, dl)); 5724 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5725 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5726 getF32Constant(DAG, 0x3efb6798, dl)); 5727 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5728 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5729 getF32Constant(DAG, 0x3f88d192, dl)); 5730 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5731 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5732 getF32Constant(DAG, 0x3fc4316c, dl)); 5733 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5734 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5735 getF32Constant(DAG, 0x3f57ce70, dl)); 5736 } 5737 5738 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5739 } 5740 5741 // No special expansion. 5742 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5743 } 5744 5745 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5746 /// limited-precision mode. 5747 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5748 const TargetLowering &TLI, SDNodeFlags Flags) { 5749 if (Op.getValueType() == MVT::f32 && 5750 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5751 return getLimitedPrecisionExp2(Op, dl, DAG); 5752 5753 // No special expansion. 5754 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5755 } 5756 5757 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5758 /// limited-precision mode with x == 10.0f. 5759 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5760 SelectionDAG &DAG, const TargetLowering &TLI, 5761 SDNodeFlags Flags) { 5762 bool IsExp10 = false; 5763 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5764 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5765 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5766 APFloat Ten(10.0f); 5767 IsExp10 = LHSC->isExactlyValue(Ten); 5768 } 5769 } 5770 5771 // TODO: What fast-math-flags should be set on the FMUL node? 5772 if (IsExp10) { 5773 // Put the exponent in the right bit position for later addition to the 5774 // final result: 5775 // 5776 // #define LOG2OF10 3.3219281f 5777 // t0 = Op * LOG2OF10; 5778 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5779 getF32Constant(DAG, 0x40549a78, dl)); 5780 return getLimitedPrecisionExp2(t0, dl, DAG); 5781 } 5782 5783 // No special expansion. 5784 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5785 } 5786 5787 /// ExpandPowI - Expand a llvm.powi intrinsic. 5788 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5789 SelectionDAG &DAG) { 5790 // If RHS is a constant, we can expand this out to a multiplication tree if 5791 // it's beneficial on the target, otherwise we end up lowering to a call to 5792 // __powidf2 (for example). 5793 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5794 unsigned Val = RHSC->getSExtValue(); 5795 5796 // powi(x, 0) -> 1.0 5797 if (Val == 0) 5798 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5799 5800 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5801 Val, DAG.shouldOptForSize())) { 5802 // Get the exponent as a positive value. 5803 if ((int)Val < 0) 5804 Val = -Val; 5805 // We use the simple binary decomposition method to generate the multiply 5806 // sequence. There are more optimal ways to do this (for example, 5807 // powi(x,15) generates one more multiply than it should), but this has 5808 // the benefit of being both really simple and much better than a libcall. 5809 SDValue Res; // Logically starts equal to 1.0 5810 SDValue CurSquare = LHS; 5811 // TODO: Intrinsics should have fast-math-flags that propagate to these 5812 // nodes. 5813 while (Val) { 5814 if (Val & 1) { 5815 if (Res.getNode()) 5816 Res = 5817 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5818 else 5819 Res = CurSquare; // 1.0*CurSquare. 5820 } 5821 5822 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5823 CurSquare, CurSquare); 5824 Val >>= 1; 5825 } 5826 5827 // If the original was negative, invert the result, producing 1/(x*x*x). 5828 if (RHSC->getSExtValue() < 0) 5829 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5830 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5831 return Res; 5832 } 5833 } 5834 5835 // Otherwise, expand to a libcall. 5836 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5837 } 5838 5839 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5840 SDValue LHS, SDValue RHS, SDValue Scale, 5841 SelectionDAG &DAG, const TargetLowering &TLI) { 5842 EVT VT = LHS.getValueType(); 5843 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5844 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5845 LLVMContext &Ctx = *DAG.getContext(); 5846 5847 // If the type is legal but the operation isn't, this node might survive all 5848 // the way to operation legalization. If we end up there and we do not have 5849 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5850 // node. 5851 5852 // Coax the legalizer into expanding the node during type legalization instead 5853 // by bumping the size by one bit. This will force it to Promote, enabling the 5854 // early expansion and avoiding the need to expand later. 5855 5856 // We don't have to do this if Scale is 0; that can always be expanded, unless 5857 // it's a saturating signed operation. Those can experience true integer 5858 // division overflow, a case which we must avoid. 5859 5860 // FIXME: We wouldn't have to do this (or any of the early 5861 // expansion/promotion) if it was possible to expand a libcall of an 5862 // illegal type during operation legalization. But it's not, so things 5863 // get a bit hacky. 5864 unsigned ScaleInt = Scale->getAsZExtVal(); 5865 if ((ScaleInt > 0 || (Saturating && Signed)) && 5866 (TLI.isTypeLegal(VT) || 5867 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5868 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5869 Opcode, VT, ScaleInt); 5870 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5871 EVT PromVT; 5872 if (VT.isScalarInteger()) 5873 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5874 else if (VT.isVector()) { 5875 PromVT = VT.getVectorElementType(); 5876 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5877 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5878 } else 5879 llvm_unreachable("Wrong VT for DIVFIX?"); 5880 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5881 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5882 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5883 // For saturating operations, we need to shift up the LHS to get the 5884 // proper saturation width, and then shift down again afterwards. 5885 if (Saturating) 5886 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5887 DAG.getConstant(1, DL, ShiftTy)); 5888 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5889 if (Saturating) 5890 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5891 DAG.getConstant(1, DL, ShiftTy)); 5892 return DAG.getZExtOrTrunc(Res, DL, VT); 5893 } 5894 } 5895 5896 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5897 } 5898 5899 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5900 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5901 static void 5902 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5903 const SDValue &N) { 5904 switch (N.getOpcode()) { 5905 case ISD::CopyFromReg: { 5906 SDValue Op = N.getOperand(1); 5907 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5908 Op.getValueType().getSizeInBits()); 5909 return; 5910 } 5911 case ISD::BITCAST: 5912 case ISD::AssertZext: 5913 case ISD::AssertSext: 5914 case ISD::TRUNCATE: 5915 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5916 return; 5917 case ISD::BUILD_PAIR: 5918 case ISD::BUILD_VECTOR: 5919 case ISD::CONCAT_VECTORS: 5920 for (SDValue Op : N->op_values()) 5921 getUnderlyingArgRegs(Regs, Op); 5922 return; 5923 default: 5924 return; 5925 } 5926 } 5927 5928 /// If the DbgValueInst is a dbg_value of a function argument, create the 5929 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5930 /// instruction selection, they will be inserted to the entry BB. 5931 /// We don't currently support this for variadic dbg_values, as they shouldn't 5932 /// appear for function arguments or in the prologue. 5933 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5934 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5935 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5936 const Argument *Arg = dyn_cast<Argument>(V); 5937 if (!Arg) 5938 return false; 5939 5940 MachineFunction &MF = DAG.getMachineFunction(); 5941 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5942 5943 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5944 // we've been asked to pursue. 5945 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5946 bool Indirect) { 5947 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5948 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5949 // pointing at the VReg, which will be patched up later. 5950 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5951 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5952 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5953 /* isKill */ false, /* isDead */ false, 5954 /* isUndef */ false, /* isEarlyClobber */ false, 5955 /* SubReg */ 0, /* isDebug */ true)}); 5956 5957 auto *NewDIExpr = FragExpr; 5958 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5959 // the DIExpression. 5960 if (Indirect) 5961 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5962 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5963 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5964 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5965 } else { 5966 // Create a completely standard DBG_VALUE. 5967 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5968 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5969 } 5970 }; 5971 5972 if (Kind == FuncArgumentDbgValueKind::Value) { 5973 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5974 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5975 // the entry block. 5976 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5977 if (!IsInEntryBlock) 5978 return false; 5979 5980 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5981 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5982 // variable that also is a param. 5983 // 5984 // Although, if we are at the top of the entry block already, we can still 5985 // emit using ArgDbgValue. This might catch some situations when the 5986 // dbg.value refers to an argument that isn't used in the entry block, so 5987 // any CopyToReg node would be optimized out and the only way to express 5988 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5989 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5990 // we should only emit as ArgDbgValue if the Variable is an argument to the 5991 // current function, and the dbg.value intrinsic is found in the entry 5992 // block. 5993 bool VariableIsFunctionInputArg = Variable->isParameter() && 5994 !DL->getInlinedAt(); 5995 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5996 if (!IsInPrologue && !VariableIsFunctionInputArg) 5997 return false; 5998 5999 // Here we assume that a function argument on IR level only can be used to 6000 // describe one input parameter on source level. If we for example have 6001 // source code like this 6002 // 6003 // struct A { long x, y; }; 6004 // void foo(struct A a, long b) { 6005 // ... 6006 // b = a.x; 6007 // ... 6008 // } 6009 // 6010 // and IR like this 6011 // 6012 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 6013 // entry: 6014 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 6015 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 6016 // call void @llvm.dbg.value(metadata i32 %b, "b", 6017 // ... 6018 // call void @llvm.dbg.value(metadata i32 %a1, "b" 6019 // ... 6020 // 6021 // then the last dbg.value is describing a parameter "b" using a value that 6022 // is an argument. But since we already has used %a1 to describe a parameter 6023 // we should not handle that last dbg.value here (that would result in an 6024 // incorrect hoisting of the DBG_VALUE to the function entry). 6025 // Notice that we allow one dbg.value per IR level argument, to accommodate 6026 // for the situation with fragments above. 6027 // If there is no node for the value being handled, we return true to skip 6028 // the normal generation of debug info, as it would kill existing debug 6029 // info for the parameter in case of duplicates. 6030 if (VariableIsFunctionInputArg) { 6031 unsigned ArgNo = Arg->getArgNo(); 6032 if (ArgNo >= FuncInfo.DescribedArgs.size()) 6033 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 6034 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 6035 return !NodeMap[V].getNode(); 6036 FuncInfo.DescribedArgs.set(ArgNo); 6037 } 6038 } 6039 6040 bool IsIndirect = false; 6041 std::optional<MachineOperand> Op; 6042 // Some arguments' frame index is recorded during argument lowering. 6043 int FI = FuncInfo.getArgumentFrameIndex(Arg); 6044 if (FI != std::numeric_limits<int>::max()) 6045 Op = MachineOperand::CreateFI(FI); 6046 6047 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 6048 if (!Op && N.getNode()) { 6049 getUnderlyingArgRegs(ArgRegsAndSizes, N); 6050 Register Reg; 6051 if (ArgRegsAndSizes.size() == 1) 6052 Reg = ArgRegsAndSizes.front().first; 6053 6054 if (Reg && Reg.isVirtual()) { 6055 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6056 Register PR = RegInfo.getLiveInPhysReg(Reg); 6057 if (PR) 6058 Reg = PR; 6059 } 6060 if (Reg) { 6061 Op = MachineOperand::CreateReg(Reg, false); 6062 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6063 } 6064 } 6065 6066 if (!Op && N.getNode()) { 6067 // Check if frame index is available. 6068 SDValue LCandidate = peekThroughBitcasts(N); 6069 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 6070 if (FrameIndexSDNode *FINode = 6071 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 6072 Op = MachineOperand::CreateFI(FINode->getIndex()); 6073 } 6074 6075 if (!Op) { 6076 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 6077 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 6078 SplitRegs) { 6079 unsigned Offset = 0; 6080 for (const auto &RegAndSize : SplitRegs) { 6081 // If the expression is already a fragment, the current register 6082 // offset+size might extend beyond the fragment. In this case, only 6083 // the register bits that are inside the fragment are relevant. 6084 int RegFragmentSizeInBits = RegAndSize.second; 6085 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 6086 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 6087 // The register is entirely outside the expression fragment, 6088 // so is irrelevant for debug info. 6089 if (Offset >= ExprFragmentSizeInBits) 6090 break; 6091 // The register is partially outside the expression fragment, only 6092 // the low bits within the fragment are relevant for debug info. 6093 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 6094 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 6095 } 6096 } 6097 6098 auto FragmentExpr = DIExpression::createFragmentExpression( 6099 Expr, Offset, RegFragmentSizeInBits); 6100 Offset += RegAndSize.second; 6101 // If a valid fragment expression cannot be created, the variable's 6102 // correct value cannot be determined and so it is set as Undef. 6103 if (!FragmentExpr) { 6104 SDDbgValue *SDV = DAG.getConstantDbgValue( 6105 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 6106 DAG.AddDbgValue(SDV, false); 6107 continue; 6108 } 6109 MachineInstr *NewMI = 6110 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 6111 Kind != FuncArgumentDbgValueKind::Value); 6112 FuncInfo.ArgDbgValues.push_back(NewMI); 6113 } 6114 }; 6115 6116 // Check if ValueMap has reg number. 6117 DenseMap<const Value *, Register>::const_iterator 6118 VMI = FuncInfo.ValueMap.find(V); 6119 if (VMI != FuncInfo.ValueMap.end()) { 6120 const auto &TLI = DAG.getTargetLoweringInfo(); 6121 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 6122 V->getType(), std::nullopt); 6123 if (RFV.occupiesMultipleRegs()) { 6124 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 6125 return true; 6126 } 6127 6128 Op = MachineOperand::CreateReg(VMI->second, false); 6129 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 6130 } else if (ArgRegsAndSizes.size() > 1) { 6131 // This was split due to the calling convention, and no virtual register 6132 // mapping exists for the value. 6133 splitMultiRegDbgValue(ArgRegsAndSizes); 6134 return true; 6135 } 6136 } 6137 6138 if (!Op) 6139 return false; 6140 6141 assert(Variable->isValidLocationForIntrinsic(DL) && 6142 "Expected inlined-at fields to agree"); 6143 MachineInstr *NewMI = nullptr; 6144 6145 if (Op->isReg()) 6146 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 6147 else 6148 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 6149 Variable, Expr); 6150 6151 // Otherwise, use ArgDbgValues. 6152 FuncInfo.ArgDbgValues.push_back(NewMI); 6153 return true; 6154 } 6155 6156 /// Return the appropriate SDDbgValue based on N. 6157 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 6158 DILocalVariable *Variable, 6159 DIExpression *Expr, 6160 const DebugLoc &dl, 6161 unsigned DbgSDNodeOrder) { 6162 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 6163 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 6164 // stack slot locations. 6165 // 6166 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 6167 // debug values here after optimization: 6168 // 6169 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 6170 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 6171 // 6172 // Both describe the direct values of their associated variables. 6173 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 6174 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6175 } 6176 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 6177 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 6178 } 6179 6180 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 6181 switch (Intrinsic) { 6182 case Intrinsic::smul_fix: 6183 return ISD::SMULFIX; 6184 case Intrinsic::umul_fix: 6185 return ISD::UMULFIX; 6186 case Intrinsic::smul_fix_sat: 6187 return ISD::SMULFIXSAT; 6188 case Intrinsic::umul_fix_sat: 6189 return ISD::UMULFIXSAT; 6190 case Intrinsic::sdiv_fix: 6191 return ISD::SDIVFIX; 6192 case Intrinsic::udiv_fix: 6193 return ISD::UDIVFIX; 6194 case Intrinsic::sdiv_fix_sat: 6195 return ISD::SDIVFIXSAT; 6196 case Intrinsic::udiv_fix_sat: 6197 return ISD::UDIVFIXSAT; 6198 default: 6199 llvm_unreachable("Unhandled fixed point intrinsic"); 6200 } 6201 } 6202 6203 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6204 const char *FunctionName) { 6205 assert(FunctionName && "FunctionName must not be nullptr"); 6206 SDValue Callee = DAG.getExternalSymbol( 6207 FunctionName, 6208 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6209 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6210 } 6211 6212 /// Given a @llvm.call.preallocated.setup, return the corresponding 6213 /// preallocated call. 6214 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6215 assert(cast<CallBase>(PreallocatedSetup) 6216 ->getCalledFunction() 6217 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6218 "expected call_preallocated_setup Value"); 6219 for (const auto *U : PreallocatedSetup->users()) { 6220 auto *UseCall = cast<CallBase>(U); 6221 const Function *Fn = UseCall->getCalledFunction(); 6222 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6223 return UseCall; 6224 } 6225 } 6226 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6227 } 6228 6229 /// If DI is a debug value with an EntryValue expression, lower it using the 6230 /// corresponding physical register of the associated Argument value 6231 /// (guaranteed to exist by the verifier). 6232 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6233 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6234 DIExpression *Expr, DebugLoc DbgLoc) { 6235 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6236 return false; 6237 6238 // These properties are guaranteed by the verifier. 6239 const Argument *Arg = cast<Argument>(Values[0]); 6240 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6241 6242 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6243 if (ArgIt == FuncInfo.ValueMap.end()) { 6244 LLVM_DEBUG( 6245 dbgs() << "Dropping dbg.value: expression is entry_value but " 6246 "couldn't find an associated register for the Argument\n"); 6247 return true; 6248 } 6249 Register ArgVReg = ArgIt->getSecond(); 6250 6251 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6252 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6253 SDDbgValue *SDV = DAG.getVRegDbgValue( 6254 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6255 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6256 return true; 6257 } 6258 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6259 "couldn't find a physical register\n"); 6260 return true; 6261 } 6262 6263 /// Lower the call to the specified intrinsic function. 6264 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6265 unsigned Intrinsic) { 6266 SDLoc sdl = getCurSDLoc(); 6267 switch (Intrinsic) { 6268 case Intrinsic::experimental_convergence_anchor: 6269 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6270 break; 6271 case Intrinsic::experimental_convergence_entry: 6272 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6273 break; 6274 case Intrinsic::experimental_convergence_loop: { 6275 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6276 auto *Token = Bundle->Inputs[0].get(); 6277 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6278 getValue(Token))); 6279 break; 6280 } 6281 } 6282 } 6283 6284 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I, 6285 unsigned IntrinsicID) { 6286 // For now, we're only lowering an 'add' histogram. 6287 // We can add others later, e.g. saturating adds, min/max. 6288 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add && 6289 "Tried to lower unsupported histogram type"); 6290 SDLoc sdl = getCurSDLoc(); 6291 Value *Ptr = I.getOperand(0); 6292 SDValue Inc = getValue(I.getOperand(1)); 6293 SDValue Mask = getValue(I.getOperand(2)); 6294 6295 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6296 DataLayout TargetDL = DAG.getDataLayout(); 6297 EVT VT = Inc.getValueType(); 6298 Align Alignment = DAG.getEVTAlign(VT); 6299 6300 const MDNode *Ranges = getRangeMetadata(I); 6301 6302 SDValue Root = DAG.getRoot(); 6303 SDValue Base; 6304 SDValue Index; 6305 ISD::MemIndexType IndexType; 6306 SDValue Scale; 6307 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 6308 I.getParent(), VT.getScalarStoreSize()); 6309 6310 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 6311 6312 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6313 MachinePointerInfo(AS), 6314 MachineMemOperand::MOLoad | MachineMemOperand::MOStore, 6315 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 6316 6317 if (!UniformBase) { 6318 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6319 Index = getValue(Ptr); 6320 IndexType = ISD::SIGNED_SCALED; 6321 Scale = 6322 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 6323 } 6324 6325 EVT IdxVT = Index.getValueType(); 6326 EVT EltTy = IdxVT.getVectorElementType(); 6327 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 6328 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 6329 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 6330 } 6331 6332 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32); 6333 6334 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID}; 6335 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl, 6336 Ops, MMO, IndexType); 6337 6338 setValue(&I, Histogram); 6339 DAG.setRoot(Histogram); 6340 } 6341 6342 /// Lower the call to the specified intrinsic function. 6343 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6344 unsigned Intrinsic) { 6345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6346 SDLoc sdl = getCurSDLoc(); 6347 DebugLoc dl = getCurDebugLoc(); 6348 SDValue Res; 6349 6350 SDNodeFlags Flags; 6351 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6352 Flags.copyFMF(*FPOp); 6353 6354 switch (Intrinsic) { 6355 default: 6356 // By default, turn this into a target intrinsic node. 6357 visitTargetIntrinsic(I, Intrinsic); 6358 return; 6359 case Intrinsic::vscale: { 6360 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6361 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6362 return; 6363 } 6364 case Intrinsic::vastart: visitVAStart(I); return; 6365 case Intrinsic::vaend: visitVAEnd(I); return; 6366 case Intrinsic::vacopy: visitVACopy(I); return; 6367 case Intrinsic::returnaddress: 6368 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6369 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6370 getValue(I.getArgOperand(0)))); 6371 return; 6372 case Intrinsic::addressofreturnaddress: 6373 setValue(&I, 6374 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6375 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6376 return; 6377 case Intrinsic::sponentry: 6378 setValue(&I, 6379 DAG.getNode(ISD::SPONENTRY, sdl, 6380 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6381 return; 6382 case Intrinsic::frameaddress: 6383 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6384 TLI.getFrameIndexTy(DAG.getDataLayout()), 6385 getValue(I.getArgOperand(0)))); 6386 return; 6387 case Intrinsic::read_volatile_register: 6388 case Intrinsic::read_register: { 6389 Value *Reg = I.getArgOperand(0); 6390 SDValue Chain = getRoot(); 6391 SDValue RegName = 6392 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6393 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6394 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6395 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6396 setValue(&I, Res); 6397 DAG.setRoot(Res.getValue(1)); 6398 return; 6399 } 6400 case Intrinsic::write_register: { 6401 Value *Reg = I.getArgOperand(0); 6402 Value *RegValue = I.getArgOperand(1); 6403 SDValue Chain = getRoot(); 6404 SDValue RegName = 6405 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6406 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6407 RegName, getValue(RegValue))); 6408 return; 6409 } 6410 case Intrinsic::memcpy: { 6411 const auto &MCI = cast<MemCpyInst>(I); 6412 SDValue Op1 = getValue(I.getArgOperand(0)); 6413 SDValue Op2 = getValue(I.getArgOperand(1)); 6414 SDValue Op3 = getValue(I.getArgOperand(2)); 6415 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6416 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6417 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6418 Align Alignment = std::min(DstAlign, SrcAlign); 6419 bool isVol = MCI.isVolatile(); 6420 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6421 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6422 // node. 6423 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6424 SDValue MC = DAG.getMemcpy( 6425 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6426 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6427 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6428 updateDAGForMaybeTailCall(MC); 6429 return; 6430 } 6431 case Intrinsic::memcpy_inline: { 6432 const auto &MCI = cast<MemCpyInlineInst>(I); 6433 SDValue Dst = getValue(I.getArgOperand(0)); 6434 SDValue Src = getValue(I.getArgOperand(1)); 6435 SDValue Size = getValue(I.getArgOperand(2)); 6436 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6437 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6438 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6439 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6440 Align Alignment = std::min(DstAlign, SrcAlign); 6441 bool isVol = MCI.isVolatile(); 6442 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6443 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6444 // node. 6445 SDValue MC = DAG.getMemcpy( 6446 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6447 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6448 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6449 updateDAGForMaybeTailCall(MC); 6450 return; 6451 } 6452 case Intrinsic::memset: { 6453 const auto &MSI = cast<MemSetInst>(I); 6454 SDValue Op1 = getValue(I.getArgOperand(0)); 6455 SDValue Op2 = getValue(I.getArgOperand(1)); 6456 SDValue Op3 = getValue(I.getArgOperand(2)); 6457 // @llvm.memset defines 0 and 1 to both mean no alignment. 6458 Align Alignment = MSI.getDestAlign().valueOrOne(); 6459 bool isVol = MSI.isVolatile(); 6460 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6461 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6462 SDValue MS = DAG.getMemset( 6463 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6464 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6465 updateDAGForMaybeTailCall(MS); 6466 return; 6467 } 6468 case Intrinsic::memset_inline: { 6469 const auto &MSII = cast<MemSetInlineInst>(I); 6470 SDValue Dst = getValue(I.getArgOperand(0)); 6471 SDValue Value = getValue(I.getArgOperand(1)); 6472 SDValue Size = getValue(I.getArgOperand(2)); 6473 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6474 // @llvm.memset defines 0 and 1 to both mean no alignment. 6475 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6476 bool isVol = MSII.isVolatile(); 6477 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6478 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6479 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6480 /* AlwaysInline */ true, isTC, 6481 MachinePointerInfo(I.getArgOperand(0)), 6482 I.getAAMetadata()); 6483 updateDAGForMaybeTailCall(MC); 6484 return; 6485 } 6486 case Intrinsic::memmove: { 6487 const auto &MMI = cast<MemMoveInst>(I); 6488 SDValue Op1 = getValue(I.getArgOperand(0)); 6489 SDValue Op2 = getValue(I.getArgOperand(1)); 6490 SDValue Op3 = getValue(I.getArgOperand(2)); 6491 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6492 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6493 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6494 Align Alignment = std::min(DstAlign, SrcAlign); 6495 bool isVol = MMI.isVolatile(); 6496 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6497 // FIXME: Support passing different dest/src alignments to the memmove DAG 6498 // node. 6499 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6500 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6501 isTC, MachinePointerInfo(I.getArgOperand(0)), 6502 MachinePointerInfo(I.getArgOperand(1)), 6503 I.getAAMetadata(), AA); 6504 updateDAGForMaybeTailCall(MM); 6505 return; 6506 } 6507 case Intrinsic::memcpy_element_unordered_atomic: { 6508 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6509 SDValue Dst = getValue(MI.getRawDest()); 6510 SDValue Src = getValue(MI.getRawSource()); 6511 SDValue Length = getValue(MI.getLength()); 6512 6513 Type *LengthTy = MI.getLength()->getType(); 6514 unsigned ElemSz = MI.getElementSizeInBytes(); 6515 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6516 SDValue MC = 6517 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6518 isTC, MachinePointerInfo(MI.getRawDest()), 6519 MachinePointerInfo(MI.getRawSource())); 6520 updateDAGForMaybeTailCall(MC); 6521 return; 6522 } 6523 case Intrinsic::memmove_element_unordered_atomic: { 6524 auto &MI = cast<AtomicMemMoveInst>(I); 6525 SDValue Dst = getValue(MI.getRawDest()); 6526 SDValue Src = getValue(MI.getRawSource()); 6527 SDValue Length = getValue(MI.getLength()); 6528 6529 Type *LengthTy = MI.getLength()->getType(); 6530 unsigned ElemSz = MI.getElementSizeInBytes(); 6531 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6532 SDValue MC = 6533 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6534 isTC, MachinePointerInfo(MI.getRawDest()), 6535 MachinePointerInfo(MI.getRawSource())); 6536 updateDAGForMaybeTailCall(MC); 6537 return; 6538 } 6539 case Intrinsic::memset_element_unordered_atomic: { 6540 auto &MI = cast<AtomicMemSetInst>(I); 6541 SDValue Dst = getValue(MI.getRawDest()); 6542 SDValue Val = getValue(MI.getValue()); 6543 SDValue Length = getValue(MI.getLength()); 6544 6545 Type *LengthTy = MI.getLength()->getType(); 6546 unsigned ElemSz = MI.getElementSizeInBytes(); 6547 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6548 SDValue MC = 6549 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6550 isTC, MachinePointerInfo(MI.getRawDest())); 6551 updateDAGForMaybeTailCall(MC); 6552 return; 6553 } 6554 case Intrinsic::call_preallocated_setup: { 6555 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6556 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6557 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6558 getRoot(), SrcValue); 6559 setValue(&I, Res); 6560 DAG.setRoot(Res); 6561 return; 6562 } 6563 case Intrinsic::call_preallocated_arg: { 6564 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6565 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6566 SDValue Ops[3]; 6567 Ops[0] = getRoot(); 6568 Ops[1] = SrcValue; 6569 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6570 MVT::i32); // arg index 6571 SDValue Res = DAG.getNode( 6572 ISD::PREALLOCATED_ARG, sdl, 6573 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6574 setValue(&I, Res); 6575 DAG.setRoot(Res.getValue(1)); 6576 return; 6577 } 6578 case Intrinsic::dbg_declare: { 6579 const auto &DI = cast<DbgDeclareInst>(I); 6580 // Debug intrinsics are handled separately in assignment tracking mode. 6581 // Some intrinsics are handled right after Argument lowering. 6582 if (AssignmentTrackingEnabled || 6583 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6584 return; 6585 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6586 DILocalVariable *Variable = DI.getVariable(); 6587 DIExpression *Expression = DI.getExpression(); 6588 dropDanglingDebugInfo(Variable, Expression); 6589 // Assume dbg.declare can not currently use DIArgList, i.e. 6590 // it is non-variadic. 6591 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6592 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6593 DI.getDebugLoc()); 6594 return; 6595 } 6596 case Intrinsic::dbg_label: { 6597 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6598 DILabel *Label = DI.getLabel(); 6599 assert(Label && "Missing label"); 6600 6601 SDDbgLabel *SDV; 6602 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6603 DAG.AddDbgLabel(SDV); 6604 return; 6605 } 6606 case Intrinsic::dbg_assign: { 6607 // Debug intrinsics are handled seperately in assignment tracking mode. 6608 if (AssignmentTrackingEnabled) 6609 return; 6610 // If assignment tracking hasn't been enabled then fall through and treat 6611 // the dbg.assign as a dbg.value. 6612 [[fallthrough]]; 6613 } 6614 case Intrinsic::dbg_value: { 6615 // Debug intrinsics are handled seperately in assignment tracking mode. 6616 if (AssignmentTrackingEnabled) 6617 return; 6618 const DbgValueInst &DI = cast<DbgValueInst>(I); 6619 assert(DI.getVariable() && "Missing variable"); 6620 6621 DILocalVariable *Variable = DI.getVariable(); 6622 DIExpression *Expression = DI.getExpression(); 6623 dropDanglingDebugInfo(Variable, Expression); 6624 6625 if (DI.isKillLocation()) { 6626 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6627 return; 6628 } 6629 6630 SmallVector<Value *, 4> Values(DI.getValues()); 6631 if (Values.empty()) 6632 return; 6633 6634 bool IsVariadic = DI.hasArgList(); 6635 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6636 SDNodeOrder, IsVariadic)) 6637 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6638 DI.getDebugLoc(), SDNodeOrder); 6639 return; 6640 } 6641 6642 case Intrinsic::eh_typeid_for: { 6643 // Find the type id for the given typeinfo. 6644 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6645 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6646 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6647 setValue(&I, Res); 6648 return; 6649 } 6650 6651 case Intrinsic::eh_return_i32: 6652 case Intrinsic::eh_return_i64: 6653 DAG.getMachineFunction().setCallsEHReturn(true); 6654 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6655 MVT::Other, 6656 getControlRoot(), 6657 getValue(I.getArgOperand(0)), 6658 getValue(I.getArgOperand(1)))); 6659 return; 6660 case Intrinsic::eh_unwind_init: 6661 DAG.getMachineFunction().setCallsUnwindInit(true); 6662 return; 6663 case Intrinsic::eh_dwarf_cfa: 6664 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6665 TLI.getPointerTy(DAG.getDataLayout()), 6666 getValue(I.getArgOperand(0)))); 6667 return; 6668 case Intrinsic::eh_sjlj_callsite: { 6669 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6670 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6671 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6672 6673 MMI.setCurrentCallSite(CI->getZExtValue()); 6674 return; 6675 } 6676 case Intrinsic::eh_sjlj_functioncontext: { 6677 // Get and store the index of the function context. 6678 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6679 AllocaInst *FnCtx = 6680 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6681 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6682 MFI.setFunctionContextIndex(FI); 6683 return; 6684 } 6685 case Intrinsic::eh_sjlj_setjmp: { 6686 SDValue Ops[2]; 6687 Ops[0] = getRoot(); 6688 Ops[1] = getValue(I.getArgOperand(0)); 6689 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6690 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6691 setValue(&I, Op.getValue(0)); 6692 DAG.setRoot(Op.getValue(1)); 6693 return; 6694 } 6695 case Intrinsic::eh_sjlj_longjmp: 6696 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6697 getRoot(), getValue(I.getArgOperand(0)))); 6698 return; 6699 case Intrinsic::eh_sjlj_setup_dispatch: 6700 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6701 getRoot())); 6702 return; 6703 case Intrinsic::masked_gather: 6704 visitMaskedGather(I); 6705 return; 6706 case Intrinsic::masked_load: 6707 visitMaskedLoad(I); 6708 return; 6709 case Intrinsic::masked_scatter: 6710 visitMaskedScatter(I); 6711 return; 6712 case Intrinsic::masked_store: 6713 visitMaskedStore(I); 6714 return; 6715 case Intrinsic::masked_expandload: 6716 visitMaskedLoad(I, true /* IsExpanding */); 6717 return; 6718 case Intrinsic::masked_compressstore: 6719 visitMaskedStore(I, true /* IsCompressing */); 6720 return; 6721 case Intrinsic::powi: 6722 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6723 getValue(I.getArgOperand(1)), DAG)); 6724 return; 6725 case Intrinsic::log: 6726 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6727 return; 6728 case Intrinsic::log2: 6729 setValue(&I, 6730 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6731 return; 6732 case Intrinsic::log10: 6733 setValue(&I, 6734 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6735 return; 6736 case Intrinsic::exp: 6737 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6738 return; 6739 case Intrinsic::exp2: 6740 setValue(&I, 6741 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6742 return; 6743 case Intrinsic::pow: 6744 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6745 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6746 return; 6747 case Intrinsic::sqrt: 6748 case Intrinsic::fabs: 6749 case Intrinsic::sin: 6750 case Intrinsic::cos: 6751 case Intrinsic::exp10: 6752 case Intrinsic::floor: 6753 case Intrinsic::ceil: 6754 case Intrinsic::trunc: 6755 case Intrinsic::rint: 6756 case Intrinsic::nearbyint: 6757 case Intrinsic::round: 6758 case Intrinsic::roundeven: 6759 case Intrinsic::canonicalize: { 6760 unsigned Opcode; 6761 // clang-format off 6762 switch (Intrinsic) { 6763 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6764 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6765 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6766 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6767 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6768 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6769 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6770 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6771 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6772 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6773 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6774 case Intrinsic::round: Opcode = ISD::FROUND; break; 6775 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6776 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6777 } 6778 // clang-format on 6779 6780 setValue(&I, DAG.getNode(Opcode, sdl, 6781 getValue(I.getArgOperand(0)).getValueType(), 6782 getValue(I.getArgOperand(0)), Flags)); 6783 return; 6784 } 6785 case Intrinsic::lround: 6786 case Intrinsic::llround: 6787 case Intrinsic::lrint: 6788 case Intrinsic::llrint: { 6789 unsigned Opcode; 6790 // clang-format off 6791 switch (Intrinsic) { 6792 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6793 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6794 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6795 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6796 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6797 } 6798 // clang-format on 6799 6800 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6801 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6802 getValue(I.getArgOperand(0)))); 6803 return; 6804 } 6805 case Intrinsic::minnum: 6806 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6807 getValue(I.getArgOperand(0)).getValueType(), 6808 getValue(I.getArgOperand(0)), 6809 getValue(I.getArgOperand(1)), Flags)); 6810 return; 6811 case Intrinsic::maxnum: 6812 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6813 getValue(I.getArgOperand(0)).getValueType(), 6814 getValue(I.getArgOperand(0)), 6815 getValue(I.getArgOperand(1)), Flags)); 6816 return; 6817 case Intrinsic::minimum: 6818 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6819 getValue(I.getArgOperand(0)).getValueType(), 6820 getValue(I.getArgOperand(0)), 6821 getValue(I.getArgOperand(1)), Flags)); 6822 return; 6823 case Intrinsic::maximum: 6824 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6825 getValue(I.getArgOperand(0)).getValueType(), 6826 getValue(I.getArgOperand(0)), 6827 getValue(I.getArgOperand(1)), Flags)); 6828 return; 6829 case Intrinsic::copysign: 6830 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6831 getValue(I.getArgOperand(0)).getValueType(), 6832 getValue(I.getArgOperand(0)), 6833 getValue(I.getArgOperand(1)), Flags)); 6834 return; 6835 case Intrinsic::ldexp: 6836 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6837 getValue(I.getArgOperand(0)).getValueType(), 6838 getValue(I.getArgOperand(0)), 6839 getValue(I.getArgOperand(1)), Flags)); 6840 return; 6841 case Intrinsic::frexp: { 6842 SmallVector<EVT, 2> ValueVTs; 6843 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6844 SDVTList VTs = DAG.getVTList(ValueVTs); 6845 setValue(&I, 6846 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6847 return; 6848 } 6849 case Intrinsic::arithmetic_fence: { 6850 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6851 getValue(I.getArgOperand(0)).getValueType(), 6852 getValue(I.getArgOperand(0)), Flags)); 6853 return; 6854 } 6855 case Intrinsic::fma: 6856 setValue(&I, DAG.getNode( 6857 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6858 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6859 getValue(I.getArgOperand(2)), Flags)); 6860 return; 6861 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6862 case Intrinsic::INTRINSIC: 6863 #include "llvm/IR/ConstrainedOps.def" 6864 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6865 return; 6866 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6867 #include "llvm/IR/VPIntrinsics.def" 6868 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6869 return; 6870 case Intrinsic::fptrunc_round: { 6871 // Get the last argument, the metadata and convert it to an integer in the 6872 // call 6873 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6874 std::optional<RoundingMode> RoundMode = 6875 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6876 6877 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6878 6879 // Propagate fast-math-flags from IR to node(s). 6880 SDNodeFlags Flags; 6881 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6882 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6883 6884 SDValue Result; 6885 Result = DAG.getNode( 6886 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6887 DAG.getTargetConstant((int)*RoundMode, sdl, 6888 TLI.getPointerTy(DAG.getDataLayout()))); 6889 setValue(&I, Result); 6890 6891 return; 6892 } 6893 case Intrinsic::fmuladd: { 6894 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6895 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6896 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6897 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6898 getValue(I.getArgOperand(0)).getValueType(), 6899 getValue(I.getArgOperand(0)), 6900 getValue(I.getArgOperand(1)), 6901 getValue(I.getArgOperand(2)), Flags)); 6902 } else { 6903 // TODO: Intrinsic calls should have fast-math-flags. 6904 SDValue Mul = DAG.getNode( 6905 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6906 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6907 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6908 getValue(I.getArgOperand(0)).getValueType(), 6909 Mul, getValue(I.getArgOperand(2)), Flags); 6910 setValue(&I, Add); 6911 } 6912 return; 6913 } 6914 case Intrinsic::convert_to_fp16: 6915 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6916 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6917 getValue(I.getArgOperand(0)), 6918 DAG.getTargetConstant(0, sdl, 6919 MVT::i32)))); 6920 return; 6921 case Intrinsic::convert_from_fp16: 6922 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6923 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6924 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6925 getValue(I.getArgOperand(0))))); 6926 return; 6927 case Intrinsic::fptosi_sat: { 6928 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6929 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6930 getValue(I.getArgOperand(0)), 6931 DAG.getValueType(VT.getScalarType()))); 6932 return; 6933 } 6934 case Intrinsic::fptoui_sat: { 6935 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6936 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6937 getValue(I.getArgOperand(0)), 6938 DAG.getValueType(VT.getScalarType()))); 6939 return; 6940 } 6941 case Intrinsic::set_rounding: 6942 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6943 {getRoot(), getValue(I.getArgOperand(0))}); 6944 setValue(&I, Res); 6945 DAG.setRoot(Res.getValue(0)); 6946 return; 6947 case Intrinsic::is_fpclass: { 6948 const DataLayout DLayout = DAG.getDataLayout(); 6949 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6950 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6951 FPClassTest Test = static_cast<FPClassTest>( 6952 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6953 MachineFunction &MF = DAG.getMachineFunction(); 6954 const Function &F = MF.getFunction(); 6955 SDValue Op = getValue(I.getArgOperand(0)); 6956 SDNodeFlags Flags; 6957 Flags.setNoFPExcept( 6958 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6959 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6960 // expansion can use illegal types. Making expansion early allows 6961 // legalizing these types prior to selection. 6962 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6963 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6964 setValue(&I, Result); 6965 return; 6966 } 6967 6968 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6969 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6970 setValue(&I, V); 6971 return; 6972 } 6973 case Intrinsic::get_fpenv: { 6974 const DataLayout DLayout = DAG.getDataLayout(); 6975 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6976 Align TempAlign = DAG.getEVTAlign(EnvVT); 6977 SDValue Chain = getRoot(); 6978 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6979 // and temporary storage in stack. 6980 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6981 Res = DAG.getNode( 6982 ISD::GET_FPENV, sdl, 6983 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6984 MVT::Other), 6985 Chain); 6986 } else { 6987 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6988 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6989 auto MPI = 6990 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6991 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6992 MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(), 6993 TempAlign); 6994 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6995 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6996 } 6997 setValue(&I, Res); 6998 DAG.setRoot(Res.getValue(1)); 6999 return; 7000 } 7001 case Intrinsic::set_fpenv: { 7002 const DataLayout DLayout = DAG.getDataLayout(); 7003 SDValue Env = getValue(I.getArgOperand(0)); 7004 EVT EnvVT = Env.getValueType(); 7005 Align TempAlign = DAG.getEVTAlign(EnvVT); 7006 SDValue Chain = getRoot(); 7007 // If SET_FPENV is custom or legal, use it. Otherwise use loading 7008 // environment from memory. 7009 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 7010 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 7011 } else { 7012 // Allocate space in stack, copy environment bits into it and use this 7013 // memory in SET_FPENV_MEM. 7014 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 7015 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 7016 auto MPI = 7017 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 7018 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 7019 MachineMemOperand::MOStore); 7020 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7021 MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(), 7022 TempAlign); 7023 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 7024 } 7025 DAG.setRoot(Chain); 7026 return; 7027 } 7028 case Intrinsic::reset_fpenv: 7029 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 7030 return; 7031 case Intrinsic::get_fpmode: 7032 Res = DAG.getNode( 7033 ISD::GET_FPMODE, sdl, 7034 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7035 MVT::Other), 7036 DAG.getRoot()); 7037 setValue(&I, Res); 7038 DAG.setRoot(Res.getValue(1)); 7039 return; 7040 case Intrinsic::set_fpmode: 7041 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 7042 getValue(I.getArgOperand(0))); 7043 DAG.setRoot(Res); 7044 return; 7045 case Intrinsic::reset_fpmode: { 7046 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 7047 DAG.setRoot(Res); 7048 return; 7049 } 7050 case Intrinsic::pcmarker: { 7051 SDValue Tmp = getValue(I.getArgOperand(0)); 7052 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 7053 return; 7054 } 7055 case Intrinsic::readcyclecounter: { 7056 SDValue Op = getRoot(); 7057 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 7058 DAG.getVTList(MVT::i64, MVT::Other), Op); 7059 setValue(&I, Res); 7060 DAG.setRoot(Res.getValue(1)); 7061 return; 7062 } 7063 case Intrinsic::readsteadycounter: { 7064 SDValue Op = getRoot(); 7065 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 7066 DAG.getVTList(MVT::i64, MVT::Other), Op); 7067 setValue(&I, Res); 7068 DAG.setRoot(Res.getValue(1)); 7069 return; 7070 } 7071 case Intrinsic::bitreverse: 7072 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 7073 getValue(I.getArgOperand(0)).getValueType(), 7074 getValue(I.getArgOperand(0)))); 7075 return; 7076 case Intrinsic::bswap: 7077 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 7078 getValue(I.getArgOperand(0)).getValueType(), 7079 getValue(I.getArgOperand(0)))); 7080 return; 7081 case Intrinsic::cttz: { 7082 SDValue Arg = getValue(I.getArgOperand(0)); 7083 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7084 EVT Ty = Arg.getValueType(); 7085 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 7086 sdl, Ty, Arg)); 7087 return; 7088 } 7089 case Intrinsic::ctlz: { 7090 SDValue Arg = getValue(I.getArgOperand(0)); 7091 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 7092 EVT Ty = Arg.getValueType(); 7093 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 7094 sdl, Ty, Arg)); 7095 return; 7096 } 7097 case Intrinsic::ctpop: { 7098 SDValue Arg = getValue(I.getArgOperand(0)); 7099 EVT Ty = Arg.getValueType(); 7100 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 7101 return; 7102 } 7103 case Intrinsic::fshl: 7104 case Intrinsic::fshr: { 7105 bool IsFSHL = Intrinsic == Intrinsic::fshl; 7106 SDValue X = getValue(I.getArgOperand(0)); 7107 SDValue Y = getValue(I.getArgOperand(1)); 7108 SDValue Z = getValue(I.getArgOperand(2)); 7109 EVT VT = X.getValueType(); 7110 7111 if (X == Y) { 7112 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 7113 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 7114 } else { 7115 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 7116 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 7117 } 7118 return; 7119 } 7120 case Intrinsic::sadd_sat: { 7121 SDValue Op1 = getValue(I.getArgOperand(0)); 7122 SDValue Op2 = getValue(I.getArgOperand(1)); 7123 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7124 return; 7125 } 7126 case Intrinsic::uadd_sat: { 7127 SDValue Op1 = getValue(I.getArgOperand(0)); 7128 SDValue Op2 = getValue(I.getArgOperand(1)); 7129 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 7130 return; 7131 } 7132 case Intrinsic::ssub_sat: { 7133 SDValue Op1 = getValue(I.getArgOperand(0)); 7134 SDValue Op2 = getValue(I.getArgOperand(1)); 7135 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7136 return; 7137 } 7138 case Intrinsic::usub_sat: { 7139 SDValue Op1 = getValue(I.getArgOperand(0)); 7140 SDValue Op2 = getValue(I.getArgOperand(1)); 7141 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 7142 return; 7143 } 7144 case Intrinsic::sshl_sat: { 7145 SDValue Op1 = getValue(I.getArgOperand(0)); 7146 SDValue Op2 = getValue(I.getArgOperand(1)); 7147 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7148 return; 7149 } 7150 case Intrinsic::ushl_sat: { 7151 SDValue Op1 = getValue(I.getArgOperand(0)); 7152 SDValue Op2 = getValue(I.getArgOperand(1)); 7153 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 7154 return; 7155 } 7156 case Intrinsic::smul_fix: 7157 case Intrinsic::umul_fix: 7158 case Intrinsic::smul_fix_sat: 7159 case Intrinsic::umul_fix_sat: { 7160 SDValue Op1 = getValue(I.getArgOperand(0)); 7161 SDValue Op2 = getValue(I.getArgOperand(1)); 7162 SDValue Op3 = getValue(I.getArgOperand(2)); 7163 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7164 Op1.getValueType(), Op1, Op2, Op3)); 7165 return; 7166 } 7167 case Intrinsic::sdiv_fix: 7168 case Intrinsic::udiv_fix: 7169 case Intrinsic::sdiv_fix_sat: 7170 case Intrinsic::udiv_fix_sat: { 7171 SDValue Op1 = getValue(I.getArgOperand(0)); 7172 SDValue Op2 = getValue(I.getArgOperand(1)); 7173 SDValue Op3 = getValue(I.getArgOperand(2)); 7174 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 7175 Op1, Op2, Op3, DAG, TLI)); 7176 return; 7177 } 7178 case Intrinsic::smax: { 7179 SDValue Op1 = getValue(I.getArgOperand(0)); 7180 SDValue Op2 = getValue(I.getArgOperand(1)); 7181 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 7182 return; 7183 } 7184 case Intrinsic::smin: { 7185 SDValue Op1 = getValue(I.getArgOperand(0)); 7186 SDValue Op2 = getValue(I.getArgOperand(1)); 7187 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 7188 return; 7189 } 7190 case Intrinsic::umax: { 7191 SDValue Op1 = getValue(I.getArgOperand(0)); 7192 SDValue Op2 = getValue(I.getArgOperand(1)); 7193 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 7194 return; 7195 } 7196 case Intrinsic::umin: { 7197 SDValue Op1 = getValue(I.getArgOperand(0)); 7198 SDValue Op2 = getValue(I.getArgOperand(1)); 7199 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 7200 return; 7201 } 7202 case Intrinsic::abs: { 7203 // TODO: Preserve "int min is poison" arg in SDAG? 7204 SDValue Op1 = getValue(I.getArgOperand(0)); 7205 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 7206 return; 7207 } 7208 case Intrinsic::stacksave: { 7209 SDValue Op = getRoot(); 7210 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7211 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 7212 setValue(&I, Res); 7213 DAG.setRoot(Res.getValue(1)); 7214 return; 7215 } 7216 case Intrinsic::stackrestore: 7217 Res = getValue(I.getArgOperand(0)); 7218 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 7219 return; 7220 case Intrinsic::get_dynamic_area_offset: { 7221 SDValue Op = getRoot(); 7222 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7223 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7224 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 7225 // target. 7226 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 7227 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 7228 " intrinsic!"); 7229 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 7230 Op); 7231 DAG.setRoot(Op); 7232 setValue(&I, Res); 7233 return; 7234 } 7235 case Intrinsic::stackguard: { 7236 MachineFunction &MF = DAG.getMachineFunction(); 7237 const Module &M = *MF.getFunction().getParent(); 7238 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7239 SDValue Chain = getRoot(); 7240 if (TLI.useLoadStackGuardNode()) { 7241 Res = getLoadStackGuard(DAG, sdl, Chain); 7242 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 7243 } else { 7244 const Value *Global = TLI.getSDagStackGuard(M); 7245 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7246 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7247 MachinePointerInfo(Global, 0), Align, 7248 MachineMemOperand::MOVolatile); 7249 } 7250 if (TLI.useStackGuardXorFP()) 7251 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7252 DAG.setRoot(Chain); 7253 setValue(&I, Res); 7254 return; 7255 } 7256 case Intrinsic::stackprotector: { 7257 // Emit code into the DAG to store the stack guard onto the stack. 7258 MachineFunction &MF = DAG.getMachineFunction(); 7259 MachineFrameInfo &MFI = MF.getFrameInfo(); 7260 SDValue Src, Chain = getRoot(); 7261 7262 if (TLI.useLoadStackGuardNode()) 7263 Src = getLoadStackGuard(DAG, sdl, Chain); 7264 else 7265 Src = getValue(I.getArgOperand(0)); // The guard's value. 7266 7267 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7268 7269 int FI = FuncInfo.StaticAllocaMap[Slot]; 7270 MFI.setStackProtectorIndex(FI); 7271 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7272 7273 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7274 7275 // Store the stack protector onto the stack. 7276 Res = DAG.getStore( 7277 Chain, sdl, Src, FIN, 7278 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7279 MaybeAlign(), MachineMemOperand::MOVolatile); 7280 setValue(&I, Res); 7281 DAG.setRoot(Res); 7282 return; 7283 } 7284 case Intrinsic::objectsize: 7285 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7286 7287 case Intrinsic::is_constant: 7288 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7289 7290 case Intrinsic::annotation: 7291 case Intrinsic::ptr_annotation: 7292 case Intrinsic::launder_invariant_group: 7293 case Intrinsic::strip_invariant_group: 7294 // Drop the intrinsic, but forward the value 7295 setValue(&I, getValue(I.getOperand(0))); 7296 return; 7297 7298 case Intrinsic::assume: 7299 case Intrinsic::experimental_noalias_scope_decl: 7300 case Intrinsic::var_annotation: 7301 case Intrinsic::sideeffect: 7302 // Discard annotate attributes, noalias scope declarations, assumptions, and 7303 // artificial side-effects. 7304 return; 7305 7306 case Intrinsic::codeview_annotation: { 7307 // Emit a label associated with this metadata. 7308 MachineFunction &MF = DAG.getMachineFunction(); 7309 MCSymbol *Label = 7310 MF.getMMI().getContext().createTempSymbol("annotation", true); 7311 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7312 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7313 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7314 DAG.setRoot(Res); 7315 return; 7316 } 7317 7318 case Intrinsic::init_trampoline: { 7319 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7320 7321 SDValue Ops[6]; 7322 Ops[0] = getRoot(); 7323 Ops[1] = getValue(I.getArgOperand(0)); 7324 Ops[2] = getValue(I.getArgOperand(1)); 7325 Ops[3] = getValue(I.getArgOperand(2)); 7326 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7327 Ops[5] = DAG.getSrcValue(F); 7328 7329 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7330 7331 DAG.setRoot(Res); 7332 return; 7333 } 7334 case Intrinsic::adjust_trampoline: 7335 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7336 TLI.getPointerTy(DAG.getDataLayout()), 7337 getValue(I.getArgOperand(0)))); 7338 return; 7339 case Intrinsic::gcroot: { 7340 assert(DAG.getMachineFunction().getFunction().hasGC() && 7341 "only valid in functions with gc specified, enforced by Verifier"); 7342 assert(GFI && "implied by previous"); 7343 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7344 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7345 7346 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7347 GFI->addStackRoot(FI->getIndex(), TypeMap); 7348 return; 7349 } 7350 case Intrinsic::gcread: 7351 case Intrinsic::gcwrite: 7352 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7353 case Intrinsic::get_rounding: 7354 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7355 setValue(&I, Res); 7356 DAG.setRoot(Res.getValue(1)); 7357 return; 7358 7359 case Intrinsic::expect: 7360 // Just replace __builtin_expect(exp, c) with EXP. 7361 setValue(&I, getValue(I.getArgOperand(0))); 7362 return; 7363 7364 case Intrinsic::ubsantrap: 7365 case Intrinsic::debugtrap: 7366 case Intrinsic::trap: { 7367 StringRef TrapFuncName = 7368 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7369 if (TrapFuncName.empty()) { 7370 switch (Intrinsic) { 7371 case Intrinsic::trap: 7372 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7373 break; 7374 case Intrinsic::debugtrap: 7375 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7376 break; 7377 case Intrinsic::ubsantrap: 7378 DAG.setRoot(DAG.getNode( 7379 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7380 DAG.getTargetConstant( 7381 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7382 MVT::i32))); 7383 break; 7384 default: llvm_unreachable("unknown trap intrinsic"); 7385 } 7386 return; 7387 } 7388 TargetLowering::ArgListTy Args; 7389 if (Intrinsic == Intrinsic::ubsantrap) { 7390 Args.push_back(TargetLoweringBase::ArgListEntry()); 7391 Args[0].Val = I.getArgOperand(0); 7392 Args[0].Node = getValue(Args[0].Val); 7393 Args[0].Ty = Args[0].Val->getType(); 7394 } 7395 7396 TargetLowering::CallLoweringInfo CLI(DAG); 7397 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7398 CallingConv::C, I.getType(), 7399 DAG.getExternalSymbol(TrapFuncName.data(), 7400 TLI.getPointerTy(DAG.getDataLayout())), 7401 std::move(Args)); 7402 7403 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7404 DAG.setRoot(Result.second); 7405 return; 7406 } 7407 7408 case Intrinsic::allow_runtime_check: 7409 case Intrinsic::allow_ubsan_check: 7410 setValue(&I, getValue(ConstantInt::getTrue(I.getType()))); 7411 return; 7412 7413 case Intrinsic::uadd_with_overflow: 7414 case Intrinsic::sadd_with_overflow: 7415 case Intrinsic::usub_with_overflow: 7416 case Intrinsic::ssub_with_overflow: 7417 case Intrinsic::umul_with_overflow: 7418 case Intrinsic::smul_with_overflow: { 7419 ISD::NodeType Op; 7420 switch (Intrinsic) { 7421 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7422 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7423 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7424 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7425 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7426 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7427 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7428 } 7429 SDValue Op1 = getValue(I.getArgOperand(0)); 7430 SDValue Op2 = getValue(I.getArgOperand(1)); 7431 7432 EVT ResultVT = Op1.getValueType(); 7433 EVT OverflowVT = MVT::i1; 7434 if (ResultVT.isVector()) 7435 OverflowVT = EVT::getVectorVT( 7436 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7437 7438 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7439 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7440 return; 7441 } 7442 case Intrinsic::prefetch: { 7443 SDValue Ops[5]; 7444 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7445 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7446 Ops[0] = DAG.getRoot(); 7447 Ops[1] = getValue(I.getArgOperand(0)); 7448 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7449 MVT::i32); 7450 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7451 MVT::i32); 7452 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7453 MVT::i32); 7454 SDValue Result = DAG.getMemIntrinsicNode( 7455 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7456 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7457 /* align */ std::nullopt, Flags); 7458 7459 // Chain the prefetch in parallel with any pending loads, to stay out of 7460 // the way of later optimizations. 7461 PendingLoads.push_back(Result); 7462 Result = getRoot(); 7463 DAG.setRoot(Result); 7464 return; 7465 } 7466 case Intrinsic::lifetime_start: 7467 case Intrinsic::lifetime_end: { 7468 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7469 // Stack coloring is not enabled in O0, discard region information. 7470 if (TM.getOptLevel() == CodeGenOptLevel::None) 7471 return; 7472 7473 const int64_t ObjectSize = 7474 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7475 Value *const ObjectPtr = I.getArgOperand(1); 7476 SmallVector<const Value *, 4> Allocas; 7477 getUnderlyingObjects(ObjectPtr, Allocas); 7478 7479 for (const Value *Alloca : Allocas) { 7480 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7481 7482 // Could not find an Alloca. 7483 if (!LifetimeObject) 7484 continue; 7485 7486 // First check that the Alloca is static, otherwise it won't have a 7487 // valid frame index. 7488 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7489 if (SI == FuncInfo.StaticAllocaMap.end()) 7490 return; 7491 7492 const int FrameIndex = SI->second; 7493 int64_t Offset; 7494 if (GetPointerBaseWithConstantOffset( 7495 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7496 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7497 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7498 Offset); 7499 DAG.setRoot(Res); 7500 } 7501 return; 7502 } 7503 case Intrinsic::pseudoprobe: { 7504 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7505 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7506 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7507 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7508 DAG.setRoot(Res); 7509 return; 7510 } 7511 case Intrinsic::invariant_start: 7512 // Discard region information. 7513 setValue(&I, 7514 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7515 return; 7516 case Intrinsic::invariant_end: 7517 // Discard region information. 7518 return; 7519 case Intrinsic::clear_cache: { 7520 SDValue InputChain = DAG.getRoot(); 7521 SDValue StartVal = getValue(I.getArgOperand(0)); 7522 SDValue EndVal = getValue(I.getArgOperand(1)); 7523 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other), 7524 {InputChain, StartVal, EndVal}); 7525 setValue(&I, Res); 7526 DAG.setRoot(Res); 7527 return; 7528 } 7529 case Intrinsic::donothing: 7530 case Intrinsic::seh_try_begin: 7531 case Intrinsic::seh_scope_begin: 7532 case Intrinsic::seh_try_end: 7533 case Intrinsic::seh_scope_end: 7534 // ignore 7535 return; 7536 case Intrinsic::experimental_stackmap: 7537 visitStackmap(I); 7538 return; 7539 case Intrinsic::experimental_patchpoint_void: 7540 case Intrinsic::experimental_patchpoint: 7541 visitPatchpoint(I); 7542 return; 7543 case Intrinsic::experimental_gc_statepoint: 7544 LowerStatepoint(cast<GCStatepointInst>(I)); 7545 return; 7546 case Intrinsic::experimental_gc_result: 7547 visitGCResult(cast<GCResultInst>(I)); 7548 return; 7549 case Intrinsic::experimental_gc_relocate: 7550 visitGCRelocate(cast<GCRelocateInst>(I)); 7551 return; 7552 case Intrinsic::instrprof_cover: 7553 llvm_unreachable("instrprof failed to lower a cover"); 7554 case Intrinsic::instrprof_increment: 7555 llvm_unreachable("instrprof failed to lower an increment"); 7556 case Intrinsic::instrprof_timestamp: 7557 llvm_unreachable("instrprof failed to lower a timestamp"); 7558 case Intrinsic::instrprof_value_profile: 7559 llvm_unreachable("instrprof failed to lower a value profiling call"); 7560 case Intrinsic::instrprof_mcdc_parameters: 7561 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7562 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7563 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7564 case Intrinsic::instrprof_mcdc_condbitmap_update: 7565 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7566 case Intrinsic::localescape: { 7567 MachineFunction &MF = DAG.getMachineFunction(); 7568 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7569 7570 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7571 // is the same on all targets. 7572 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7573 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7574 if (isa<ConstantPointerNull>(Arg)) 7575 continue; // Skip null pointers. They represent a hole in index space. 7576 AllocaInst *Slot = cast<AllocaInst>(Arg); 7577 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7578 "can only escape static allocas"); 7579 int FI = FuncInfo.StaticAllocaMap[Slot]; 7580 MCSymbol *FrameAllocSym = 7581 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7582 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7583 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7584 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7585 .addSym(FrameAllocSym) 7586 .addFrameIndex(FI); 7587 } 7588 7589 return; 7590 } 7591 7592 case Intrinsic::localrecover: { 7593 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7594 MachineFunction &MF = DAG.getMachineFunction(); 7595 7596 // Get the symbol that defines the frame offset. 7597 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7598 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7599 unsigned IdxVal = 7600 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7601 MCSymbol *FrameAllocSym = 7602 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7603 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7604 7605 Value *FP = I.getArgOperand(1); 7606 SDValue FPVal = getValue(FP); 7607 EVT PtrVT = FPVal.getValueType(); 7608 7609 // Create a MCSymbol for the label to avoid any target lowering 7610 // that would make this PC relative. 7611 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7612 SDValue OffsetVal = 7613 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7614 7615 // Add the offset to the FP. 7616 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7617 setValue(&I, Add); 7618 7619 return; 7620 } 7621 7622 case Intrinsic::eh_exceptionpointer: 7623 case Intrinsic::eh_exceptioncode: { 7624 // Get the exception pointer vreg, copy from it, and resize it to fit. 7625 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7626 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7627 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7628 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7629 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7630 if (Intrinsic == Intrinsic::eh_exceptioncode) 7631 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7632 setValue(&I, N); 7633 return; 7634 } 7635 case Intrinsic::xray_customevent: { 7636 // Here we want to make sure that the intrinsic behaves as if it has a 7637 // specific calling convention. 7638 const auto &Triple = DAG.getTarget().getTargetTriple(); 7639 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7640 return; 7641 7642 SmallVector<SDValue, 8> Ops; 7643 7644 // We want to say that we always want the arguments in registers. 7645 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7646 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7647 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7648 SDValue Chain = getRoot(); 7649 Ops.push_back(LogEntryVal); 7650 Ops.push_back(StrSizeVal); 7651 Ops.push_back(Chain); 7652 7653 // We need to enforce the calling convention for the callsite, so that 7654 // argument ordering is enforced correctly, and that register allocation can 7655 // see that some registers may be assumed clobbered and have to preserve 7656 // them across calls to the intrinsic. 7657 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7658 sdl, NodeTys, Ops); 7659 SDValue patchableNode = SDValue(MN, 0); 7660 DAG.setRoot(patchableNode); 7661 setValue(&I, patchableNode); 7662 return; 7663 } 7664 case Intrinsic::xray_typedevent: { 7665 // Here we want to make sure that the intrinsic behaves as if it has a 7666 // specific calling convention. 7667 const auto &Triple = DAG.getTarget().getTargetTriple(); 7668 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7669 return; 7670 7671 SmallVector<SDValue, 8> Ops; 7672 7673 // We want to say that we always want the arguments in registers. 7674 // It's unclear to me how manipulating the selection DAG here forces callers 7675 // to provide arguments in registers instead of on the stack. 7676 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7677 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7678 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7679 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7680 SDValue Chain = getRoot(); 7681 Ops.push_back(LogTypeId); 7682 Ops.push_back(LogEntryVal); 7683 Ops.push_back(StrSizeVal); 7684 Ops.push_back(Chain); 7685 7686 // We need to enforce the calling convention for the callsite, so that 7687 // argument ordering is enforced correctly, and that register allocation can 7688 // see that some registers may be assumed clobbered and have to preserve 7689 // them across calls to the intrinsic. 7690 MachineSDNode *MN = DAG.getMachineNode( 7691 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7692 SDValue patchableNode = SDValue(MN, 0); 7693 DAG.setRoot(patchableNode); 7694 setValue(&I, patchableNode); 7695 return; 7696 } 7697 case Intrinsic::experimental_deoptimize: 7698 LowerDeoptimizeCall(&I); 7699 return; 7700 case Intrinsic::experimental_stepvector: 7701 visitStepVector(I); 7702 return; 7703 case Intrinsic::vector_reduce_fadd: 7704 case Intrinsic::vector_reduce_fmul: 7705 case Intrinsic::vector_reduce_add: 7706 case Intrinsic::vector_reduce_mul: 7707 case Intrinsic::vector_reduce_and: 7708 case Intrinsic::vector_reduce_or: 7709 case Intrinsic::vector_reduce_xor: 7710 case Intrinsic::vector_reduce_smax: 7711 case Intrinsic::vector_reduce_smin: 7712 case Intrinsic::vector_reduce_umax: 7713 case Intrinsic::vector_reduce_umin: 7714 case Intrinsic::vector_reduce_fmax: 7715 case Intrinsic::vector_reduce_fmin: 7716 case Intrinsic::vector_reduce_fmaximum: 7717 case Intrinsic::vector_reduce_fminimum: 7718 visitVectorReduce(I, Intrinsic); 7719 return; 7720 7721 case Intrinsic::icall_branch_funnel: { 7722 SmallVector<SDValue, 16> Ops; 7723 Ops.push_back(getValue(I.getArgOperand(0))); 7724 7725 int64_t Offset; 7726 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7727 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7728 if (!Base) 7729 report_fatal_error( 7730 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7731 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7732 7733 struct BranchFunnelTarget { 7734 int64_t Offset; 7735 SDValue Target; 7736 }; 7737 SmallVector<BranchFunnelTarget, 8> Targets; 7738 7739 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7740 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7741 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7742 if (ElemBase != Base) 7743 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7744 "to the same GlobalValue"); 7745 7746 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7747 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7748 if (!GA) 7749 report_fatal_error( 7750 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7751 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7752 GA->getGlobal(), sdl, Val.getValueType(), 7753 GA->getOffset())}); 7754 } 7755 llvm::sort(Targets, 7756 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7757 return T1.Offset < T2.Offset; 7758 }); 7759 7760 for (auto &T : Targets) { 7761 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7762 Ops.push_back(T.Target); 7763 } 7764 7765 Ops.push_back(DAG.getRoot()); // Chain 7766 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7767 MVT::Other, Ops), 7768 0); 7769 DAG.setRoot(N); 7770 setValue(&I, N); 7771 HasTailCall = true; 7772 return; 7773 } 7774 7775 case Intrinsic::wasm_landingpad_index: 7776 // Information this intrinsic contained has been transferred to 7777 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7778 // delete it now. 7779 return; 7780 7781 case Intrinsic::aarch64_settag: 7782 case Intrinsic::aarch64_settag_zero: { 7783 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7784 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7785 SDValue Val = TSI.EmitTargetCodeForSetTag( 7786 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7787 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7788 ZeroMemory); 7789 DAG.setRoot(Val); 7790 setValue(&I, Val); 7791 return; 7792 } 7793 case Intrinsic::amdgcn_cs_chain: { 7794 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7795 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7796 "Non-zero flags not supported yet"); 7797 7798 // At this point we don't care if it's amdgpu_cs_chain or 7799 // amdgpu_cs_chain_preserve. 7800 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7801 7802 Type *RetTy = I.getType(); 7803 assert(RetTy->isVoidTy() && "Should not return"); 7804 7805 SDValue Callee = getValue(I.getOperand(0)); 7806 7807 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7808 // We'll also tack the value of the EXEC mask at the end. 7809 TargetLowering::ArgListTy Args; 7810 Args.reserve(3); 7811 7812 for (unsigned Idx : {2, 3, 1}) { 7813 TargetLowering::ArgListEntry Arg; 7814 Arg.Node = getValue(I.getOperand(Idx)); 7815 Arg.Ty = I.getOperand(Idx)->getType(); 7816 Arg.setAttributes(&I, Idx); 7817 Args.push_back(Arg); 7818 } 7819 7820 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7821 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7822 Args[2].IsInReg = true; // EXEC should be inreg 7823 7824 TargetLowering::CallLoweringInfo CLI(DAG); 7825 CLI.setDebugLoc(getCurSDLoc()) 7826 .setChain(getRoot()) 7827 .setCallee(CC, RetTy, Callee, std::move(Args)) 7828 .setNoReturn(true) 7829 .setTailCall(true) 7830 .setConvergent(I.isConvergent()); 7831 CLI.CB = &I; 7832 std::pair<SDValue, SDValue> Result = 7833 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7834 (void)Result; 7835 assert(!Result.first.getNode() && !Result.second.getNode() && 7836 "Should've lowered as tail call"); 7837 7838 HasTailCall = true; 7839 return; 7840 } 7841 case Intrinsic::ptrmask: { 7842 SDValue Ptr = getValue(I.getOperand(0)); 7843 SDValue Mask = getValue(I.getOperand(1)); 7844 7845 EVT PtrVT = Ptr.getValueType(); 7846 assert(PtrVT == Mask.getValueType() && 7847 "Pointers with different index type are not supported by SDAG"); 7848 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7849 return; 7850 } 7851 case Intrinsic::threadlocal_address: { 7852 setValue(&I, getValue(I.getOperand(0))); 7853 return; 7854 } 7855 case Intrinsic::get_active_lane_mask: { 7856 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7857 SDValue Index = getValue(I.getOperand(0)); 7858 EVT ElementVT = Index.getValueType(); 7859 7860 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7861 visitTargetIntrinsic(I, Intrinsic); 7862 return; 7863 } 7864 7865 SDValue TripCount = getValue(I.getOperand(1)); 7866 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7867 CCVT.getVectorElementCount()); 7868 7869 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7870 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7871 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7872 SDValue VectorInduction = DAG.getNode( 7873 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7874 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7875 VectorTripCount, ISD::CondCode::SETULT); 7876 setValue(&I, SetCC); 7877 return; 7878 } 7879 case Intrinsic::experimental_get_vector_length: { 7880 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7881 "Expected positive VF"); 7882 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7883 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7884 7885 SDValue Count = getValue(I.getOperand(0)); 7886 EVT CountVT = Count.getValueType(); 7887 7888 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7889 visitTargetIntrinsic(I, Intrinsic); 7890 return; 7891 } 7892 7893 // Expand to a umin between the trip count and the maximum elements the type 7894 // can hold. 7895 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7896 7897 // Extend the trip count to at least the result VT. 7898 if (CountVT.bitsLT(VT)) { 7899 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7900 CountVT = VT; 7901 } 7902 7903 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7904 ElementCount::get(VF, IsScalable)); 7905 7906 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7907 // Clip to the result type if needed. 7908 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7909 7910 setValue(&I, Trunc); 7911 return; 7912 } 7913 case Intrinsic::experimental_cttz_elts: { 7914 auto DL = getCurSDLoc(); 7915 SDValue Op = getValue(I.getOperand(0)); 7916 EVT OpVT = Op.getValueType(); 7917 7918 if (!TLI.shouldExpandCttzElements(OpVT)) { 7919 visitTargetIntrinsic(I, Intrinsic); 7920 return; 7921 } 7922 7923 if (OpVT.getScalarType() != MVT::i1) { 7924 // Compare the input vector elements to zero & use to count trailing zeros 7925 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7926 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7927 OpVT.getVectorElementCount()); 7928 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7929 } 7930 7931 // If the zero-is-poison flag is set, we can assume the upper limit 7932 // of the result is VF-1. 7933 bool ZeroIsPoison = 7934 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero(); 7935 ConstantRange VScaleRange(1, true); // Dummy value. 7936 if (isa<ScalableVectorType>(I.getOperand(0)->getType())) 7937 VScaleRange = getVScaleRange(I.getCaller(), 64); 7938 unsigned EltWidth = TLI.getBitWidthForCttzElements( 7939 I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange); 7940 7941 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7942 7943 // Create the new vector type & get the vector length 7944 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7945 OpVT.getVectorElementCount()); 7946 7947 SDValue VL = 7948 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7949 7950 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7951 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7952 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7953 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7954 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7955 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7956 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7957 7958 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7959 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7960 7961 setValue(&I, Ret); 7962 return; 7963 } 7964 case Intrinsic::vector_insert: { 7965 SDValue Vec = getValue(I.getOperand(0)); 7966 SDValue SubVec = getValue(I.getOperand(1)); 7967 SDValue Index = getValue(I.getOperand(2)); 7968 7969 // The intrinsic's index type is i64, but the SDNode requires an index type 7970 // suitable for the target. Convert the index as required. 7971 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7972 if (Index.getValueType() != VectorIdxTy) 7973 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7974 7975 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7976 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7977 Index)); 7978 return; 7979 } 7980 case Intrinsic::vector_extract: { 7981 SDValue Vec = getValue(I.getOperand(0)); 7982 SDValue Index = getValue(I.getOperand(1)); 7983 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7984 7985 // The intrinsic's index type is i64, but the SDNode requires an index type 7986 // suitable for the target. Convert the index as required. 7987 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7988 if (Index.getValueType() != VectorIdxTy) 7989 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7990 7991 setValue(&I, 7992 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7993 return; 7994 } 7995 case Intrinsic::vector_reverse: 7996 visitVectorReverse(I); 7997 return; 7998 case Intrinsic::vector_splice: 7999 visitVectorSplice(I); 8000 return; 8001 case Intrinsic::callbr_landingpad: 8002 visitCallBrLandingPad(I); 8003 return; 8004 case Intrinsic::vector_interleave2: 8005 visitVectorInterleave(I); 8006 return; 8007 case Intrinsic::vector_deinterleave2: 8008 visitVectorDeinterleave(I); 8009 return; 8010 case Intrinsic::experimental_convergence_anchor: 8011 case Intrinsic::experimental_convergence_entry: 8012 case Intrinsic::experimental_convergence_loop: 8013 visitConvergenceControl(I, Intrinsic); 8014 return; 8015 case Intrinsic::experimental_vector_histogram_add: { 8016 visitVectorHistogram(I, Intrinsic); 8017 return; 8018 } 8019 } 8020 } 8021 8022 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 8023 const ConstrainedFPIntrinsic &FPI) { 8024 SDLoc sdl = getCurSDLoc(); 8025 8026 // We do not need to serialize constrained FP intrinsics against 8027 // each other or against (nonvolatile) loads, so they can be 8028 // chained like loads. 8029 SDValue Chain = DAG.getRoot(); 8030 SmallVector<SDValue, 4> Opers; 8031 Opers.push_back(Chain); 8032 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) 8033 Opers.push_back(getValue(FPI.getArgOperand(I))); 8034 8035 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 8036 assert(Result.getNode()->getNumValues() == 2); 8037 8038 // Push node to the appropriate list so that future instructions can be 8039 // chained up correctly. 8040 SDValue OutChain = Result.getValue(1); 8041 switch (EB) { 8042 case fp::ExceptionBehavior::ebIgnore: 8043 // The only reason why ebIgnore nodes still need to be chained is that 8044 // they might depend on the current rounding mode, and therefore must 8045 // not be moved across instruction that may change that mode. 8046 [[fallthrough]]; 8047 case fp::ExceptionBehavior::ebMayTrap: 8048 // These must not be moved across calls or instructions that may change 8049 // floating-point exception masks. 8050 PendingConstrainedFP.push_back(OutChain); 8051 break; 8052 case fp::ExceptionBehavior::ebStrict: 8053 // These must not be moved across calls or instructions that may change 8054 // floating-point exception masks or read floating-point exception flags. 8055 // In addition, they cannot be optimized out even if unused. 8056 PendingConstrainedFPStrict.push_back(OutChain); 8057 break; 8058 } 8059 }; 8060 8061 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8062 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 8063 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 8064 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 8065 8066 SDNodeFlags Flags; 8067 if (EB == fp::ExceptionBehavior::ebIgnore) 8068 Flags.setNoFPExcept(true); 8069 8070 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 8071 Flags.copyFMF(*FPOp); 8072 8073 unsigned Opcode; 8074 switch (FPI.getIntrinsicID()) { 8075 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8076 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8077 case Intrinsic::INTRINSIC: \ 8078 Opcode = ISD::STRICT_##DAGN; \ 8079 break; 8080 #include "llvm/IR/ConstrainedOps.def" 8081 case Intrinsic::experimental_constrained_fmuladd: { 8082 Opcode = ISD::STRICT_FMA; 8083 // Break fmuladd into fmul and fadd. 8084 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 8085 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 8086 Opers.pop_back(); 8087 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 8088 pushOutChain(Mul, EB); 8089 Opcode = ISD::STRICT_FADD; 8090 Opers.clear(); 8091 Opers.push_back(Mul.getValue(1)); 8092 Opers.push_back(Mul.getValue(0)); 8093 Opers.push_back(getValue(FPI.getArgOperand(2))); 8094 } 8095 break; 8096 } 8097 } 8098 8099 // A few strict DAG nodes carry additional operands that are not 8100 // set up by the default code above. 8101 switch (Opcode) { 8102 default: break; 8103 case ISD::STRICT_FP_ROUND: 8104 Opers.push_back( 8105 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 8106 break; 8107 case ISD::STRICT_FSETCC: 8108 case ISD::STRICT_FSETCCS: { 8109 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 8110 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 8111 if (TM.Options.NoNaNsFPMath) 8112 Condition = getFCmpCodeWithoutNaN(Condition); 8113 Opers.push_back(DAG.getCondCode(Condition)); 8114 break; 8115 } 8116 } 8117 8118 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 8119 pushOutChain(Result, EB); 8120 8121 SDValue FPResult = Result.getValue(0); 8122 setValue(&FPI, FPResult); 8123 } 8124 8125 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 8126 std::optional<unsigned> ResOPC; 8127 switch (VPIntrin.getIntrinsicID()) { 8128 case Intrinsic::vp_ctlz: { 8129 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8130 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 8131 break; 8132 } 8133 case Intrinsic::vp_cttz: { 8134 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8135 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 8136 break; 8137 } 8138 case Intrinsic::vp_cttz_elts: { 8139 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 8140 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS; 8141 break; 8142 } 8143 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 8144 case Intrinsic::VPID: \ 8145 ResOPC = ISD::VPSD; \ 8146 break; 8147 #include "llvm/IR/VPIntrinsics.def" 8148 } 8149 8150 if (!ResOPC) 8151 llvm_unreachable( 8152 "Inconsistency: no SDNode available for this VPIntrinsic!"); 8153 8154 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 8155 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 8156 if (VPIntrin.getFastMathFlags().allowReassoc()) 8157 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 8158 : ISD::VP_REDUCE_FMUL; 8159 } 8160 8161 return *ResOPC; 8162 } 8163 8164 void SelectionDAGBuilder::visitVPLoad( 8165 const VPIntrinsic &VPIntrin, EVT VT, 8166 const SmallVectorImpl<SDValue> &OpValues) { 8167 SDLoc DL = getCurSDLoc(); 8168 Value *PtrOperand = VPIntrin.getArgOperand(0); 8169 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8170 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8171 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8172 SDValue LD; 8173 // Do not serialize variable-length loads of constant memory with 8174 // anything. 8175 if (!Alignment) 8176 Alignment = DAG.getEVTAlign(VT); 8177 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8178 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8179 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8180 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8181 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8182 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8183 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 8184 MMO, false /*IsExpanding */); 8185 if (AddToChain) 8186 PendingLoads.push_back(LD.getValue(1)); 8187 setValue(&VPIntrin, LD); 8188 } 8189 8190 void SelectionDAGBuilder::visitVPGather( 8191 const VPIntrinsic &VPIntrin, EVT VT, 8192 const SmallVectorImpl<SDValue> &OpValues) { 8193 SDLoc DL = getCurSDLoc(); 8194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8195 Value *PtrOperand = VPIntrin.getArgOperand(0); 8196 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8197 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8198 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8199 SDValue LD; 8200 if (!Alignment) 8201 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8202 unsigned AS = 8203 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8204 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8205 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8206 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8207 SDValue Base, Index, Scale; 8208 ISD::MemIndexType IndexType; 8209 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8210 this, VPIntrin.getParent(), 8211 VT.getScalarStoreSize()); 8212 if (!UniformBase) { 8213 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8214 Index = getValue(PtrOperand); 8215 IndexType = ISD::SIGNED_SCALED; 8216 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8217 } 8218 EVT IdxVT = Index.getValueType(); 8219 EVT EltTy = IdxVT.getVectorElementType(); 8220 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8221 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8222 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8223 } 8224 LD = DAG.getGatherVP( 8225 DAG.getVTList(VT, MVT::Other), VT, DL, 8226 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 8227 IndexType); 8228 PendingLoads.push_back(LD.getValue(1)); 8229 setValue(&VPIntrin, LD); 8230 } 8231 8232 void SelectionDAGBuilder::visitVPStore( 8233 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8234 SDLoc DL = getCurSDLoc(); 8235 Value *PtrOperand = VPIntrin.getArgOperand(1); 8236 EVT VT = OpValues[0].getValueType(); 8237 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8238 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8239 SDValue ST; 8240 if (!Alignment) 8241 Alignment = DAG.getEVTAlign(VT); 8242 SDValue Ptr = OpValues[1]; 8243 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 8244 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8245 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8246 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8247 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 8248 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 8249 /* IsTruncating */ false, /*IsCompressing*/ false); 8250 DAG.setRoot(ST); 8251 setValue(&VPIntrin, ST); 8252 } 8253 8254 void SelectionDAGBuilder::visitVPScatter( 8255 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8256 SDLoc DL = getCurSDLoc(); 8257 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8258 Value *PtrOperand = VPIntrin.getArgOperand(1); 8259 EVT VT = OpValues[0].getValueType(); 8260 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8261 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8262 SDValue ST; 8263 if (!Alignment) 8264 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8265 unsigned AS = 8266 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8267 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8268 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8269 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8270 SDValue Base, Index, Scale; 8271 ISD::MemIndexType IndexType; 8272 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8273 this, VPIntrin.getParent(), 8274 VT.getScalarStoreSize()); 8275 if (!UniformBase) { 8276 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8277 Index = getValue(PtrOperand); 8278 IndexType = ISD::SIGNED_SCALED; 8279 Scale = 8280 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8281 } 8282 EVT IdxVT = Index.getValueType(); 8283 EVT EltTy = IdxVT.getVectorElementType(); 8284 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8285 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8286 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8287 } 8288 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8289 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8290 OpValues[2], OpValues[3]}, 8291 MMO, IndexType); 8292 DAG.setRoot(ST); 8293 setValue(&VPIntrin, ST); 8294 } 8295 8296 void SelectionDAGBuilder::visitVPStridedLoad( 8297 const VPIntrinsic &VPIntrin, EVT VT, 8298 const SmallVectorImpl<SDValue> &OpValues) { 8299 SDLoc DL = getCurSDLoc(); 8300 Value *PtrOperand = VPIntrin.getArgOperand(0); 8301 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8302 if (!Alignment) 8303 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8304 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8305 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8306 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8307 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8308 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8309 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8310 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8311 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 8312 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges); 8313 8314 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8315 OpValues[2], OpValues[3], MMO, 8316 false /*IsExpanding*/); 8317 8318 if (AddToChain) 8319 PendingLoads.push_back(LD.getValue(1)); 8320 setValue(&VPIntrin, LD); 8321 } 8322 8323 void SelectionDAGBuilder::visitVPStridedStore( 8324 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8325 SDLoc DL = getCurSDLoc(); 8326 Value *PtrOperand = VPIntrin.getArgOperand(1); 8327 EVT VT = OpValues[0].getValueType(); 8328 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8329 if (!Alignment) 8330 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8331 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8332 unsigned AS = PtrOperand->getType()->getPointerAddressSpace(); 8333 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8334 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8335 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo); 8336 8337 SDValue ST = DAG.getStridedStoreVP( 8338 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8339 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8340 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8341 /*IsCompressing*/ false); 8342 8343 DAG.setRoot(ST); 8344 setValue(&VPIntrin, ST); 8345 } 8346 8347 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8349 SDLoc DL = getCurSDLoc(); 8350 8351 ISD::CondCode Condition; 8352 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8353 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8354 if (IsFP) { 8355 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8356 // flags, but calls that don't return floating-point types can't be 8357 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8358 Condition = getFCmpCondCode(CondCode); 8359 if (TM.Options.NoNaNsFPMath) 8360 Condition = getFCmpCodeWithoutNaN(Condition); 8361 } else { 8362 Condition = getICmpCondCode(CondCode); 8363 } 8364 8365 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8366 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8367 // #2 is the condition code 8368 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8369 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8370 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8371 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8372 "Unexpected target EVL type"); 8373 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8374 8375 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8376 VPIntrin.getType()); 8377 setValue(&VPIntrin, 8378 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8379 } 8380 8381 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8382 const VPIntrinsic &VPIntrin) { 8383 SDLoc DL = getCurSDLoc(); 8384 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8385 8386 auto IID = VPIntrin.getIntrinsicID(); 8387 8388 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8389 return visitVPCmp(*CmpI); 8390 8391 SmallVector<EVT, 4> ValueVTs; 8392 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8393 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8394 SDVTList VTs = DAG.getVTList(ValueVTs); 8395 8396 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8397 8398 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8399 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8400 "Unexpected target EVL type"); 8401 8402 // Request operands. 8403 SmallVector<SDValue, 7> OpValues; 8404 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8405 auto Op = getValue(VPIntrin.getArgOperand(I)); 8406 if (I == EVLParamPos) 8407 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8408 OpValues.push_back(Op); 8409 } 8410 8411 switch (Opcode) { 8412 default: { 8413 SDNodeFlags SDFlags; 8414 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8415 SDFlags.copyFMF(*FPMO); 8416 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8417 setValue(&VPIntrin, Result); 8418 break; 8419 } 8420 case ISD::VP_LOAD: 8421 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8422 break; 8423 case ISD::VP_GATHER: 8424 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8425 break; 8426 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8427 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8428 break; 8429 case ISD::VP_STORE: 8430 visitVPStore(VPIntrin, OpValues); 8431 break; 8432 case ISD::VP_SCATTER: 8433 visitVPScatter(VPIntrin, OpValues); 8434 break; 8435 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8436 visitVPStridedStore(VPIntrin, OpValues); 8437 break; 8438 case ISD::VP_FMULADD: { 8439 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8440 SDNodeFlags SDFlags; 8441 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8442 SDFlags.copyFMF(*FPMO); 8443 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8444 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8445 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8446 } else { 8447 SDValue Mul = DAG.getNode( 8448 ISD::VP_FMUL, DL, VTs, 8449 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8450 SDValue Add = 8451 DAG.getNode(ISD::VP_FADD, DL, VTs, 8452 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8453 setValue(&VPIntrin, Add); 8454 } 8455 break; 8456 } 8457 case ISD::VP_IS_FPCLASS: { 8458 const DataLayout DLayout = DAG.getDataLayout(); 8459 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8460 auto Constant = OpValues[1]->getAsZExtVal(); 8461 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8462 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8463 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8464 setValue(&VPIntrin, V); 8465 return; 8466 } 8467 case ISD::VP_INTTOPTR: { 8468 SDValue N = OpValues[0]; 8469 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8470 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8471 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8472 OpValues[2]); 8473 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8474 OpValues[2]); 8475 setValue(&VPIntrin, N); 8476 break; 8477 } 8478 case ISD::VP_PTRTOINT: { 8479 SDValue N = OpValues[0]; 8480 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8481 VPIntrin.getType()); 8482 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8483 VPIntrin.getOperand(0)->getType()); 8484 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8485 OpValues[2]); 8486 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8487 OpValues[2]); 8488 setValue(&VPIntrin, N); 8489 break; 8490 } 8491 case ISD::VP_ABS: 8492 case ISD::VP_CTLZ: 8493 case ISD::VP_CTLZ_ZERO_UNDEF: 8494 case ISD::VP_CTTZ: 8495 case ISD::VP_CTTZ_ZERO_UNDEF: 8496 case ISD::VP_CTTZ_ELTS_ZERO_UNDEF: 8497 case ISD::VP_CTTZ_ELTS: { 8498 SDValue Result = 8499 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8500 setValue(&VPIntrin, Result); 8501 break; 8502 } 8503 } 8504 } 8505 8506 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8507 const BasicBlock *EHPadBB, 8508 MCSymbol *&BeginLabel) { 8509 MachineFunction &MF = DAG.getMachineFunction(); 8510 MachineModuleInfo &MMI = MF.getMMI(); 8511 8512 // Insert a label before the invoke call to mark the try range. This can be 8513 // used to detect deletion of the invoke via the MachineModuleInfo. 8514 BeginLabel = MMI.getContext().createTempSymbol(); 8515 8516 // For SjLj, keep track of which landing pads go with which invokes 8517 // so as to maintain the ordering of pads in the LSDA. 8518 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8519 if (CallSiteIndex) { 8520 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8521 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8522 8523 // Now that the call site is handled, stop tracking it. 8524 MMI.setCurrentCallSite(0); 8525 } 8526 8527 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8528 } 8529 8530 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8531 const BasicBlock *EHPadBB, 8532 MCSymbol *BeginLabel) { 8533 assert(BeginLabel && "BeginLabel should've been set"); 8534 8535 MachineFunction &MF = DAG.getMachineFunction(); 8536 MachineModuleInfo &MMI = MF.getMMI(); 8537 8538 // Insert a label at the end of the invoke call to mark the try range. This 8539 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8540 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8541 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8542 8543 // Inform MachineModuleInfo of range. 8544 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8545 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8546 // actually use outlined funclets and their LSDA info style. 8547 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8548 assert(II && "II should've been set"); 8549 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8550 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8551 } else if (!isScopedEHPersonality(Pers)) { 8552 assert(EHPadBB); 8553 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8554 } 8555 8556 return Chain; 8557 } 8558 8559 std::pair<SDValue, SDValue> 8560 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8561 const BasicBlock *EHPadBB) { 8562 MCSymbol *BeginLabel = nullptr; 8563 8564 if (EHPadBB) { 8565 // Both PendingLoads and PendingExports must be flushed here; 8566 // this call might not return. 8567 (void)getRoot(); 8568 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8569 CLI.setChain(getRoot()); 8570 } 8571 8572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8573 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8574 8575 assert((CLI.IsTailCall || Result.second.getNode()) && 8576 "Non-null chain expected with non-tail call!"); 8577 assert((Result.second.getNode() || !Result.first.getNode()) && 8578 "Null value expected with tail call!"); 8579 8580 if (!Result.second.getNode()) { 8581 // As a special case, a null chain means that a tail call has been emitted 8582 // and the DAG root is already updated. 8583 HasTailCall = true; 8584 8585 // Since there's no actual continuation from this block, nothing can be 8586 // relying on us setting vregs for them. 8587 PendingExports.clear(); 8588 } else { 8589 DAG.setRoot(Result.second); 8590 } 8591 8592 if (EHPadBB) { 8593 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8594 BeginLabel)); 8595 } 8596 8597 return Result; 8598 } 8599 8600 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8601 bool isTailCall, 8602 bool isMustTailCall, 8603 const BasicBlock *EHPadBB) { 8604 auto &DL = DAG.getDataLayout(); 8605 FunctionType *FTy = CB.getFunctionType(); 8606 Type *RetTy = CB.getType(); 8607 8608 TargetLowering::ArgListTy Args; 8609 Args.reserve(CB.arg_size()); 8610 8611 const Value *SwiftErrorVal = nullptr; 8612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8613 8614 if (isTailCall) { 8615 // Avoid emitting tail calls in functions with the disable-tail-calls 8616 // attribute. 8617 auto *Caller = CB.getParent()->getParent(); 8618 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8619 "true" && !isMustTailCall) 8620 isTailCall = false; 8621 8622 // We can't tail call inside a function with a swifterror argument. Lowering 8623 // does not support this yet. It would have to move into the swifterror 8624 // register before the call. 8625 if (TLI.supportSwiftError() && 8626 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8627 isTailCall = false; 8628 } 8629 8630 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8631 TargetLowering::ArgListEntry Entry; 8632 const Value *V = *I; 8633 8634 // Skip empty types 8635 if (V->getType()->isEmptyTy()) 8636 continue; 8637 8638 SDValue ArgNode = getValue(V); 8639 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8640 8641 Entry.setAttributes(&CB, I - CB.arg_begin()); 8642 8643 // Use swifterror virtual register as input to the call. 8644 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8645 SwiftErrorVal = V; 8646 // We find the virtual register for the actual swifterror argument. 8647 // Instead of using the Value, we use the virtual register instead. 8648 Entry.Node = 8649 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8650 EVT(TLI.getPointerTy(DL))); 8651 } 8652 8653 Args.push_back(Entry); 8654 8655 // If we have an explicit sret argument that is an Instruction, (i.e., it 8656 // might point to function-local memory), we can't meaningfully tail-call. 8657 if (Entry.IsSRet && isa<Instruction>(V)) 8658 isTailCall = false; 8659 } 8660 8661 // If call site has a cfguardtarget operand bundle, create and add an 8662 // additional ArgListEntry. 8663 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8664 TargetLowering::ArgListEntry Entry; 8665 Value *V = Bundle->Inputs[0]; 8666 SDValue ArgNode = getValue(V); 8667 Entry.Node = ArgNode; 8668 Entry.Ty = V->getType(); 8669 Entry.IsCFGuardTarget = true; 8670 Args.push_back(Entry); 8671 } 8672 8673 // Check if target-independent constraints permit a tail call here. 8674 // Target-dependent constraints are checked within TLI->LowerCallTo. 8675 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8676 isTailCall = false; 8677 8678 // Disable tail calls if there is an swifterror argument. Targets have not 8679 // been updated to support tail calls. 8680 if (TLI.supportSwiftError() && SwiftErrorVal) 8681 isTailCall = false; 8682 8683 ConstantInt *CFIType = nullptr; 8684 if (CB.isIndirectCall()) { 8685 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8686 if (!TLI.supportKCFIBundles()) 8687 report_fatal_error( 8688 "Target doesn't support calls with kcfi operand bundles."); 8689 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8690 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8691 } 8692 } 8693 8694 SDValue ConvControlToken; 8695 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8696 auto *Token = Bundle->Inputs[0].get(); 8697 ConvControlToken = getValue(Token); 8698 } 8699 8700 TargetLowering::CallLoweringInfo CLI(DAG); 8701 CLI.setDebugLoc(getCurSDLoc()) 8702 .setChain(getRoot()) 8703 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8704 .setTailCall(isTailCall) 8705 .setConvergent(CB.isConvergent()) 8706 .setIsPreallocated( 8707 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8708 .setCFIType(CFIType) 8709 .setConvergenceControlToken(ConvControlToken); 8710 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8711 8712 if (Result.first.getNode()) { 8713 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8714 setValue(&CB, Result.first); 8715 } 8716 8717 // The last element of CLI.InVals has the SDValue for swifterror return. 8718 // Here we copy it to a virtual register and update SwiftErrorMap for 8719 // book-keeping. 8720 if (SwiftErrorVal && TLI.supportSwiftError()) { 8721 // Get the last element of InVals. 8722 SDValue Src = CLI.InVals.back(); 8723 Register VReg = 8724 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8725 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8726 DAG.setRoot(CopyNode); 8727 } 8728 } 8729 8730 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8731 SelectionDAGBuilder &Builder) { 8732 // Check to see if this load can be trivially constant folded, e.g. if the 8733 // input is from a string literal. 8734 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8735 // Cast pointer to the type we really want to load. 8736 Type *LoadTy = 8737 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8738 if (LoadVT.isVector()) 8739 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8740 8741 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8742 PointerType::getUnqual(LoadTy)); 8743 8744 if (const Constant *LoadCst = 8745 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8746 LoadTy, Builder.DAG.getDataLayout())) 8747 return Builder.getValue(LoadCst); 8748 } 8749 8750 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8751 // still constant memory, the input chain can be the entry node. 8752 SDValue Root; 8753 bool ConstantMemory = false; 8754 8755 // Do not serialize (non-volatile) loads of constant memory with anything. 8756 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8757 Root = Builder.DAG.getEntryNode(); 8758 ConstantMemory = true; 8759 } else { 8760 // Do not serialize non-volatile loads against each other. 8761 Root = Builder.DAG.getRoot(); 8762 } 8763 8764 SDValue Ptr = Builder.getValue(PtrVal); 8765 SDValue LoadVal = 8766 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8767 MachinePointerInfo(PtrVal), Align(1)); 8768 8769 if (!ConstantMemory) 8770 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8771 return LoadVal; 8772 } 8773 8774 /// Record the value for an instruction that produces an integer result, 8775 /// converting the type where necessary. 8776 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8777 SDValue Value, 8778 bool IsSigned) { 8779 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8780 I.getType(), true); 8781 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8782 setValue(&I, Value); 8783 } 8784 8785 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8786 /// true and lower it. Otherwise return false, and it will be lowered like a 8787 /// normal call. 8788 /// The caller already checked that \p I calls the appropriate LibFunc with a 8789 /// correct prototype. 8790 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8791 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8792 const Value *Size = I.getArgOperand(2); 8793 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8794 if (CSize && CSize->getZExtValue() == 0) { 8795 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8796 I.getType(), true); 8797 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8798 return true; 8799 } 8800 8801 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8802 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8803 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8804 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8805 if (Res.first.getNode()) { 8806 processIntegerCallValue(I, Res.first, true); 8807 PendingLoads.push_back(Res.second); 8808 return true; 8809 } 8810 8811 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8812 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8813 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8814 return false; 8815 8816 // If the target has a fast compare for the given size, it will return a 8817 // preferred load type for that size. Require that the load VT is legal and 8818 // that the target supports unaligned loads of that type. Otherwise, return 8819 // INVALID. 8820 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8821 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8822 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8823 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8824 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8825 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8826 // TODO: Check alignment of src and dest ptrs. 8827 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8828 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8829 if (!TLI.isTypeLegal(LVT) || 8830 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8831 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8832 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8833 } 8834 8835 return LVT; 8836 }; 8837 8838 // This turns into unaligned loads. We only do this if the target natively 8839 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8840 // we'll only produce a small number of byte loads. 8841 MVT LoadVT; 8842 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8843 switch (NumBitsToCompare) { 8844 default: 8845 return false; 8846 case 16: 8847 LoadVT = MVT::i16; 8848 break; 8849 case 32: 8850 LoadVT = MVT::i32; 8851 break; 8852 case 64: 8853 case 128: 8854 case 256: 8855 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8856 break; 8857 } 8858 8859 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8860 return false; 8861 8862 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8863 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8864 8865 // Bitcast to a wide integer type if the loads are vectors. 8866 if (LoadVT.isVector()) { 8867 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8868 LoadL = DAG.getBitcast(CmpVT, LoadL); 8869 LoadR = DAG.getBitcast(CmpVT, LoadR); 8870 } 8871 8872 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8873 processIntegerCallValue(I, Cmp, false); 8874 return true; 8875 } 8876 8877 /// See if we can lower a memchr call into an optimized form. If so, return 8878 /// true and lower it. Otherwise return false, and it will be lowered like a 8879 /// normal call. 8880 /// The caller already checked that \p I calls the appropriate LibFunc with a 8881 /// correct prototype. 8882 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8883 const Value *Src = I.getArgOperand(0); 8884 const Value *Char = I.getArgOperand(1); 8885 const Value *Length = I.getArgOperand(2); 8886 8887 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8888 std::pair<SDValue, SDValue> Res = 8889 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8890 getValue(Src), getValue(Char), getValue(Length), 8891 MachinePointerInfo(Src)); 8892 if (Res.first.getNode()) { 8893 setValue(&I, Res.first); 8894 PendingLoads.push_back(Res.second); 8895 return true; 8896 } 8897 8898 return false; 8899 } 8900 8901 /// See if we can lower a mempcpy call into an optimized form. If so, return 8902 /// true and lower it. Otherwise return false, and it will be lowered like a 8903 /// normal call. 8904 /// The caller already checked that \p I calls the appropriate LibFunc with a 8905 /// correct prototype. 8906 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8907 SDValue Dst = getValue(I.getArgOperand(0)); 8908 SDValue Src = getValue(I.getArgOperand(1)); 8909 SDValue Size = getValue(I.getArgOperand(2)); 8910 8911 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8912 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8913 // DAG::getMemcpy needs Alignment to be defined. 8914 Align Alignment = std::min(DstAlign, SrcAlign); 8915 8916 SDLoc sdl = getCurSDLoc(); 8917 8918 // In the mempcpy context we need to pass in a false value for isTailCall 8919 // because the return pointer needs to be adjusted by the size of 8920 // the copied memory. 8921 SDValue Root = getMemoryRoot(); 8922 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8923 /*isTailCall=*/false, 8924 MachinePointerInfo(I.getArgOperand(0)), 8925 MachinePointerInfo(I.getArgOperand(1)), 8926 I.getAAMetadata()); 8927 assert(MC.getNode() != nullptr && 8928 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8929 DAG.setRoot(MC); 8930 8931 // Check if Size needs to be truncated or extended. 8932 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8933 8934 // Adjust return pointer to point just past the last dst byte. 8935 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8936 Dst, Size); 8937 setValue(&I, DstPlusSize); 8938 return true; 8939 } 8940 8941 /// See if we can lower a strcpy call into an optimized form. If so, return 8942 /// true and lower it, otherwise return false and it will be lowered like a 8943 /// normal call. 8944 /// The caller already checked that \p I calls the appropriate LibFunc with a 8945 /// correct prototype. 8946 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8947 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8948 8949 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8950 std::pair<SDValue, SDValue> Res = 8951 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8952 getValue(Arg0), getValue(Arg1), 8953 MachinePointerInfo(Arg0), 8954 MachinePointerInfo(Arg1), isStpcpy); 8955 if (Res.first.getNode()) { 8956 setValue(&I, Res.first); 8957 DAG.setRoot(Res.second); 8958 return true; 8959 } 8960 8961 return false; 8962 } 8963 8964 /// See if we can lower a strcmp call into an optimized form. If so, return 8965 /// true and lower it, otherwise return false and it will be lowered like a 8966 /// normal call. 8967 /// The caller already checked that \p I calls the appropriate LibFunc with a 8968 /// correct prototype. 8969 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8970 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8971 8972 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8973 std::pair<SDValue, SDValue> Res = 8974 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8975 getValue(Arg0), getValue(Arg1), 8976 MachinePointerInfo(Arg0), 8977 MachinePointerInfo(Arg1)); 8978 if (Res.first.getNode()) { 8979 processIntegerCallValue(I, Res.first, true); 8980 PendingLoads.push_back(Res.second); 8981 return true; 8982 } 8983 8984 return false; 8985 } 8986 8987 /// See if we can lower a strlen call into an optimized form. If so, return 8988 /// true and lower it, otherwise return false and it will be lowered like a 8989 /// normal call. 8990 /// The caller already checked that \p I calls the appropriate LibFunc with a 8991 /// correct prototype. 8992 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8993 const Value *Arg0 = I.getArgOperand(0); 8994 8995 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8996 std::pair<SDValue, SDValue> Res = 8997 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8998 getValue(Arg0), MachinePointerInfo(Arg0)); 8999 if (Res.first.getNode()) { 9000 processIntegerCallValue(I, Res.first, false); 9001 PendingLoads.push_back(Res.second); 9002 return true; 9003 } 9004 9005 return false; 9006 } 9007 9008 /// See if we can lower a strnlen call into an optimized form. If so, return 9009 /// true and lower it, otherwise return false and it will be lowered like a 9010 /// normal call. 9011 /// The caller already checked that \p I calls the appropriate LibFunc with a 9012 /// correct prototype. 9013 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 9014 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 9015 9016 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 9017 std::pair<SDValue, SDValue> Res = 9018 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 9019 getValue(Arg0), getValue(Arg1), 9020 MachinePointerInfo(Arg0)); 9021 if (Res.first.getNode()) { 9022 processIntegerCallValue(I, Res.first, false); 9023 PendingLoads.push_back(Res.second); 9024 return true; 9025 } 9026 9027 return false; 9028 } 9029 9030 /// See if we can lower a unary floating-point operation into an SDNode with 9031 /// the specified Opcode. If so, return true and lower it, otherwise return 9032 /// false and it will be lowered like a normal call. 9033 /// The caller already checked that \p I calls the appropriate LibFunc with a 9034 /// correct prototype. 9035 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 9036 unsigned Opcode) { 9037 // We already checked this call's prototype; verify it doesn't modify errno. 9038 if (!I.onlyReadsMemory()) 9039 return false; 9040 9041 SDNodeFlags Flags; 9042 Flags.copyFMF(cast<FPMathOperator>(I)); 9043 9044 SDValue Tmp = getValue(I.getArgOperand(0)); 9045 setValue(&I, 9046 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 9047 return true; 9048 } 9049 9050 /// See if we can lower a binary floating-point operation into an SDNode with 9051 /// the specified Opcode. If so, return true and lower it. Otherwise return 9052 /// false, and it will be lowered like a normal call. 9053 /// The caller already checked that \p I calls the appropriate LibFunc with a 9054 /// correct prototype. 9055 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 9056 unsigned Opcode) { 9057 // We already checked this call's prototype; verify it doesn't modify errno. 9058 if (!I.onlyReadsMemory()) 9059 return false; 9060 9061 SDNodeFlags Flags; 9062 Flags.copyFMF(cast<FPMathOperator>(I)); 9063 9064 SDValue Tmp0 = getValue(I.getArgOperand(0)); 9065 SDValue Tmp1 = getValue(I.getArgOperand(1)); 9066 EVT VT = Tmp0.getValueType(); 9067 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 9068 return true; 9069 } 9070 9071 void SelectionDAGBuilder::visitCall(const CallInst &I) { 9072 // Handle inline assembly differently. 9073 if (I.isInlineAsm()) { 9074 visitInlineAsm(I); 9075 return; 9076 } 9077 9078 diagnoseDontCall(I); 9079 9080 if (Function *F = I.getCalledFunction()) { 9081 if (F->isDeclaration()) { 9082 // Is this an LLVM intrinsic or a target-specific intrinsic? 9083 unsigned IID = F->getIntrinsicID(); 9084 if (!IID) 9085 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 9086 IID = II->getIntrinsicID(F); 9087 9088 if (IID) { 9089 visitIntrinsicCall(I, IID); 9090 return; 9091 } 9092 } 9093 9094 // Check for well-known libc/libm calls. If the function is internal, it 9095 // can't be a library call. Don't do the check if marked as nobuiltin for 9096 // some reason or the call site requires strict floating point semantics. 9097 LibFunc Func; 9098 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 9099 F->hasName() && LibInfo->getLibFunc(*F, Func) && 9100 LibInfo->hasOptimizedCodeGen(Func)) { 9101 switch (Func) { 9102 default: break; 9103 case LibFunc_bcmp: 9104 if (visitMemCmpBCmpCall(I)) 9105 return; 9106 break; 9107 case LibFunc_copysign: 9108 case LibFunc_copysignf: 9109 case LibFunc_copysignl: 9110 // We already checked this call's prototype; verify it doesn't modify 9111 // errno. 9112 if (I.onlyReadsMemory()) { 9113 SDValue LHS = getValue(I.getArgOperand(0)); 9114 SDValue RHS = getValue(I.getArgOperand(1)); 9115 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 9116 LHS.getValueType(), LHS, RHS)); 9117 return; 9118 } 9119 break; 9120 case LibFunc_fabs: 9121 case LibFunc_fabsf: 9122 case LibFunc_fabsl: 9123 if (visitUnaryFloatCall(I, ISD::FABS)) 9124 return; 9125 break; 9126 case LibFunc_fmin: 9127 case LibFunc_fminf: 9128 case LibFunc_fminl: 9129 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 9130 return; 9131 break; 9132 case LibFunc_fmax: 9133 case LibFunc_fmaxf: 9134 case LibFunc_fmaxl: 9135 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 9136 return; 9137 break; 9138 case LibFunc_sin: 9139 case LibFunc_sinf: 9140 case LibFunc_sinl: 9141 if (visitUnaryFloatCall(I, ISD::FSIN)) 9142 return; 9143 break; 9144 case LibFunc_cos: 9145 case LibFunc_cosf: 9146 case LibFunc_cosl: 9147 if (visitUnaryFloatCall(I, ISD::FCOS)) 9148 return; 9149 break; 9150 case LibFunc_sqrt: 9151 case LibFunc_sqrtf: 9152 case LibFunc_sqrtl: 9153 case LibFunc_sqrt_finite: 9154 case LibFunc_sqrtf_finite: 9155 case LibFunc_sqrtl_finite: 9156 if (visitUnaryFloatCall(I, ISD::FSQRT)) 9157 return; 9158 break; 9159 case LibFunc_floor: 9160 case LibFunc_floorf: 9161 case LibFunc_floorl: 9162 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 9163 return; 9164 break; 9165 case LibFunc_nearbyint: 9166 case LibFunc_nearbyintf: 9167 case LibFunc_nearbyintl: 9168 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 9169 return; 9170 break; 9171 case LibFunc_ceil: 9172 case LibFunc_ceilf: 9173 case LibFunc_ceill: 9174 if (visitUnaryFloatCall(I, ISD::FCEIL)) 9175 return; 9176 break; 9177 case LibFunc_rint: 9178 case LibFunc_rintf: 9179 case LibFunc_rintl: 9180 if (visitUnaryFloatCall(I, ISD::FRINT)) 9181 return; 9182 break; 9183 case LibFunc_round: 9184 case LibFunc_roundf: 9185 case LibFunc_roundl: 9186 if (visitUnaryFloatCall(I, ISD::FROUND)) 9187 return; 9188 break; 9189 case LibFunc_trunc: 9190 case LibFunc_truncf: 9191 case LibFunc_truncl: 9192 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 9193 return; 9194 break; 9195 case LibFunc_log2: 9196 case LibFunc_log2f: 9197 case LibFunc_log2l: 9198 if (visitUnaryFloatCall(I, ISD::FLOG2)) 9199 return; 9200 break; 9201 case LibFunc_exp2: 9202 case LibFunc_exp2f: 9203 case LibFunc_exp2l: 9204 if (visitUnaryFloatCall(I, ISD::FEXP2)) 9205 return; 9206 break; 9207 case LibFunc_exp10: 9208 case LibFunc_exp10f: 9209 case LibFunc_exp10l: 9210 if (visitUnaryFloatCall(I, ISD::FEXP10)) 9211 return; 9212 break; 9213 case LibFunc_ldexp: 9214 case LibFunc_ldexpf: 9215 case LibFunc_ldexpl: 9216 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 9217 return; 9218 break; 9219 case LibFunc_memcmp: 9220 if (visitMemCmpBCmpCall(I)) 9221 return; 9222 break; 9223 case LibFunc_mempcpy: 9224 if (visitMemPCpyCall(I)) 9225 return; 9226 break; 9227 case LibFunc_memchr: 9228 if (visitMemChrCall(I)) 9229 return; 9230 break; 9231 case LibFunc_strcpy: 9232 if (visitStrCpyCall(I, false)) 9233 return; 9234 break; 9235 case LibFunc_stpcpy: 9236 if (visitStrCpyCall(I, true)) 9237 return; 9238 break; 9239 case LibFunc_strcmp: 9240 if (visitStrCmpCall(I)) 9241 return; 9242 break; 9243 case LibFunc_strlen: 9244 if (visitStrLenCall(I)) 9245 return; 9246 break; 9247 case LibFunc_strnlen: 9248 if (visitStrNLenCall(I)) 9249 return; 9250 break; 9251 } 9252 } 9253 } 9254 9255 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9256 // have to do anything here to lower funclet bundles. 9257 // CFGuardTarget bundles are lowered in LowerCallTo. 9258 assert(!I.hasOperandBundlesOtherThan( 9259 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9260 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9261 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9262 LLVMContext::OB_convergencectrl}) && 9263 "Cannot lower calls with arbitrary operand bundles!"); 9264 9265 SDValue Callee = getValue(I.getCalledOperand()); 9266 9267 if (I.hasDeoptState()) 9268 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9269 else 9270 // Check if we can potentially perform a tail call. More detailed checking 9271 // is be done within LowerCallTo, after more information about the call is 9272 // known. 9273 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9274 } 9275 9276 namespace { 9277 9278 /// AsmOperandInfo - This contains information for each constraint that we are 9279 /// lowering. 9280 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9281 public: 9282 /// CallOperand - If this is the result output operand or a clobber 9283 /// this is null, otherwise it is the incoming operand to the CallInst. 9284 /// This gets modified as the asm is processed. 9285 SDValue CallOperand; 9286 9287 /// AssignedRegs - If this is a register or register class operand, this 9288 /// contains the set of register corresponding to the operand. 9289 RegsForValue AssignedRegs; 9290 9291 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9292 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9293 } 9294 9295 /// Whether or not this operand accesses memory 9296 bool hasMemory(const TargetLowering &TLI) const { 9297 // Indirect operand accesses access memory. 9298 if (isIndirect) 9299 return true; 9300 9301 for (const auto &Code : Codes) 9302 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9303 return true; 9304 9305 return false; 9306 } 9307 }; 9308 9309 9310 } // end anonymous namespace 9311 9312 /// Make sure that the output operand \p OpInfo and its corresponding input 9313 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9314 /// out). 9315 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9316 SDISelAsmOperandInfo &MatchingOpInfo, 9317 SelectionDAG &DAG) { 9318 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9319 return; 9320 9321 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9322 const auto &TLI = DAG.getTargetLoweringInfo(); 9323 9324 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9325 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9326 OpInfo.ConstraintVT); 9327 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9328 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9329 MatchingOpInfo.ConstraintVT); 9330 if ((OpInfo.ConstraintVT.isInteger() != 9331 MatchingOpInfo.ConstraintVT.isInteger()) || 9332 (MatchRC.second != InputRC.second)) { 9333 // FIXME: error out in a more elegant fashion 9334 report_fatal_error("Unsupported asm: input constraint" 9335 " with a matching output constraint of" 9336 " incompatible type!"); 9337 } 9338 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9339 } 9340 9341 /// Get a direct memory input to behave well as an indirect operand. 9342 /// This may introduce stores, hence the need for a \p Chain. 9343 /// \return The (possibly updated) chain. 9344 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9345 SDISelAsmOperandInfo &OpInfo, 9346 SelectionDAG &DAG) { 9347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9348 9349 // If we don't have an indirect input, put it in the constpool if we can, 9350 // otherwise spill it to a stack slot. 9351 // TODO: This isn't quite right. We need to handle these according to 9352 // the addressing mode that the constraint wants. Also, this may take 9353 // an additional register for the computation and we don't want that 9354 // either. 9355 9356 // If the operand is a float, integer, or vector constant, spill to a 9357 // constant pool entry to get its address. 9358 const Value *OpVal = OpInfo.CallOperandVal; 9359 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9360 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9361 OpInfo.CallOperand = DAG.getConstantPool( 9362 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9363 return Chain; 9364 } 9365 9366 // Otherwise, create a stack slot and emit a store to it before the asm. 9367 Type *Ty = OpVal->getType(); 9368 auto &DL = DAG.getDataLayout(); 9369 uint64_t TySize = DL.getTypeAllocSize(Ty); 9370 MachineFunction &MF = DAG.getMachineFunction(); 9371 int SSFI = MF.getFrameInfo().CreateStackObject( 9372 TySize, DL.getPrefTypeAlign(Ty), false); 9373 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9374 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9375 MachinePointerInfo::getFixedStack(MF, SSFI), 9376 TLI.getMemValueType(DL, Ty)); 9377 OpInfo.CallOperand = StackSlot; 9378 9379 return Chain; 9380 } 9381 9382 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9383 /// specified operand. We prefer to assign virtual registers, to allow the 9384 /// register allocator to handle the assignment process. However, if the asm 9385 /// uses features that we can't model on machineinstrs, we have SDISel do the 9386 /// allocation. This produces generally horrible, but correct, code. 9387 /// 9388 /// OpInfo describes the operand 9389 /// RefOpInfo describes the matching operand if any, the operand otherwise 9390 static std::optional<unsigned> 9391 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9392 SDISelAsmOperandInfo &OpInfo, 9393 SDISelAsmOperandInfo &RefOpInfo) { 9394 LLVMContext &Context = *DAG.getContext(); 9395 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9396 9397 MachineFunction &MF = DAG.getMachineFunction(); 9398 SmallVector<unsigned, 4> Regs; 9399 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9400 9401 // No work to do for memory/address operands. 9402 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9403 OpInfo.ConstraintType == TargetLowering::C_Address) 9404 return std::nullopt; 9405 9406 // If this is a constraint for a single physreg, or a constraint for a 9407 // register class, find it. 9408 unsigned AssignedReg; 9409 const TargetRegisterClass *RC; 9410 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9411 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9412 // RC is unset only on failure. Return immediately. 9413 if (!RC) 9414 return std::nullopt; 9415 9416 // Get the actual register value type. This is important, because the user 9417 // may have asked for (e.g.) the AX register in i32 type. We need to 9418 // remember that AX is actually i16 to get the right extension. 9419 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9420 9421 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9422 // If this is an FP operand in an integer register (or visa versa), or more 9423 // generally if the operand value disagrees with the register class we plan 9424 // to stick it in, fix the operand type. 9425 // 9426 // If this is an input value, the bitcast to the new type is done now. 9427 // Bitcast for output value is done at the end of visitInlineAsm(). 9428 if ((OpInfo.Type == InlineAsm::isOutput || 9429 OpInfo.Type == InlineAsm::isInput) && 9430 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9431 // Try to convert to the first EVT that the reg class contains. If the 9432 // types are identical size, use a bitcast to convert (e.g. two differing 9433 // vector types). Note: output bitcast is done at the end of 9434 // visitInlineAsm(). 9435 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9436 // Exclude indirect inputs while they are unsupported because the code 9437 // to perform the load is missing and thus OpInfo.CallOperand still 9438 // refers to the input address rather than the pointed-to value. 9439 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9440 OpInfo.CallOperand = 9441 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9442 OpInfo.ConstraintVT = RegVT; 9443 // If the operand is an FP value and we want it in integer registers, 9444 // use the corresponding integer type. This turns an f64 value into 9445 // i64, which can be passed with two i32 values on a 32-bit machine. 9446 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9447 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9448 if (OpInfo.Type == InlineAsm::isInput) 9449 OpInfo.CallOperand = 9450 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9451 OpInfo.ConstraintVT = VT; 9452 } 9453 } 9454 } 9455 9456 // No need to allocate a matching input constraint since the constraint it's 9457 // matching to has already been allocated. 9458 if (OpInfo.isMatchingInputConstraint()) 9459 return std::nullopt; 9460 9461 EVT ValueVT = OpInfo.ConstraintVT; 9462 if (OpInfo.ConstraintVT == MVT::Other) 9463 ValueVT = RegVT; 9464 9465 // Initialize NumRegs. 9466 unsigned NumRegs = 1; 9467 if (OpInfo.ConstraintVT != MVT::Other) 9468 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9469 9470 // If this is a constraint for a specific physical register, like {r17}, 9471 // assign it now. 9472 9473 // If this associated to a specific register, initialize iterator to correct 9474 // place. If virtual, make sure we have enough registers 9475 9476 // Initialize iterator if necessary 9477 TargetRegisterClass::iterator I = RC->begin(); 9478 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9479 9480 // Do not check for single registers. 9481 if (AssignedReg) { 9482 I = std::find(I, RC->end(), AssignedReg); 9483 if (I == RC->end()) { 9484 // RC does not contain the selected register, which indicates a 9485 // mismatch between the register and the required type/bitwidth. 9486 return {AssignedReg}; 9487 } 9488 } 9489 9490 for (; NumRegs; --NumRegs, ++I) { 9491 assert(I != RC->end() && "Ran out of registers to allocate!"); 9492 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9493 Regs.push_back(R); 9494 } 9495 9496 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9497 return std::nullopt; 9498 } 9499 9500 static unsigned 9501 findMatchingInlineAsmOperand(unsigned OperandNo, 9502 const std::vector<SDValue> &AsmNodeOperands) { 9503 // Scan until we find the definition we already emitted of this operand. 9504 unsigned CurOp = InlineAsm::Op_FirstOperand; 9505 for (; OperandNo; --OperandNo) { 9506 // Advance to the next operand. 9507 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9508 const InlineAsm::Flag F(OpFlag); 9509 assert( 9510 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9511 "Skipped past definitions?"); 9512 CurOp += F.getNumOperandRegisters() + 1; 9513 } 9514 return CurOp; 9515 } 9516 9517 namespace { 9518 9519 class ExtraFlags { 9520 unsigned Flags = 0; 9521 9522 public: 9523 explicit ExtraFlags(const CallBase &Call) { 9524 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9525 if (IA->hasSideEffects()) 9526 Flags |= InlineAsm::Extra_HasSideEffects; 9527 if (IA->isAlignStack()) 9528 Flags |= InlineAsm::Extra_IsAlignStack; 9529 if (Call.isConvergent()) 9530 Flags |= InlineAsm::Extra_IsConvergent; 9531 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9532 } 9533 9534 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9535 // Ideally, we would only check against memory constraints. However, the 9536 // meaning of an Other constraint can be target-specific and we can't easily 9537 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9538 // for Other constraints as well. 9539 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9540 OpInfo.ConstraintType == TargetLowering::C_Other) { 9541 if (OpInfo.Type == InlineAsm::isInput) 9542 Flags |= InlineAsm::Extra_MayLoad; 9543 else if (OpInfo.Type == InlineAsm::isOutput) 9544 Flags |= InlineAsm::Extra_MayStore; 9545 else if (OpInfo.Type == InlineAsm::isClobber) 9546 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9547 } 9548 } 9549 9550 unsigned get() const { return Flags; } 9551 }; 9552 9553 } // end anonymous namespace 9554 9555 static bool isFunction(SDValue Op) { 9556 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9557 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9558 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9559 9560 // In normal "call dllimport func" instruction (non-inlineasm) it force 9561 // indirect access by specifing call opcode. And usually specially print 9562 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9563 // not do in this way now. (In fact, this is similar with "Data Access" 9564 // action). So here we ignore dllimport function. 9565 if (Fn && !Fn->hasDLLImportStorageClass()) 9566 return true; 9567 } 9568 } 9569 return false; 9570 } 9571 9572 /// visitInlineAsm - Handle a call to an InlineAsm object. 9573 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9574 const BasicBlock *EHPadBB) { 9575 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9576 9577 /// ConstraintOperands - Information about all of the constraints. 9578 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9579 9580 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9581 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9582 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9583 9584 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9585 // AsmDialect, MayLoad, MayStore). 9586 bool HasSideEffect = IA->hasSideEffects(); 9587 ExtraFlags ExtraInfo(Call); 9588 9589 for (auto &T : TargetConstraints) { 9590 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9591 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9592 9593 if (OpInfo.CallOperandVal) 9594 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9595 9596 if (!HasSideEffect) 9597 HasSideEffect = OpInfo.hasMemory(TLI); 9598 9599 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9600 // FIXME: Could we compute this on OpInfo rather than T? 9601 9602 // Compute the constraint code and ConstraintType to use. 9603 TLI.ComputeConstraintToUse(T, SDValue()); 9604 9605 if (T.ConstraintType == TargetLowering::C_Immediate && 9606 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9607 // We've delayed emitting a diagnostic like the "n" constraint because 9608 // inlining could cause an integer showing up. 9609 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9610 "' expects an integer constant " 9611 "expression"); 9612 9613 ExtraInfo.update(T); 9614 } 9615 9616 // We won't need to flush pending loads if this asm doesn't touch 9617 // memory and is nonvolatile. 9618 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9619 9620 bool EmitEHLabels = isa<InvokeInst>(Call); 9621 if (EmitEHLabels) { 9622 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9623 } 9624 bool IsCallBr = isa<CallBrInst>(Call); 9625 9626 if (IsCallBr || EmitEHLabels) { 9627 // If this is a callbr or invoke we need to flush pending exports since 9628 // inlineasm_br and invoke are terminators. 9629 // We need to do this before nodes are glued to the inlineasm_br node. 9630 Chain = getControlRoot(); 9631 } 9632 9633 MCSymbol *BeginLabel = nullptr; 9634 if (EmitEHLabels) { 9635 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9636 } 9637 9638 int OpNo = -1; 9639 SmallVector<StringRef> AsmStrs; 9640 IA->collectAsmStrs(AsmStrs); 9641 9642 // Second pass over the constraints: compute which constraint option to use. 9643 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9644 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9645 OpNo++; 9646 9647 // If this is an output operand with a matching input operand, look up the 9648 // matching input. If their types mismatch, e.g. one is an integer, the 9649 // other is floating point, or their sizes are different, flag it as an 9650 // error. 9651 if (OpInfo.hasMatchingInput()) { 9652 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9653 patchMatchingInput(OpInfo, Input, DAG); 9654 } 9655 9656 // Compute the constraint code and ConstraintType to use. 9657 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9658 9659 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9660 OpInfo.Type == InlineAsm::isClobber) || 9661 OpInfo.ConstraintType == TargetLowering::C_Address) 9662 continue; 9663 9664 // In Linux PIC model, there are 4 cases about value/label addressing: 9665 // 9666 // 1: Function call or Label jmp inside the module. 9667 // 2: Data access (such as global variable, static variable) inside module. 9668 // 3: Function call or Label jmp outside the module. 9669 // 4: Data access (such as global variable) outside the module. 9670 // 9671 // Due to current llvm inline asm architecture designed to not "recognize" 9672 // the asm code, there are quite troubles for us to treat mem addressing 9673 // differently for same value/adress used in different instuctions. 9674 // For example, in pic model, call a func may in plt way or direclty 9675 // pc-related, but lea/mov a function adress may use got. 9676 // 9677 // Here we try to "recognize" function call for the case 1 and case 3 in 9678 // inline asm. And try to adjust the constraint for them. 9679 // 9680 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9681 // label, so here we don't handle jmp function label now, but we need to 9682 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9683 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9684 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9685 TM.getCodeModel() != CodeModel::Large) { 9686 OpInfo.isIndirect = false; 9687 OpInfo.ConstraintType = TargetLowering::C_Address; 9688 } 9689 9690 // If this is a memory input, and if the operand is not indirect, do what we 9691 // need to provide an address for the memory input. 9692 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9693 !OpInfo.isIndirect) { 9694 assert((OpInfo.isMultipleAlternative || 9695 (OpInfo.Type == InlineAsm::isInput)) && 9696 "Can only indirectify direct input operands!"); 9697 9698 // Memory operands really want the address of the value. 9699 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9700 9701 // There is no longer a Value* corresponding to this operand. 9702 OpInfo.CallOperandVal = nullptr; 9703 9704 // It is now an indirect operand. 9705 OpInfo.isIndirect = true; 9706 } 9707 9708 } 9709 9710 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9711 std::vector<SDValue> AsmNodeOperands; 9712 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9713 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9714 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9715 9716 // If we have a !srcloc metadata node associated with it, we want to attach 9717 // this to the ultimately generated inline asm machineinstr. To do this, we 9718 // pass in the third operand as this (potentially null) inline asm MDNode. 9719 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9720 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9721 9722 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9723 // bits as operand 3. 9724 AsmNodeOperands.push_back(DAG.getTargetConstant( 9725 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9726 9727 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9728 // this, assign virtual and physical registers for inputs and otput. 9729 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9730 // Assign Registers. 9731 SDISelAsmOperandInfo &RefOpInfo = 9732 OpInfo.isMatchingInputConstraint() 9733 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9734 : OpInfo; 9735 const auto RegError = 9736 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9737 if (RegError) { 9738 const MachineFunction &MF = DAG.getMachineFunction(); 9739 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9740 const char *RegName = TRI.getName(*RegError); 9741 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9742 "' allocated for constraint '" + 9743 Twine(OpInfo.ConstraintCode) + 9744 "' does not match required type"); 9745 return; 9746 } 9747 9748 auto DetectWriteToReservedRegister = [&]() { 9749 const MachineFunction &MF = DAG.getMachineFunction(); 9750 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9751 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9752 if (Register::isPhysicalRegister(Reg) && 9753 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9754 const char *RegName = TRI.getName(Reg); 9755 emitInlineAsmError(Call, "write to reserved register '" + 9756 Twine(RegName) + "'"); 9757 return true; 9758 } 9759 } 9760 return false; 9761 }; 9762 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9763 (OpInfo.Type == InlineAsm::isInput && 9764 !OpInfo.isMatchingInputConstraint())) && 9765 "Only address as input operand is allowed."); 9766 9767 switch (OpInfo.Type) { 9768 case InlineAsm::isOutput: 9769 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9770 const InlineAsm::ConstraintCode ConstraintID = 9771 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9772 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9773 "Failed to convert memory constraint code to constraint id."); 9774 9775 // Add information to the INLINEASM node to know about this output. 9776 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9777 OpFlags.setMemConstraint(ConstraintID); 9778 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9779 MVT::i32)); 9780 AsmNodeOperands.push_back(OpInfo.CallOperand); 9781 } else { 9782 // Otherwise, this outputs to a register (directly for C_Register / 9783 // C_RegisterClass, and a target-defined fashion for 9784 // C_Immediate/C_Other). Find a register that we can use. 9785 if (OpInfo.AssignedRegs.Regs.empty()) { 9786 emitInlineAsmError( 9787 Call, "couldn't allocate output register for constraint '" + 9788 Twine(OpInfo.ConstraintCode) + "'"); 9789 return; 9790 } 9791 9792 if (DetectWriteToReservedRegister()) 9793 return; 9794 9795 // Add information to the INLINEASM node to know that this register is 9796 // set. 9797 OpInfo.AssignedRegs.AddInlineAsmOperands( 9798 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9799 : InlineAsm::Kind::RegDef, 9800 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9801 } 9802 break; 9803 9804 case InlineAsm::isInput: 9805 case InlineAsm::isLabel: { 9806 SDValue InOperandVal = OpInfo.CallOperand; 9807 9808 if (OpInfo.isMatchingInputConstraint()) { 9809 // If this is required to match an output register we have already set, 9810 // just use its register. 9811 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9812 AsmNodeOperands); 9813 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9814 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9815 if (OpInfo.isIndirect) { 9816 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9817 emitInlineAsmError(Call, "inline asm not supported yet: " 9818 "don't know how to handle tied " 9819 "indirect register inputs"); 9820 return; 9821 } 9822 9823 SmallVector<unsigned, 4> Regs; 9824 MachineFunction &MF = DAG.getMachineFunction(); 9825 MachineRegisterInfo &MRI = MF.getRegInfo(); 9826 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9827 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9828 Register TiedReg = R->getReg(); 9829 MVT RegVT = R->getSimpleValueType(0); 9830 const TargetRegisterClass *RC = 9831 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9832 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9833 : TRI.getMinimalPhysRegClass(TiedReg); 9834 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9835 Regs.push_back(MRI.createVirtualRegister(RC)); 9836 9837 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9838 9839 SDLoc dl = getCurSDLoc(); 9840 // Use the produced MatchedRegs object to 9841 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9842 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9843 OpInfo.getMatchedOperand(), dl, DAG, 9844 AsmNodeOperands); 9845 break; 9846 } 9847 9848 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9849 assert(Flag.getNumOperandRegisters() == 1 && 9850 "Unexpected number of operands"); 9851 // Add information to the INLINEASM node to know about this input. 9852 // See InlineAsm.h isUseOperandTiedToDef. 9853 Flag.clearMemConstraint(); 9854 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9855 AsmNodeOperands.push_back(DAG.getTargetConstant( 9856 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9857 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9858 break; 9859 } 9860 9861 // Treat indirect 'X' constraint as memory. 9862 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9863 OpInfo.isIndirect) 9864 OpInfo.ConstraintType = TargetLowering::C_Memory; 9865 9866 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9867 OpInfo.ConstraintType == TargetLowering::C_Other) { 9868 std::vector<SDValue> Ops; 9869 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9870 Ops, DAG); 9871 if (Ops.empty()) { 9872 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9873 if (isa<ConstantSDNode>(InOperandVal)) { 9874 emitInlineAsmError(Call, "value out of range for constraint '" + 9875 Twine(OpInfo.ConstraintCode) + "'"); 9876 return; 9877 } 9878 9879 emitInlineAsmError(Call, 9880 "invalid operand for inline asm constraint '" + 9881 Twine(OpInfo.ConstraintCode) + "'"); 9882 return; 9883 } 9884 9885 // Add information to the INLINEASM node to know about this input. 9886 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9887 AsmNodeOperands.push_back(DAG.getTargetConstant( 9888 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9889 llvm::append_range(AsmNodeOperands, Ops); 9890 break; 9891 } 9892 9893 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9894 assert((OpInfo.isIndirect || 9895 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9896 "Operand must be indirect to be a mem!"); 9897 assert(InOperandVal.getValueType() == 9898 TLI.getPointerTy(DAG.getDataLayout()) && 9899 "Memory operands expect pointer values"); 9900 9901 const InlineAsm::ConstraintCode ConstraintID = 9902 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9903 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9904 "Failed to convert memory constraint code to constraint id."); 9905 9906 // Add information to the INLINEASM node to know about this input. 9907 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9908 ResOpType.setMemConstraint(ConstraintID); 9909 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9910 getCurSDLoc(), 9911 MVT::i32)); 9912 AsmNodeOperands.push_back(InOperandVal); 9913 break; 9914 } 9915 9916 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9917 const InlineAsm::ConstraintCode ConstraintID = 9918 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9919 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9920 "Failed to convert memory constraint code to constraint id."); 9921 9922 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9923 9924 SDValue AsmOp = InOperandVal; 9925 if (isFunction(InOperandVal)) { 9926 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9927 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9928 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9929 InOperandVal.getValueType(), 9930 GA->getOffset()); 9931 } 9932 9933 // Add information to the INLINEASM node to know about this input. 9934 ResOpType.setMemConstraint(ConstraintID); 9935 9936 AsmNodeOperands.push_back( 9937 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9938 9939 AsmNodeOperands.push_back(AsmOp); 9940 break; 9941 } 9942 9943 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9944 OpInfo.ConstraintType == TargetLowering::C_Register) && 9945 "Unknown constraint type!"); 9946 9947 // TODO: Support this. 9948 if (OpInfo.isIndirect) { 9949 emitInlineAsmError( 9950 Call, "Don't know how to handle indirect register inputs yet " 9951 "for constraint '" + 9952 Twine(OpInfo.ConstraintCode) + "'"); 9953 return; 9954 } 9955 9956 // Copy the input into the appropriate registers. 9957 if (OpInfo.AssignedRegs.Regs.empty()) { 9958 emitInlineAsmError(Call, 9959 "couldn't allocate input reg for constraint '" + 9960 Twine(OpInfo.ConstraintCode) + "'"); 9961 return; 9962 } 9963 9964 if (DetectWriteToReservedRegister()) 9965 return; 9966 9967 SDLoc dl = getCurSDLoc(); 9968 9969 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9970 &Call); 9971 9972 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9973 0, dl, DAG, AsmNodeOperands); 9974 break; 9975 } 9976 case InlineAsm::isClobber: 9977 // Add the clobbered value to the operand list, so that the register 9978 // allocator is aware that the physreg got clobbered. 9979 if (!OpInfo.AssignedRegs.Regs.empty()) 9980 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9981 false, 0, getCurSDLoc(), DAG, 9982 AsmNodeOperands); 9983 break; 9984 } 9985 } 9986 9987 // Finish up input operands. Set the input chain and add the flag last. 9988 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9989 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9990 9991 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9992 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9993 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9994 Glue = Chain.getValue(1); 9995 9996 // Do additional work to generate outputs. 9997 9998 SmallVector<EVT, 1> ResultVTs; 9999 SmallVector<SDValue, 1> ResultValues; 10000 SmallVector<SDValue, 8> OutChains; 10001 10002 llvm::Type *CallResultType = Call.getType(); 10003 ArrayRef<Type *> ResultTypes; 10004 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 10005 ResultTypes = StructResult->elements(); 10006 else if (!CallResultType->isVoidTy()) 10007 ResultTypes = ArrayRef(CallResultType); 10008 10009 auto CurResultType = ResultTypes.begin(); 10010 auto handleRegAssign = [&](SDValue V) { 10011 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 10012 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 10013 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 10014 ++CurResultType; 10015 // If the type of the inline asm call site return value is different but has 10016 // same size as the type of the asm output bitcast it. One example of this 10017 // is for vectors with different width / number of elements. This can 10018 // happen for register classes that can contain multiple different value 10019 // types. The preg or vreg allocated may not have the same VT as was 10020 // expected. 10021 // 10022 // This can also happen for a return value that disagrees with the register 10023 // class it is put in, eg. a double in a general-purpose register on a 10024 // 32-bit machine. 10025 if (ResultVT != V.getValueType() && 10026 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 10027 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 10028 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 10029 V.getValueType().isInteger()) { 10030 // If a result value was tied to an input value, the computed result 10031 // may have a wider width than the expected result. Extract the 10032 // relevant portion. 10033 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 10034 } 10035 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 10036 ResultVTs.push_back(ResultVT); 10037 ResultValues.push_back(V); 10038 }; 10039 10040 // Deal with output operands. 10041 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 10042 if (OpInfo.Type == InlineAsm::isOutput) { 10043 SDValue Val; 10044 // Skip trivial output operands. 10045 if (OpInfo.AssignedRegs.Regs.empty()) 10046 continue; 10047 10048 switch (OpInfo.ConstraintType) { 10049 case TargetLowering::C_Register: 10050 case TargetLowering::C_RegisterClass: 10051 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 10052 Chain, &Glue, &Call); 10053 break; 10054 case TargetLowering::C_Immediate: 10055 case TargetLowering::C_Other: 10056 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 10057 OpInfo, DAG); 10058 break; 10059 case TargetLowering::C_Memory: 10060 break; // Already handled. 10061 case TargetLowering::C_Address: 10062 break; // Silence warning. 10063 case TargetLowering::C_Unknown: 10064 assert(false && "Unexpected unknown constraint"); 10065 } 10066 10067 // Indirect output manifest as stores. Record output chains. 10068 if (OpInfo.isIndirect) { 10069 const Value *Ptr = OpInfo.CallOperandVal; 10070 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 10071 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 10072 MachinePointerInfo(Ptr)); 10073 OutChains.push_back(Store); 10074 } else { 10075 // generate CopyFromRegs to associated registers. 10076 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 10077 if (Val.getOpcode() == ISD::MERGE_VALUES) { 10078 for (const SDValue &V : Val->op_values()) 10079 handleRegAssign(V); 10080 } else 10081 handleRegAssign(Val); 10082 } 10083 } 10084 } 10085 10086 // Set results. 10087 if (!ResultValues.empty()) { 10088 assert(CurResultType == ResultTypes.end() && 10089 "Mismatch in number of ResultTypes"); 10090 assert(ResultValues.size() == ResultTypes.size() && 10091 "Mismatch in number of output operands in asm result"); 10092 10093 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10094 DAG.getVTList(ResultVTs), ResultValues); 10095 setValue(&Call, V); 10096 } 10097 10098 // Collect store chains. 10099 if (!OutChains.empty()) 10100 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 10101 10102 if (EmitEHLabels) { 10103 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 10104 } 10105 10106 // Only Update Root if inline assembly has a memory effect. 10107 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 10108 EmitEHLabels) 10109 DAG.setRoot(Chain); 10110 } 10111 10112 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 10113 const Twine &Message) { 10114 LLVMContext &Ctx = *DAG.getContext(); 10115 Ctx.emitError(&Call, Message); 10116 10117 // Make sure we leave the DAG in a valid state 10118 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10119 SmallVector<EVT, 1> ValueVTs; 10120 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 10121 10122 if (ValueVTs.empty()) 10123 return; 10124 10125 SmallVector<SDValue, 1> Ops; 10126 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 10127 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 10128 10129 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 10130 } 10131 10132 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 10133 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 10134 MVT::Other, getRoot(), 10135 getValue(I.getArgOperand(0)), 10136 DAG.getSrcValue(I.getArgOperand(0)))); 10137 } 10138 10139 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 10140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10141 const DataLayout &DL = DAG.getDataLayout(); 10142 SDValue V = DAG.getVAArg( 10143 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 10144 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 10145 DL.getABITypeAlign(I.getType()).value()); 10146 DAG.setRoot(V.getValue(1)); 10147 10148 if (I.getType()->isPointerTy()) 10149 V = DAG.getPtrExtOrTrunc( 10150 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 10151 setValue(&I, V); 10152 } 10153 10154 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 10155 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 10156 MVT::Other, getRoot(), 10157 getValue(I.getArgOperand(0)), 10158 DAG.getSrcValue(I.getArgOperand(0)))); 10159 } 10160 10161 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 10162 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 10163 MVT::Other, getRoot(), 10164 getValue(I.getArgOperand(0)), 10165 getValue(I.getArgOperand(1)), 10166 DAG.getSrcValue(I.getArgOperand(0)), 10167 DAG.getSrcValue(I.getArgOperand(1)))); 10168 } 10169 10170 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 10171 const Instruction &I, 10172 SDValue Op) { 10173 const MDNode *Range = getRangeMetadata(I); 10174 if (!Range) 10175 return Op; 10176 10177 ConstantRange CR = getConstantRangeFromMetadata(*Range); 10178 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 10179 return Op; 10180 10181 APInt Lo = CR.getUnsignedMin(); 10182 if (!Lo.isMinValue()) 10183 return Op; 10184 10185 APInt Hi = CR.getUnsignedMax(); 10186 unsigned Bits = std::max(Hi.getActiveBits(), 10187 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 10188 10189 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 10190 10191 SDLoc SL = getCurSDLoc(); 10192 10193 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 10194 DAG.getValueType(SmallVT)); 10195 unsigned NumVals = Op.getNode()->getNumValues(); 10196 if (NumVals == 1) 10197 return ZExt; 10198 10199 SmallVector<SDValue, 4> Ops; 10200 10201 Ops.push_back(ZExt); 10202 for (unsigned I = 1; I != NumVals; ++I) 10203 Ops.push_back(Op.getValue(I)); 10204 10205 return DAG.getMergeValues(Ops, SL); 10206 } 10207 10208 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 10209 /// the call being lowered. 10210 /// 10211 /// This is a helper for lowering intrinsics that follow a target calling 10212 /// convention or require stack pointer adjustment. Only a subset of the 10213 /// intrinsic's operands need to participate in the calling convention. 10214 void SelectionDAGBuilder::populateCallLoweringInfo( 10215 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 10216 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 10217 AttributeSet RetAttrs, bool IsPatchPoint) { 10218 TargetLowering::ArgListTy Args; 10219 Args.reserve(NumArgs); 10220 10221 // Populate the argument list. 10222 // Attributes for args start at offset 1, after the return attribute. 10223 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 10224 ArgI != ArgE; ++ArgI) { 10225 const Value *V = Call->getOperand(ArgI); 10226 10227 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 10228 10229 TargetLowering::ArgListEntry Entry; 10230 Entry.Node = getValue(V); 10231 Entry.Ty = V->getType(); 10232 Entry.setAttributes(Call, ArgI); 10233 Args.push_back(Entry); 10234 } 10235 10236 CLI.setDebugLoc(getCurSDLoc()) 10237 .setChain(getRoot()) 10238 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 10239 RetAttrs) 10240 .setDiscardResult(Call->use_empty()) 10241 .setIsPatchPoint(IsPatchPoint) 10242 .setIsPreallocated( 10243 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 10244 } 10245 10246 /// Add a stack map intrinsic call's live variable operands to a stackmap 10247 /// or patchpoint target node's operand list. 10248 /// 10249 /// Constants are converted to TargetConstants purely as an optimization to 10250 /// avoid constant materialization and register allocation. 10251 /// 10252 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 10253 /// generate addess computation nodes, and so FinalizeISel can convert the 10254 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10255 /// address materialization and register allocation, but may also be required 10256 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10257 /// alloca in the entry block, then the runtime may assume that the alloca's 10258 /// StackMap location can be read immediately after compilation and that the 10259 /// location is valid at any point during execution (this is similar to the 10260 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10261 /// only available in a register, then the runtime would need to trap when 10262 /// execution reaches the StackMap in order to read the alloca's location. 10263 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10264 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10265 SelectionDAGBuilder &Builder) { 10266 SelectionDAG &DAG = Builder.DAG; 10267 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10268 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10269 10270 // Things on the stack are pointer-typed, meaning that they are already 10271 // legal and can be emitted directly to target nodes. 10272 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10273 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10274 } else { 10275 // Otherwise emit a target independent node to be legalised. 10276 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10277 } 10278 } 10279 } 10280 10281 /// Lower llvm.experimental.stackmap. 10282 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10283 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10284 // [live variables...]) 10285 10286 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10287 10288 SDValue Chain, InGlue, Callee; 10289 SmallVector<SDValue, 32> Ops; 10290 10291 SDLoc DL = getCurSDLoc(); 10292 Callee = getValue(CI.getCalledOperand()); 10293 10294 // The stackmap intrinsic only records the live variables (the arguments 10295 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10296 // intrinsic, this won't be lowered to a function call. This means we don't 10297 // have to worry about calling conventions and target specific lowering code. 10298 // Instead we perform the call lowering right here. 10299 // 10300 // chain, flag = CALLSEQ_START(chain, 0, 0) 10301 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10302 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10303 // 10304 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10305 InGlue = Chain.getValue(1); 10306 10307 // Add the STACKMAP operands, starting with DAG house-keeping. 10308 Ops.push_back(Chain); 10309 Ops.push_back(InGlue); 10310 10311 // Add the <id>, <numShadowBytes> operands. 10312 // 10313 // These do not require legalisation, and can be emitted directly to target 10314 // constant nodes. 10315 SDValue ID = getValue(CI.getArgOperand(0)); 10316 assert(ID.getValueType() == MVT::i64); 10317 SDValue IDConst = 10318 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10319 Ops.push_back(IDConst); 10320 10321 SDValue Shad = getValue(CI.getArgOperand(1)); 10322 assert(Shad.getValueType() == MVT::i32); 10323 SDValue ShadConst = 10324 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10325 Ops.push_back(ShadConst); 10326 10327 // Add the live variables. 10328 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10329 10330 // Create the STACKMAP node. 10331 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10332 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10333 InGlue = Chain.getValue(1); 10334 10335 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10336 10337 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10338 10339 // Set the root to the target-lowered call chain. 10340 DAG.setRoot(Chain); 10341 10342 // Inform the Frame Information that we have a stackmap in this function. 10343 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10344 } 10345 10346 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10347 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10348 const BasicBlock *EHPadBB) { 10349 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>, 10350 // i32 <numBytes>, 10351 // i8* <target>, 10352 // i32 <numArgs>, 10353 // [Args...], 10354 // [live variables...]) 10355 10356 CallingConv::ID CC = CB.getCallingConv(); 10357 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10358 bool HasDef = !CB.getType()->isVoidTy(); 10359 SDLoc dl = getCurSDLoc(); 10360 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10361 10362 // Handle immediate and symbolic callees. 10363 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10364 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10365 /*isTarget=*/true); 10366 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10367 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10368 SDLoc(SymbolicCallee), 10369 SymbolicCallee->getValueType(0)); 10370 10371 // Get the real number of arguments participating in the call <numArgs> 10372 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10373 unsigned NumArgs = NArgVal->getAsZExtVal(); 10374 10375 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10376 // Intrinsics include all meta-operands up to but not including CC. 10377 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10378 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10379 "Not enough arguments provided to the patchpoint intrinsic"); 10380 10381 // For AnyRegCC the arguments are lowered later on manually. 10382 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10383 Type *ReturnTy = 10384 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10385 10386 TargetLowering::CallLoweringInfo CLI(DAG); 10387 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10388 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10389 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10390 10391 SDNode *CallEnd = Result.second.getNode(); 10392 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10393 CallEnd = CallEnd->getOperand(0).getNode(); 10394 10395 /// Get a call instruction from the call sequence chain. 10396 /// Tail calls are not allowed. 10397 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10398 "Expected a callseq node."); 10399 SDNode *Call = CallEnd->getOperand(0).getNode(); 10400 bool HasGlue = Call->getGluedNode(); 10401 10402 // Replace the target specific call node with the patchable intrinsic. 10403 SmallVector<SDValue, 8> Ops; 10404 10405 // Push the chain. 10406 Ops.push_back(*(Call->op_begin())); 10407 10408 // Optionally, push the glue (if any). 10409 if (HasGlue) 10410 Ops.push_back(*(Call->op_end() - 1)); 10411 10412 // Push the register mask info. 10413 if (HasGlue) 10414 Ops.push_back(*(Call->op_end() - 2)); 10415 else 10416 Ops.push_back(*(Call->op_end() - 1)); 10417 10418 // Add the <id> and <numBytes> constants. 10419 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10420 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10421 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10422 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10423 10424 // Add the callee. 10425 Ops.push_back(Callee); 10426 10427 // Adjust <numArgs> to account for any arguments that have been passed on the 10428 // stack instead. 10429 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10430 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10431 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10432 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10433 10434 // Add the calling convention 10435 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10436 10437 // Add the arguments we omitted previously. The register allocator should 10438 // place these in any free register. 10439 if (IsAnyRegCC) 10440 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10441 Ops.push_back(getValue(CB.getArgOperand(i))); 10442 10443 // Push the arguments from the call instruction. 10444 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10445 Ops.append(Call->op_begin() + 2, e); 10446 10447 // Push live variables for the stack map. 10448 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10449 10450 SDVTList NodeTys; 10451 if (IsAnyRegCC && HasDef) { 10452 // Create the return types based on the intrinsic definition 10453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10454 SmallVector<EVT, 3> ValueVTs; 10455 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10456 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10457 10458 // There is always a chain and a glue type at the end 10459 ValueVTs.push_back(MVT::Other); 10460 ValueVTs.push_back(MVT::Glue); 10461 NodeTys = DAG.getVTList(ValueVTs); 10462 } else 10463 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10464 10465 // Replace the target specific call node with a PATCHPOINT node. 10466 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10467 10468 // Update the NodeMap. 10469 if (HasDef) { 10470 if (IsAnyRegCC) 10471 setValue(&CB, SDValue(PPV.getNode(), 0)); 10472 else 10473 setValue(&CB, Result.first); 10474 } 10475 10476 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10477 // call sequence. Furthermore the location of the chain and glue can change 10478 // when the AnyReg calling convention is used and the intrinsic returns a 10479 // value. 10480 if (IsAnyRegCC && HasDef) { 10481 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10482 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10483 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10484 } else 10485 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10486 DAG.DeleteNode(Call); 10487 10488 // Inform the Frame Information that we have a patchpoint in this function. 10489 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10490 } 10491 10492 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10493 unsigned Intrinsic) { 10494 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10495 SDValue Op1 = getValue(I.getArgOperand(0)); 10496 SDValue Op2; 10497 if (I.arg_size() > 1) 10498 Op2 = getValue(I.getArgOperand(1)); 10499 SDLoc dl = getCurSDLoc(); 10500 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10501 SDValue Res; 10502 SDNodeFlags SDFlags; 10503 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10504 SDFlags.copyFMF(*FPMO); 10505 10506 switch (Intrinsic) { 10507 case Intrinsic::vector_reduce_fadd: 10508 if (SDFlags.hasAllowReassociation()) 10509 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10510 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10511 SDFlags); 10512 else 10513 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10514 break; 10515 case Intrinsic::vector_reduce_fmul: 10516 if (SDFlags.hasAllowReassociation()) 10517 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10518 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10519 SDFlags); 10520 else 10521 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10522 break; 10523 case Intrinsic::vector_reduce_add: 10524 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10525 break; 10526 case Intrinsic::vector_reduce_mul: 10527 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10528 break; 10529 case Intrinsic::vector_reduce_and: 10530 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10531 break; 10532 case Intrinsic::vector_reduce_or: 10533 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10534 break; 10535 case Intrinsic::vector_reduce_xor: 10536 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10537 break; 10538 case Intrinsic::vector_reduce_smax: 10539 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10540 break; 10541 case Intrinsic::vector_reduce_smin: 10542 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10543 break; 10544 case Intrinsic::vector_reduce_umax: 10545 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10546 break; 10547 case Intrinsic::vector_reduce_umin: 10548 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10549 break; 10550 case Intrinsic::vector_reduce_fmax: 10551 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10552 break; 10553 case Intrinsic::vector_reduce_fmin: 10554 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10555 break; 10556 case Intrinsic::vector_reduce_fmaximum: 10557 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10558 break; 10559 case Intrinsic::vector_reduce_fminimum: 10560 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10561 break; 10562 default: 10563 llvm_unreachable("Unhandled vector reduce intrinsic"); 10564 } 10565 setValue(&I, Res); 10566 } 10567 10568 /// Returns an AttributeList representing the attributes applied to the return 10569 /// value of the given call. 10570 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10571 SmallVector<Attribute::AttrKind, 2> Attrs; 10572 if (CLI.RetSExt) 10573 Attrs.push_back(Attribute::SExt); 10574 if (CLI.RetZExt) 10575 Attrs.push_back(Attribute::ZExt); 10576 if (CLI.IsInReg) 10577 Attrs.push_back(Attribute::InReg); 10578 10579 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10580 Attrs); 10581 } 10582 10583 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10584 /// implementation, which just calls LowerCall. 10585 /// FIXME: When all targets are 10586 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10587 std::pair<SDValue, SDValue> 10588 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10589 // Handle the incoming return values from the call. 10590 CLI.Ins.clear(); 10591 Type *OrigRetTy = CLI.RetTy; 10592 SmallVector<EVT, 4> RetTys; 10593 SmallVector<TypeSize, 4> Offsets; 10594 auto &DL = CLI.DAG.getDataLayout(); 10595 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 10596 10597 if (CLI.IsPostTypeLegalization) { 10598 // If we are lowering a libcall after legalization, split the return type. 10599 SmallVector<EVT, 4> OldRetTys; 10600 SmallVector<TypeSize, 4> OldOffsets; 10601 RetTys.swap(OldRetTys); 10602 Offsets.swap(OldOffsets); 10603 10604 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10605 EVT RetVT = OldRetTys[i]; 10606 uint64_t Offset = OldOffsets[i]; 10607 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10608 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10609 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10610 RetTys.append(NumRegs, RegisterVT); 10611 for (unsigned j = 0; j != NumRegs; ++j) 10612 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ)); 10613 } 10614 } 10615 10616 SmallVector<ISD::OutputArg, 4> Outs; 10617 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10618 10619 bool CanLowerReturn = 10620 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10621 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10622 10623 SDValue DemoteStackSlot; 10624 int DemoteStackIdx = -100; 10625 if (!CanLowerReturn) { 10626 // FIXME: equivalent assert? 10627 // assert(!CS.hasInAllocaArgument() && 10628 // "sret demotion is incompatible with inalloca"); 10629 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10630 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10631 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10632 DemoteStackIdx = 10633 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10634 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10635 DL.getAllocaAddrSpace()); 10636 10637 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10638 ArgListEntry Entry; 10639 Entry.Node = DemoteStackSlot; 10640 Entry.Ty = StackSlotPtrType; 10641 Entry.IsSExt = false; 10642 Entry.IsZExt = false; 10643 Entry.IsInReg = false; 10644 Entry.IsSRet = true; 10645 Entry.IsNest = false; 10646 Entry.IsByVal = false; 10647 Entry.IsByRef = false; 10648 Entry.IsReturned = false; 10649 Entry.IsSwiftSelf = false; 10650 Entry.IsSwiftAsync = false; 10651 Entry.IsSwiftError = false; 10652 Entry.IsCFGuardTarget = false; 10653 Entry.Alignment = Alignment; 10654 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10655 CLI.NumFixedArgs += 1; 10656 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10657 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10658 10659 // sret demotion isn't compatible with tail-calls, since the sret argument 10660 // points into the callers stack frame. 10661 CLI.IsTailCall = false; 10662 } else { 10663 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10664 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10665 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10666 ISD::ArgFlagsTy Flags; 10667 if (NeedsRegBlock) { 10668 Flags.setInConsecutiveRegs(); 10669 if (I == RetTys.size() - 1) 10670 Flags.setInConsecutiveRegsLast(); 10671 } 10672 EVT VT = RetTys[I]; 10673 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10674 CLI.CallConv, VT); 10675 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10676 CLI.CallConv, VT); 10677 for (unsigned i = 0; i != NumRegs; ++i) { 10678 ISD::InputArg MyFlags; 10679 MyFlags.Flags = Flags; 10680 MyFlags.VT = RegisterVT; 10681 MyFlags.ArgVT = VT; 10682 MyFlags.Used = CLI.IsReturnValueUsed; 10683 if (CLI.RetTy->isPointerTy()) { 10684 MyFlags.Flags.setPointer(); 10685 MyFlags.Flags.setPointerAddrSpace( 10686 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10687 } 10688 if (CLI.RetSExt) 10689 MyFlags.Flags.setSExt(); 10690 if (CLI.RetZExt) 10691 MyFlags.Flags.setZExt(); 10692 if (CLI.IsInReg) 10693 MyFlags.Flags.setInReg(); 10694 CLI.Ins.push_back(MyFlags); 10695 } 10696 } 10697 } 10698 10699 // We push in swifterror return as the last element of CLI.Ins. 10700 ArgListTy &Args = CLI.getArgs(); 10701 if (supportSwiftError()) { 10702 for (const ArgListEntry &Arg : Args) { 10703 if (Arg.IsSwiftError) { 10704 ISD::InputArg MyFlags; 10705 MyFlags.VT = getPointerTy(DL); 10706 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10707 MyFlags.Flags.setSwiftError(); 10708 CLI.Ins.push_back(MyFlags); 10709 } 10710 } 10711 } 10712 10713 // Handle all of the outgoing arguments. 10714 CLI.Outs.clear(); 10715 CLI.OutVals.clear(); 10716 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10717 SmallVector<EVT, 4> ValueVTs; 10718 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10719 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10720 Type *FinalType = Args[i].Ty; 10721 if (Args[i].IsByVal) 10722 FinalType = Args[i].IndirectType; 10723 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10724 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10725 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10726 ++Value) { 10727 EVT VT = ValueVTs[Value]; 10728 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10729 SDValue Op = SDValue(Args[i].Node.getNode(), 10730 Args[i].Node.getResNo() + Value); 10731 ISD::ArgFlagsTy Flags; 10732 10733 // Certain targets (such as MIPS), may have a different ABI alignment 10734 // for a type depending on the context. Give the target a chance to 10735 // specify the alignment it wants. 10736 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10737 Flags.setOrigAlign(OriginalAlignment); 10738 10739 if (Args[i].Ty->isPointerTy()) { 10740 Flags.setPointer(); 10741 Flags.setPointerAddrSpace( 10742 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10743 } 10744 if (Args[i].IsZExt) 10745 Flags.setZExt(); 10746 if (Args[i].IsSExt) 10747 Flags.setSExt(); 10748 if (Args[i].IsInReg) { 10749 // If we are using vectorcall calling convention, a structure that is 10750 // passed InReg - is surely an HVA 10751 if (CLI.CallConv == CallingConv::X86_VectorCall && 10752 isa<StructType>(FinalType)) { 10753 // The first value of a structure is marked 10754 if (0 == Value) 10755 Flags.setHvaStart(); 10756 Flags.setHva(); 10757 } 10758 // Set InReg Flag 10759 Flags.setInReg(); 10760 } 10761 if (Args[i].IsSRet) 10762 Flags.setSRet(); 10763 if (Args[i].IsSwiftSelf) 10764 Flags.setSwiftSelf(); 10765 if (Args[i].IsSwiftAsync) 10766 Flags.setSwiftAsync(); 10767 if (Args[i].IsSwiftError) 10768 Flags.setSwiftError(); 10769 if (Args[i].IsCFGuardTarget) 10770 Flags.setCFGuardTarget(); 10771 if (Args[i].IsByVal) 10772 Flags.setByVal(); 10773 if (Args[i].IsByRef) 10774 Flags.setByRef(); 10775 if (Args[i].IsPreallocated) { 10776 Flags.setPreallocated(); 10777 // Set the byval flag for CCAssignFn callbacks that don't know about 10778 // preallocated. This way we can know how many bytes we should've 10779 // allocated and how many bytes a callee cleanup function will pop. If 10780 // we port preallocated to more targets, we'll have to add custom 10781 // preallocated handling in the various CC lowering callbacks. 10782 Flags.setByVal(); 10783 } 10784 if (Args[i].IsInAlloca) { 10785 Flags.setInAlloca(); 10786 // Set the byval flag for CCAssignFn callbacks that don't know about 10787 // inalloca. This way we can know how many bytes we should've allocated 10788 // and how many bytes a callee cleanup function will pop. If we port 10789 // inalloca to more targets, we'll have to add custom inalloca handling 10790 // in the various CC lowering callbacks. 10791 Flags.setByVal(); 10792 } 10793 Align MemAlign; 10794 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10795 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10796 Flags.setByValSize(FrameSize); 10797 10798 // info is not there but there are cases it cannot get right. 10799 if (auto MA = Args[i].Alignment) 10800 MemAlign = *MA; 10801 else 10802 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10803 } else if (auto MA = Args[i].Alignment) { 10804 MemAlign = *MA; 10805 } else { 10806 MemAlign = OriginalAlignment; 10807 } 10808 Flags.setMemAlign(MemAlign); 10809 if (Args[i].IsNest) 10810 Flags.setNest(); 10811 if (NeedsRegBlock) 10812 Flags.setInConsecutiveRegs(); 10813 10814 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10815 CLI.CallConv, VT); 10816 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10817 CLI.CallConv, VT); 10818 SmallVector<SDValue, 4> Parts(NumParts); 10819 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10820 10821 if (Args[i].IsSExt) 10822 ExtendKind = ISD::SIGN_EXTEND; 10823 else if (Args[i].IsZExt) 10824 ExtendKind = ISD::ZERO_EXTEND; 10825 10826 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10827 // for now. 10828 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10829 CanLowerReturn) { 10830 assert((CLI.RetTy == Args[i].Ty || 10831 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10832 CLI.RetTy->getPointerAddressSpace() == 10833 Args[i].Ty->getPointerAddressSpace())) && 10834 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10835 // Before passing 'returned' to the target lowering code, ensure that 10836 // either the register MVT and the actual EVT are the same size or that 10837 // the return value and argument are extended in the same way; in these 10838 // cases it's safe to pass the argument register value unchanged as the 10839 // return register value (although it's at the target's option whether 10840 // to do so) 10841 // TODO: allow code generation to take advantage of partially preserved 10842 // registers rather than clobbering the entire register when the 10843 // parameter extension method is not compatible with the return 10844 // extension method 10845 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10846 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10847 CLI.RetZExt == Args[i].IsZExt)) 10848 Flags.setReturned(); 10849 } 10850 10851 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10852 CLI.CallConv, ExtendKind); 10853 10854 for (unsigned j = 0; j != NumParts; ++j) { 10855 // if it isn't first piece, alignment must be 1 10856 // For scalable vectors the scalable part is currently handled 10857 // by individual targets, so we just use the known minimum size here. 10858 ISD::OutputArg MyFlags( 10859 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10860 i < CLI.NumFixedArgs, i, 10861 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10862 if (NumParts > 1 && j == 0) 10863 MyFlags.Flags.setSplit(); 10864 else if (j != 0) { 10865 MyFlags.Flags.setOrigAlign(Align(1)); 10866 if (j == NumParts - 1) 10867 MyFlags.Flags.setSplitEnd(); 10868 } 10869 10870 CLI.Outs.push_back(MyFlags); 10871 CLI.OutVals.push_back(Parts[j]); 10872 } 10873 10874 if (NeedsRegBlock && Value == NumValues - 1) 10875 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10876 } 10877 } 10878 10879 SmallVector<SDValue, 4> InVals; 10880 CLI.Chain = LowerCall(CLI, InVals); 10881 10882 // Update CLI.InVals to use outside of this function. 10883 CLI.InVals = InVals; 10884 10885 // Verify that the target's LowerCall behaved as expected. 10886 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10887 "LowerCall didn't return a valid chain!"); 10888 assert((!CLI.IsTailCall || InVals.empty()) && 10889 "LowerCall emitted a return value for a tail call!"); 10890 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10891 "LowerCall didn't emit the correct number of values!"); 10892 10893 // For a tail call, the return value is merely live-out and there aren't 10894 // any nodes in the DAG representing it. Return a special value to 10895 // indicate that a tail call has been emitted and no more Instructions 10896 // should be processed in the current block. 10897 if (CLI.IsTailCall) { 10898 CLI.DAG.setRoot(CLI.Chain); 10899 return std::make_pair(SDValue(), SDValue()); 10900 } 10901 10902 #ifndef NDEBUG 10903 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10904 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10905 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10906 "LowerCall emitted a value with the wrong type!"); 10907 } 10908 #endif 10909 10910 SmallVector<SDValue, 4> ReturnValues; 10911 if (!CanLowerReturn) { 10912 // The instruction result is the result of loading from the 10913 // hidden sret parameter. 10914 SmallVector<EVT, 1> PVTs; 10915 Type *PtrRetTy = 10916 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10917 10918 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10919 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10920 EVT PtrVT = PVTs[0]; 10921 10922 unsigned NumValues = RetTys.size(); 10923 ReturnValues.resize(NumValues); 10924 SmallVector<SDValue, 4> Chains(NumValues); 10925 10926 // An aggregate return value cannot wrap around the address space, so 10927 // offsets to its parts don't wrap either. 10928 SDNodeFlags Flags; 10929 Flags.setNoUnsignedWrap(true); 10930 10931 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10932 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10933 for (unsigned i = 0; i < NumValues; ++i) { 10934 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10935 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10936 PtrVT), Flags); 10937 SDValue L = CLI.DAG.getLoad( 10938 RetTys[i], CLI.DL, CLI.Chain, Add, 10939 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10940 DemoteStackIdx, Offsets[i]), 10941 HiddenSRetAlign); 10942 ReturnValues[i] = L; 10943 Chains[i] = L.getValue(1); 10944 } 10945 10946 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10947 } else { 10948 // Collect the legal value parts into potentially illegal values 10949 // that correspond to the original function's return values. 10950 std::optional<ISD::NodeType> AssertOp; 10951 if (CLI.RetSExt) 10952 AssertOp = ISD::AssertSext; 10953 else if (CLI.RetZExt) 10954 AssertOp = ISD::AssertZext; 10955 unsigned CurReg = 0; 10956 for (EVT VT : RetTys) { 10957 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10958 CLI.CallConv, VT); 10959 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10960 CLI.CallConv, VT); 10961 10962 ReturnValues.push_back(getCopyFromParts( 10963 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 10964 CLI.Chain, CLI.CallConv, AssertOp)); 10965 CurReg += NumRegs; 10966 } 10967 10968 // For a function returning void, there is no return value. We can't create 10969 // such a node, so we just return a null return value in that case. In 10970 // that case, nothing will actually look at the value. 10971 if (ReturnValues.empty()) 10972 return std::make_pair(SDValue(), CLI.Chain); 10973 } 10974 10975 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10976 CLI.DAG.getVTList(RetTys), ReturnValues); 10977 return std::make_pair(Res, CLI.Chain); 10978 } 10979 10980 /// Places new result values for the node in Results (their number 10981 /// and types must exactly match those of the original return values of 10982 /// the node), or leaves Results empty, which indicates that the node is not 10983 /// to be custom lowered after all. 10984 void TargetLowering::LowerOperationWrapper(SDNode *N, 10985 SmallVectorImpl<SDValue> &Results, 10986 SelectionDAG &DAG) const { 10987 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10988 10989 if (!Res.getNode()) 10990 return; 10991 10992 // If the original node has one result, take the return value from 10993 // LowerOperation as is. It might not be result number 0. 10994 if (N->getNumValues() == 1) { 10995 Results.push_back(Res); 10996 return; 10997 } 10998 10999 // If the original node has multiple results, then the return node should 11000 // have the same number of results. 11001 assert((N->getNumValues() == Res->getNumValues()) && 11002 "Lowering returned the wrong number of results!"); 11003 11004 // Places new result values base on N result number. 11005 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 11006 Results.push_back(Res.getValue(I)); 11007 } 11008 11009 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11010 llvm_unreachable("LowerOperation not implemented for this target!"); 11011 } 11012 11013 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 11014 unsigned Reg, 11015 ISD::NodeType ExtendType) { 11016 SDValue Op = getNonRegisterValue(V); 11017 assert((Op.getOpcode() != ISD::CopyFromReg || 11018 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 11019 "Copy from a reg to the same reg!"); 11020 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 11021 11022 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11023 // If this is an InlineAsm we have to match the registers required, not the 11024 // notional registers required by the type. 11025 11026 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 11027 std::nullopt); // This is not an ABI copy. 11028 SDValue Chain = DAG.getEntryNode(); 11029 11030 if (ExtendType == ISD::ANY_EXTEND) { 11031 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 11032 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 11033 ExtendType = PreferredExtendIt->second; 11034 } 11035 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 11036 PendingExports.push_back(Chain); 11037 } 11038 11039 #include "llvm/CodeGen/SelectionDAGISel.h" 11040 11041 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 11042 /// entry block, return true. This includes arguments used by switches, since 11043 /// the switch may expand into multiple basic blocks. 11044 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 11045 // With FastISel active, we may be splitting blocks, so force creation 11046 // of virtual registers for all non-dead arguments. 11047 if (FastISel) 11048 return A->use_empty(); 11049 11050 const BasicBlock &Entry = A->getParent()->front(); 11051 for (const User *U : A->users()) 11052 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 11053 return false; // Use not in entry block. 11054 11055 return true; 11056 } 11057 11058 using ArgCopyElisionMapTy = 11059 DenseMap<const Argument *, 11060 std::pair<const AllocaInst *, const StoreInst *>>; 11061 11062 /// Scan the entry block of the function in FuncInfo for arguments that look 11063 /// like copies into a local alloca. Record any copied arguments in 11064 /// ArgCopyElisionCandidates. 11065 static void 11066 findArgumentCopyElisionCandidates(const DataLayout &DL, 11067 FunctionLoweringInfo *FuncInfo, 11068 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 11069 // Record the state of every static alloca used in the entry block. Argument 11070 // allocas are all used in the entry block, so we need approximately as many 11071 // entries as we have arguments. 11072 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 11073 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 11074 unsigned NumArgs = FuncInfo->Fn->arg_size(); 11075 StaticAllocas.reserve(NumArgs * 2); 11076 11077 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 11078 if (!V) 11079 return nullptr; 11080 V = V->stripPointerCasts(); 11081 const auto *AI = dyn_cast<AllocaInst>(V); 11082 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 11083 return nullptr; 11084 auto Iter = StaticAllocas.insert({AI, Unknown}); 11085 return &Iter.first->second; 11086 }; 11087 11088 // Look for stores of arguments to static allocas. Look through bitcasts and 11089 // GEPs to handle type coercions, as long as the alloca is fully initialized 11090 // by the store. Any non-store use of an alloca escapes it and any subsequent 11091 // unanalyzed store might write it. 11092 // FIXME: Handle structs initialized with multiple stores. 11093 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 11094 // Look for stores, and handle non-store uses conservatively. 11095 const auto *SI = dyn_cast<StoreInst>(&I); 11096 if (!SI) { 11097 // We will look through cast uses, so ignore them completely. 11098 if (I.isCast()) 11099 continue; 11100 // Ignore debug info and pseudo op intrinsics, they don't escape or store 11101 // to allocas. 11102 if (I.isDebugOrPseudoInst()) 11103 continue; 11104 // This is an unknown instruction. Assume it escapes or writes to all 11105 // static alloca operands. 11106 for (const Use &U : I.operands()) { 11107 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 11108 *Info = StaticAllocaInfo::Clobbered; 11109 } 11110 continue; 11111 } 11112 11113 // If the stored value is a static alloca, mark it as escaped. 11114 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 11115 *Info = StaticAllocaInfo::Clobbered; 11116 11117 // Check if the destination is a static alloca. 11118 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 11119 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 11120 if (!Info) 11121 continue; 11122 const AllocaInst *AI = cast<AllocaInst>(Dst); 11123 11124 // Skip allocas that have been initialized or clobbered. 11125 if (*Info != StaticAllocaInfo::Unknown) 11126 continue; 11127 11128 // Check if the stored value is an argument, and that this store fully 11129 // initializes the alloca. 11130 // If the argument type has padding bits we can't directly forward a pointer 11131 // as the upper bits may contain garbage. 11132 // Don't elide copies from the same argument twice. 11133 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 11134 const auto *Arg = dyn_cast<Argument>(Val); 11135 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 11136 Arg->getType()->isEmptyTy() || 11137 DL.getTypeStoreSize(Arg->getType()) != 11138 DL.getTypeAllocSize(AI->getAllocatedType()) || 11139 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 11140 ArgCopyElisionCandidates.count(Arg)) { 11141 *Info = StaticAllocaInfo::Clobbered; 11142 continue; 11143 } 11144 11145 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 11146 << '\n'); 11147 11148 // Mark this alloca and store for argument copy elision. 11149 *Info = StaticAllocaInfo::Elidable; 11150 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 11151 11152 // Stop scanning if we've seen all arguments. This will happen early in -O0 11153 // builds, which is useful, because -O0 builds have large entry blocks and 11154 // many allocas. 11155 if (ArgCopyElisionCandidates.size() == NumArgs) 11156 break; 11157 } 11158 } 11159 11160 /// Try to elide argument copies from memory into a local alloca. Succeeds if 11161 /// ArgVal is a load from a suitable fixed stack object. 11162 static void tryToElideArgumentCopy( 11163 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 11164 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 11165 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 11166 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 11167 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 11168 // Check if this is a load from a fixed stack object. 11169 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 11170 if (!LNode) 11171 return; 11172 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 11173 if (!FINode) 11174 return; 11175 11176 // Check that the fixed stack object is the right size and alignment. 11177 // Look at the alignment that the user wrote on the alloca instead of looking 11178 // at the stack object. 11179 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 11180 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 11181 const AllocaInst *AI = ArgCopyIter->second.first; 11182 int FixedIndex = FINode->getIndex(); 11183 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 11184 int OldIndex = AllocaIndex; 11185 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 11186 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 11187 LLVM_DEBUG( 11188 dbgs() << " argument copy elision failed due to bad fixed stack " 11189 "object size\n"); 11190 return; 11191 } 11192 Align RequiredAlignment = AI->getAlign(); 11193 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 11194 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 11195 "greater than stack argument alignment (" 11196 << DebugStr(RequiredAlignment) << " vs " 11197 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 11198 return; 11199 } 11200 11201 // Perform the elision. Delete the old stack object and replace its only use 11202 // in the variable info map. Mark the stack object as mutable and aliased. 11203 LLVM_DEBUG({ 11204 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 11205 << " Replacing frame index " << OldIndex << " with " << FixedIndex 11206 << '\n'; 11207 }); 11208 MFI.RemoveStackObject(OldIndex); 11209 MFI.setIsImmutableObjectIndex(FixedIndex, false); 11210 MFI.setIsAliasedObjectIndex(FixedIndex, true); 11211 AllocaIndex = FixedIndex; 11212 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 11213 for (SDValue ArgVal : ArgVals) 11214 Chains.push_back(ArgVal.getValue(1)); 11215 11216 // Avoid emitting code for the store implementing the copy. 11217 const StoreInst *SI = ArgCopyIter->second.second; 11218 ElidedArgCopyInstrs.insert(SI); 11219 11220 // Check for uses of the argument again so that we can avoid exporting ArgVal 11221 // if it is't used by anything other than the store. 11222 for (const Value *U : Arg.users()) { 11223 if (U != SI) { 11224 ArgHasUses = true; 11225 break; 11226 } 11227 } 11228 } 11229 11230 void SelectionDAGISel::LowerArguments(const Function &F) { 11231 SelectionDAG &DAG = SDB->DAG; 11232 SDLoc dl = SDB->getCurSDLoc(); 11233 const DataLayout &DL = DAG.getDataLayout(); 11234 SmallVector<ISD::InputArg, 16> Ins; 11235 11236 // In Naked functions we aren't going to save any registers. 11237 if (F.hasFnAttribute(Attribute::Naked)) 11238 return; 11239 11240 if (!FuncInfo->CanLowerReturn) { 11241 // Put in an sret pointer parameter before all the other parameters. 11242 SmallVector<EVT, 1> ValueVTs; 11243 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11244 PointerType::get(F.getContext(), 11245 DAG.getDataLayout().getAllocaAddrSpace()), 11246 ValueVTs); 11247 11248 // NOTE: Assuming that a pointer will never break down to more than one VT 11249 // or one register. 11250 ISD::ArgFlagsTy Flags; 11251 Flags.setSRet(); 11252 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 11253 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 11254 ISD::InputArg::NoArgIndex, 0); 11255 Ins.push_back(RetArg); 11256 } 11257 11258 // Look for stores of arguments to static allocas. Mark such arguments with a 11259 // flag to ask the target to give us the memory location of that argument if 11260 // available. 11261 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11262 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11263 ArgCopyElisionCandidates); 11264 11265 // Set up the incoming argument description vector. 11266 for (const Argument &Arg : F.args()) { 11267 unsigned ArgNo = Arg.getArgNo(); 11268 SmallVector<EVT, 4> ValueVTs; 11269 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11270 bool isArgValueUsed = !Arg.use_empty(); 11271 unsigned PartBase = 0; 11272 Type *FinalType = Arg.getType(); 11273 if (Arg.hasAttribute(Attribute::ByVal)) 11274 FinalType = Arg.getParamByValType(); 11275 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11276 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11277 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11278 Value != NumValues; ++Value) { 11279 EVT VT = ValueVTs[Value]; 11280 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11281 ISD::ArgFlagsTy Flags; 11282 11283 11284 if (Arg.getType()->isPointerTy()) { 11285 Flags.setPointer(); 11286 Flags.setPointerAddrSpace( 11287 cast<PointerType>(Arg.getType())->getAddressSpace()); 11288 } 11289 if (Arg.hasAttribute(Attribute::ZExt)) 11290 Flags.setZExt(); 11291 if (Arg.hasAttribute(Attribute::SExt)) 11292 Flags.setSExt(); 11293 if (Arg.hasAttribute(Attribute::InReg)) { 11294 // If we are using vectorcall calling convention, a structure that is 11295 // passed InReg - is surely an HVA 11296 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11297 isa<StructType>(Arg.getType())) { 11298 // The first value of a structure is marked 11299 if (0 == Value) 11300 Flags.setHvaStart(); 11301 Flags.setHva(); 11302 } 11303 // Set InReg Flag 11304 Flags.setInReg(); 11305 } 11306 if (Arg.hasAttribute(Attribute::StructRet)) 11307 Flags.setSRet(); 11308 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11309 Flags.setSwiftSelf(); 11310 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11311 Flags.setSwiftAsync(); 11312 if (Arg.hasAttribute(Attribute::SwiftError)) 11313 Flags.setSwiftError(); 11314 if (Arg.hasAttribute(Attribute::ByVal)) 11315 Flags.setByVal(); 11316 if (Arg.hasAttribute(Attribute::ByRef)) 11317 Flags.setByRef(); 11318 if (Arg.hasAttribute(Attribute::InAlloca)) { 11319 Flags.setInAlloca(); 11320 // Set the byval flag for CCAssignFn callbacks that don't know about 11321 // inalloca. This way we can know how many bytes we should've allocated 11322 // and how many bytes a callee cleanup function will pop. If we port 11323 // inalloca to more targets, we'll have to add custom inalloca handling 11324 // in the various CC lowering callbacks. 11325 Flags.setByVal(); 11326 } 11327 if (Arg.hasAttribute(Attribute::Preallocated)) { 11328 Flags.setPreallocated(); 11329 // Set the byval flag for CCAssignFn callbacks that don't know about 11330 // preallocated. This way we can know how many bytes we should've 11331 // allocated and how many bytes a callee cleanup function will pop. If 11332 // we port preallocated to more targets, we'll have to add custom 11333 // preallocated handling in the various CC lowering callbacks. 11334 Flags.setByVal(); 11335 } 11336 11337 // Certain targets (such as MIPS), may have a different ABI alignment 11338 // for a type depending on the context. Give the target a chance to 11339 // specify the alignment it wants. 11340 const Align OriginalAlignment( 11341 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11342 Flags.setOrigAlign(OriginalAlignment); 11343 11344 Align MemAlign; 11345 Type *ArgMemTy = nullptr; 11346 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11347 Flags.isByRef()) { 11348 if (!ArgMemTy) 11349 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11350 11351 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11352 11353 // For in-memory arguments, size and alignment should be passed from FE. 11354 // BE will guess if this info is not there but there are cases it cannot 11355 // get right. 11356 if (auto ParamAlign = Arg.getParamStackAlign()) 11357 MemAlign = *ParamAlign; 11358 else if ((ParamAlign = Arg.getParamAlign())) 11359 MemAlign = *ParamAlign; 11360 else 11361 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11362 if (Flags.isByRef()) 11363 Flags.setByRefSize(MemSize); 11364 else 11365 Flags.setByValSize(MemSize); 11366 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11367 MemAlign = *ParamAlign; 11368 } else { 11369 MemAlign = OriginalAlignment; 11370 } 11371 Flags.setMemAlign(MemAlign); 11372 11373 if (Arg.hasAttribute(Attribute::Nest)) 11374 Flags.setNest(); 11375 if (NeedsRegBlock) 11376 Flags.setInConsecutiveRegs(); 11377 if (ArgCopyElisionCandidates.count(&Arg)) 11378 Flags.setCopyElisionCandidate(); 11379 if (Arg.hasAttribute(Attribute::Returned)) 11380 Flags.setReturned(); 11381 11382 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11383 *CurDAG->getContext(), F.getCallingConv(), VT); 11384 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11385 *CurDAG->getContext(), F.getCallingConv(), VT); 11386 for (unsigned i = 0; i != NumRegs; ++i) { 11387 // For scalable vectors, use the minimum size; individual targets 11388 // are responsible for handling scalable vector arguments and 11389 // return values. 11390 ISD::InputArg MyFlags( 11391 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11392 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11393 if (NumRegs > 1 && i == 0) 11394 MyFlags.Flags.setSplit(); 11395 // if it isn't first piece, alignment must be 1 11396 else if (i > 0) { 11397 MyFlags.Flags.setOrigAlign(Align(1)); 11398 if (i == NumRegs - 1) 11399 MyFlags.Flags.setSplitEnd(); 11400 } 11401 Ins.push_back(MyFlags); 11402 } 11403 if (NeedsRegBlock && Value == NumValues - 1) 11404 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11405 PartBase += VT.getStoreSize().getKnownMinValue(); 11406 } 11407 } 11408 11409 // Call the target to set up the argument values. 11410 SmallVector<SDValue, 8> InVals; 11411 SDValue NewRoot = TLI->LowerFormalArguments( 11412 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11413 11414 // Verify that the target's LowerFormalArguments behaved as expected. 11415 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11416 "LowerFormalArguments didn't return a valid chain!"); 11417 assert(InVals.size() == Ins.size() && 11418 "LowerFormalArguments didn't emit the correct number of values!"); 11419 LLVM_DEBUG({ 11420 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11421 assert(InVals[i].getNode() && 11422 "LowerFormalArguments emitted a null value!"); 11423 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11424 "LowerFormalArguments emitted a value with the wrong type!"); 11425 } 11426 }); 11427 11428 // Update the DAG with the new chain value resulting from argument lowering. 11429 DAG.setRoot(NewRoot); 11430 11431 // Set up the argument values. 11432 unsigned i = 0; 11433 if (!FuncInfo->CanLowerReturn) { 11434 // Create a virtual register for the sret pointer, and put in a copy 11435 // from the sret argument into it. 11436 SmallVector<EVT, 1> ValueVTs; 11437 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11438 PointerType::get(F.getContext(), 11439 DAG.getDataLayout().getAllocaAddrSpace()), 11440 ValueVTs); 11441 MVT VT = ValueVTs[0].getSimpleVT(); 11442 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11443 std::optional<ISD::NodeType> AssertOp; 11444 SDValue ArgValue = 11445 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11446 F.getCallingConv(), AssertOp); 11447 11448 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11449 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11450 Register SRetReg = 11451 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11452 FuncInfo->DemoteRegister = SRetReg; 11453 NewRoot = 11454 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11455 DAG.setRoot(NewRoot); 11456 11457 // i indexes lowered arguments. Bump it past the hidden sret argument. 11458 ++i; 11459 } 11460 11461 SmallVector<SDValue, 4> Chains; 11462 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11463 for (const Argument &Arg : F.args()) { 11464 SmallVector<SDValue, 4> ArgValues; 11465 SmallVector<EVT, 4> ValueVTs; 11466 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11467 unsigned NumValues = ValueVTs.size(); 11468 if (NumValues == 0) 11469 continue; 11470 11471 bool ArgHasUses = !Arg.use_empty(); 11472 11473 // Elide the copying store if the target loaded this argument from a 11474 // suitable fixed stack object. 11475 if (Ins[i].Flags.isCopyElisionCandidate()) { 11476 unsigned NumParts = 0; 11477 for (EVT VT : ValueVTs) 11478 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11479 F.getCallingConv(), VT); 11480 11481 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11482 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11483 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11484 } 11485 11486 // If this argument is unused then remember its value. It is used to generate 11487 // debugging information. 11488 bool isSwiftErrorArg = 11489 TLI->supportSwiftError() && 11490 Arg.hasAttribute(Attribute::SwiftError); 11491 if (!ArgHasUses && !isSwiftErrorArg) { 11492 SDB->setUnusedArgValue(&Arg, InVals[i]); 11493 11494 // Also remember any frame index for use in FastISel. 11495 if (FrameIndexSDNode *FI = 11496 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11497 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11498 } 11499 11500 for (unsigned Val = 0; Val != NumValues; ++Val) { 11501 EVT VT = ValueVTs[Val]; 11502 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11503 F.getCallingConv(), VT); 11504 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11505 *CurDAG->getContext(), F.getCallingConv(), VT); 11506 11507 // Even an apparent 'unused' swifterror argument needs to be returned. So 11508 // we do generate a copy for it that can be used on return from the 11509 // function. 11510 if (ArgHasUses || isSwiftErrorArg) { 11511 std::optional<ISD::NodeType> AssertOp; 11512 if (Arg.hasAttribute(Attribute::SExt)) 11513 AssertOp = ISD::AssertSext; 11514 else if (Arg.hasAttribute(Attribute::ZExt)) 11515 AssertOp = ISD::AssertZext; 11516 11517 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11518 PartVT, VT, nullptr, NewRoot, 11519 F.getCallingConv(), AssertOp)); 11520 } 11521 11522 i += NumParts; 11523 } 11524 11525 // We don't need to do anything else for unused arguments. 11526 if (ArgValues.empty()) 11527 continue; 11528 11529 // Note down frame index. 11530 if (FrameIndexSDNode *FI = 11531 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11532 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11533 11534 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11535 SDB->getCurSDLoc()); 11536 11537 SDB->setValue(&Arg, Res); 11538 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11539 // We want to associate the argument with the frame index, among 11540 // involved operands, that correspond to the lowest address. The 11541 // getCopyFromParts function, called earlier, is swapping the order of 11542 // the operands to BUILD_PAIR depending on endianness. The result of 11543 // that swapping is that the least significant bits of the argument will 11544 // be in the first operand of the BUILD_PAIR node, and the most 11545 // significant bits will be in the second operand. 11546 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11547 if (LoadSDNode *LNode = 11548 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11549 if (FrameIndexSDNode *FI = 11550 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11551 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11552 } 11553 11554 // Analyses past this point are naive and don't expect an assertion. 11555 if (Res.getOpcode() == ISD::AssertZext) 11556 Res = Res.getOperand(0); 11557 11558 // Update the SwiftErrorVRegDefMap. 11559 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11560 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11561 if (Register::isVirtualRegister(Reg)) 11562 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11563 Reg); 11564 } 11565 11566 // If this argument is live outside of the entry block, insert a copy from 11567 // wherever we got it to the vreg that other BB's will reference it as. 11568 if (Res.getOpcode() == ISD::CopyFromReg) { 11569 // If we can, though, try to skip creating an unnecessary vreg. 11570 // FIXME: This isn't very clean... it would be nice to make this more 11571 // general. 11572 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11573 if (Register::isVirtualRegister(Reg)) { 11574 FuncInfo->ValueMap[&Arg] = Reg; 11575 continue; 11576 } 11577 } 11578 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11579 FuncInfo->InitializeRegForValue(&Arg); 11580 SDB->CopyToExportRegsIfNeeded(&Arg); 11581 } 11582 } 11583 11584 if (!Chains.empty()) { 11585 Chains.push_back(NewRoot); 11586 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11587 } 11588 11589 DAG.setRoot(NewRoot); 11590 11591 assert(i == InVals.size() && "Argument register count mismatch!"); 11592 11593 // If any argument copy elisions occurred and we have debug info, update the 11594 // stale frame indices used in the dbg.declare variable info table. 11595 if (!ArgCopyElisionFrameIndexMap.empty()) { 11596 for (MachineFunction::VariableDbgInfo &VI : 11597 MF->getInStackSlotVariableDbgInfo()) { 11598 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11599 if (I != ArgCopyElisionFrameIndexMap.end()) 11600 VI.updateStackSlot(I->second); 11601 } 11602 } 11603 11604 // Finally, if the target has anything special to do, allow it to do so. 11605 emitFunctionEntryCode(); 11606 } 11607 11608 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11609 /// ensure constants are generated when needed. Remember the virtual registers 11610 /// that need to be added to the Machine PHI nodes as input. We cannot just 11611 /// directly add them, because expansion might result in multiple MBB's for one 11612 /// BB. As such, the start of the BB might correspond to a different MBB than 11613 /// the end. 11614 void 11615 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11617 11618 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11619 11620 // Check PHI nodes in successors that expect a value to be available from this 11621 // block. 11622 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11623 if (!isa<PHINode>(SuccBB->begin())) continue; 11624 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11625 11626 // If this terminator has multiple identical successors (common for 11627 // switches), only handle each succ once. 11628 if (!SuccsHandled.insert(SuccMBB).second) 11629 continue; 11630 11631 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11632 11633 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11634 // nodes and Machine PHI nodes, but the incoming operands have not been 11635 // emitted yet. 11636 for (const PHINode &PN : SuccBB->phis()) { 11637 // Ignore dead phi's. 11638 if (PN.use_empty()) 11639 continue; 11640 11641 // Skip empty types 11642 if (PN.getType()->isEmptyTy()) 11643 continue; 11644 11645 unsigned Reg; 11646 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11647 11648 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11649 unsigned &RegOut = ConstantsOut[C]; 11650 if (RegOut == 0) { 11651 RegOut = FuncInfo.CreateRegs(C); 11652 // We need to zero/sign extend ConstantInt phi operands to match 11653 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11654 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11655 if (auto *CI = dyn_cast<ConstantInt>(C)) 11656 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11657 : ISD::ZERO_EXTEND; 11658 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11659 } 11660 Reg = RegOut; 11661 } else { 11662 DenseMap<const Value *, Register>::iterator I = 11663 FuncInfo.ValueMap.find(PHIOp); 11664 if (I != FuncInfo.ValueMap.end()) 11665 Reg = I->second; 11666 else { 11667 assert(isa<AllocaInst>(PHIOp) && 11668 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11669 "Didn't codegen value into a register!??"); 11670 Reg = FuncInfo.CreateRegs(PHIOp); 11671 CopyValueToVirtualRegister(PHIOp, Reg); 11672 } 11673 } 11674 11675 // Remember that this register needs to added to the machine PHI node as 11676 // the input for this MBB. 11677 SmallVector<EVT, 4> ValueVTs; 11678 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11679 for (EVT VT : ValueVTs) { 11680 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11681 for (unsigned i = 0; i != NumRegisters; ++i) 11682 FuncInfo.PHINodesToUpdate.push_back( 11683 std::make_pair(&*MBBI++, Reg + i)); 11684 Reg += NumRegisters; 11685 } 11686 } 11687 } 11688 11689 ConstantsOut.clear(); 11690 } 11691 11692 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11693 MachineFunction::iterator I(MBB); 11694 if (++I == FuncInfo.MF->end()) 11695 return nullptr; 11696 return &*I; 11697 } 11698 11699 /// During lowering new call nodes can be created (such as memset, etc.). 11700 /// Those will become new roots of the current DAG, but complications arise 11701 /// when they are tail calls. In such cases, the call lowering will update 11702 /// the root, but the builder still needs to know that a tail call has been 11703 /// lowered in order to avoid generating an additional return. 11704 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11705 // If the node is null, we do have a tail call. 11706 if (MaybeTC.getNode() != nullptr) 11707 DAG.setRoot(MaybeTC); 11708 else 11709 HasTailCall = true; 11710 } 11711 11712 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11713 MachineBasicBlock *SwitchMBB, 11714 MachineBasicBlock *DefaultMBB) { 11715 MachineFunction *CurMF = FuncInfo.MF; 11716 MachineBasicBlock *NextMBB = nullptr; 11717 MachineFunction::iterator BBI(W.MBB); 11718 if (++BBI != FuncInfo.MF->end()) 11719 NextMBB = &*BBI; 11720 11721 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11722 11723 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11724 11725 if (Size == 2 && W.MBB == SwitchMBB) { 11726 // If any two of the cases has the same destination, and if one value 11727 // is the same as the other, but has one bit unset that the other has set, 11728 // use bit manipulation to do two compares at once. For example: 11729 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11730 // TODO: This could be extended to merge any 2 cases in switches with 3 11731 // cases. 11732 // TODO: Handle cases where W.CaseBB != SwitchBB. 11733 CaseCluster &Small = *W.FirstCluster; 11734 CaseCluster &Big = *W.LastCluster; 11735 11736 if (Small.Low == Small.High && Big.Low == Big.High && 11737 Small.MBB == Big.MBB) { 11738 const APInt &SmallValue = Small.Low->getValue(); 11739 const APInt &BigValue = Big.Low->getValue(); 11740 11741 // Check that there is only one bit different. 11742 APInt CommonBit = BigValue ^ SmallValue; 11743 if (CommonBit.isPowerOf2()) { 11744 SDValue CondLHS = getValue(Cond); 11745 EVT VT = CondLHS.getValueType(); 11746 SDLoc DL = getCurSDLoc(); 11747 11748 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11749 DAG.getConstant(CommonBit, DL, VT)); 11750 SDValue Cond = DAG.getSetCC( 11751 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11752 ISD::SETEQ); 11753 11754 // Update successor info. 11755 // Both Small and Big will jump to Small.BB, so we sum up the 11756 // probabilities. 11757 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11758 if (BPI) 11759 addSuccessorWithProb( 11760 SwitchMBB, DefaultMBB, 11761 // The default destination is the first successor in IR. 11762 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11763 else 11764 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11765 11766 // Insert the true branch. 11767 SDValue BrCond = 11768 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11769 DAG.getBasicBlock(Small.MBB)); 11770 // Insert the false branch. 11771 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11772 DAG.getBasicBlock(DefaultMBB)); 11773 11774 DAG.setRoot(BrCond); 11775 return; 11776 } 11777 } 11778 } 11779 11780 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11781 // Here, we order cases by probability so the most likely case will be 11782 // checked first. However, two clusters can have the same probability in 11783 // which case their relative ordering is non-deterministic. So we use Low 11784 // as a tie-breaker as clusters are guaranteed to never overlap. 11785 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11786 [](const CaseCluster &a, const CaseCluster &b) { 11787 return a.Prob != b.Prob ? 11788 a.Prob > b.Prob : 11789 a.Low->getValue().slt(b.Low->getValue()); 11790 }); 11791 11792 // Rearrange the case blocks so that the last one falls through if possible 11793 // without changing the order of probabilities. 11794 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11795 --I; 11796 if (I->Prob > W.LastCluster->Prob) 11797 break; 11798 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11799 std::swap(*I, *W.LastCluster); 11800 break; 11801 } 11802 } 11803 } 11804 11805 // Compute total probability. 11806 BranchProbability DefaultProb = W.DefaultProb; 11807 BranchProbability UnhandledProbs = DefaultProb; 11808 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11809 UnhandledProbs += I->Prob; 11810 11811 MachineBasicBlock *CurMBB = W.MBB; 11812 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11813 bool FallthroughUnreachable = false; 11814 MachineBasicBlock *Fallthrough; 11815 if (I == W.LastCluster) { 11816 // For the last cluster, fall through to the default destination. 11817 Fallthrough = DefaultMBB; 11818 FallthroughUnreachable = isa<UnreachableInst>( 11819 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11820 } else { 11821 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11822 CurMF->insert(BBI, Fallthrough); 11823 // Put Cond in a virtual register to make it available from the new blocks. 11824 ExportFromCurrentBlock(Cond); 11825 } 11826 UnhandledProbs -= I->Prob; 11827 11828 switch (I->Kind) { 11829 case CC_JumpTable: { 11830 // FIXME: Optimize away range check based on pivot comparisons. 11831 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11832 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11833 11834 // The jump block hasn't been inserted yet; insert it here. 11835 MachineBasicBlock *JumpMBB = JT->MBB; 11836 CurMF->insert(BBI, JumpMBB); 11837 11838 auto JumpProb = I->Prob; 11839 auto FallthroughProb = UnhandledProbs; 11840 11841 // If the default statement is a target of the jump table, we evenly 11842 // distribute the default probability to successors of CurMBB. Also 11843 // update the probability on the edge from JumpMBB to Fallthrough. 11844 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11845 SE = JumpMBB->succ_end(); 11846 SI != SE; ++SI) { 11847 if (*SI == DefaultMBB) { 11848 JumpProb += DefaultProb / 2; 11849 FallthroughProb -= DefaultProb / 2; 11850 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11851 JumpMBB->normalizeSuccProbs(); 11852 break; 11853 } 11854 } 11855 11856 // If the default clause is unreachable, propagate that knowledge into 11857 // JTH->FallthroughUnreachable which will use it to suppress the range 11858 // check. 11859 // 11860 // However, don't do this if we're doing branch target enforcement, 11861 // because a table branch _without_ a range check can be a tempting JOP 11862 // gadget - out-of-bounds inputs that are impossible in correct 11863 // execution become possible again if an attacker can influence the 11864 // control flow. So if an attacker doesn't already have a BTI bypass 11865 // available, we don't want them to be able to get one out of this 11866 // table branch. 11867 if (FallthroughUnreachable) { 11868 Function &CurFunc = CurMF->getFunction(); 11869 bool HasBranchTargetEnforcement = false; 11870 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11871 HasBranchTargetEnforcement = 11872 CurFunc.getFnAttribute("branch-target-enforcement") 11873 .getValueAsBool(); 11874 } else { 11875 HasBranchTargetEnforcement = 11876 CurMF->getMMI().getModule()->getModuleFlag( 11877 "branch-target-enforcement"); 11878 } 11879 if (!HasBranchTargetEnforcement) 11880 JTH->FallthroughUnreachable = true; 11881 } 11882 11883 if (!JTH->FallthroughUnreachable) 11884 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11885 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11886 CurMBB->normalizeSuccProbs(); 11887 11888 // The jump table header will be inserted in our current block, do the 11889 // range check, and fall through to our fallthrough block. 11890 JTH->HeaderBB = CurMBB; 11891 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11892 11893 // If we're in the right place, emit the jump table header right now. 11894 if (CurMBB == SwitchMBB) { 11895 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11896 JTH->Emitted = true; 11897 } 11898 break; 11899 } 11900 case CC_BitTests: { 11901 // FIXME: Optimize away range check based on pivot comparisons. 11902 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11903 11904 // The bit test blocks haven't been inserted yet; insert them here. 11905 for (BitTestCase &BTC : BTB->Cases) 11906 CurMF->insert(BBI, BTC.ThisBB); 11907 11908 // Fill in fields of the BitTestBlock. 11909 BTB->Parent = CurMBB; 11910 BTB->Default = Fallthrough; 11911 11912 BTB->DefaultProb = UnhandledProbs; 11913 // If the cases in bit test don't form a contiguous range, we evenly 11914 // distribute the probability on the edge to Fallthrough to two 11915 // successors of CurMBB. 11916 if (!BTB->ContiguousRange) { 11917 BTB->Prob += DefaultProb / 2; 11918 BTB->DefaultProb -= DefaultProb / 2; 11919 } 11920 11921 if (FallthroughUnreachable) 11922 BTB->FallthroughUnreachable = true; 11923 11924 // If we're in the right place, emit the bit test header right now. 11925 if (CurMBB == SwitchMBB) { 11926 visitBitTestHeader(*BTB, SwitchMBB); 11927 BTB->Emitted = true; 11928 } 11929 break; 11930 } 11931 case CC_Range: { 11932 const Value *RHS, *LHS, *MHS; 11933 ISD::CondCode CC; 11934 if (I->Low == I->High) { 11935 // Check Cond == I->Low. 11936 CC = ISD::SETEQ; 11937 LHS = Cond; 11938 RHS=I->Low; 11939 MHS = nullptr; 11940 } else { 11941 // Check I->Low <= Cond <= I->High. 11942 CC = ISD::SETLE; 11943 LHS = I->Low; 11944 MHS = Cond; 11945 RHS = I->High; 11946 } 11947 11948 // If Fallthrough is unreachable, fold away the comparison. 11949 if (FallthroughUnreachable) 11950 CC = ISD::SETTRUE; 11951 11952 // The false probability is the sum of all unhandled cases. 11953 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11954 getCurSDLoc(), I->Prob, UnhandledProbs); 11955 11956 if (CurMBB == SwitchMBB) 11957 visitSwitchCase(CB, SwitchMBB); 11958 else 11959 SL->SwitchCases.push_back(CB); 11960 11961 break; 11962 } 11963 } 11964 CurMBB = Fallthrough; 11965 } 11966 } 11967 11968 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11969 const SwitchWorkListItem &W, 11970 Value *Cond, 11971 MachineBasicBlock *SwitchMBB) { 11972 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11973 "Clusters not sorted?"); 11974 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11975 11976 auto [LastLeft, FirstRight, LeftProb, RightProb] = 11977 SL->computeSplitWorkItemInfo(W); 11978 11979 // Use the first element on the right as pivot since we will make less-than 11980 // comparisons against it. 11981 CaseClusterIt PivotCluster = FirstRight; 11982 assert(PivotCluster > W.FirstCluster); 11983 assert(PivotCluster <= W.LastCluster); 11984 11985 CaseClusterIt FirstLeft = W.FirstCluster; 11986 CaseClusterIt LastRight = W.LastCluster; 11987 11988 const ConstantInt *Pivot = PivotCluster->Low; 11989 11990 // New blocks will be inserted immediately after the current one. 11991 MachineFunction::iterator BBI(W.MBB); 11992 ++BBI; 11993 11994 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11995 // we can branch to its destination directly if it's squeezed exactly in 11996 // between the known lower bound and Pivot - 1. 11997 MachineBasicBlock *LeftMBB; 11998 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11999 FirstLeft->Low == W.GE && 12000 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 12001 LeftMBB = FirstLeft->MBB; 12002 } else { 12003 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12004 FuncInfo.MF->insert(BBI, LeftMBB); 12005 WorkList.push_back( 12006 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 12007 // Put Cond in a virtual register to make it available from the new blocks. 12008 ExportFromCurrentBlock(Cond); 12009 } 12010 12011 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 12012 // single cluster, RHS.Low == Pivot, and we can branch to its destination 12013 // directly if RHS.High equals the current upper bound. 12014 MachineBasicBlock *RightMBB; 12015 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 12016 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 12017 RightMBB = FirstRight->MBB; 12018 } else { 12019 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 12020 FuncInfo.MF->insert(BBI, RightMBB); 12021 WorkList.push_back( 12022 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 12023 // Put Cond in a virtual register to make it available from the new blocks. 12024 ExportFromCurrentBlock(Cond); 12025 } 12026 12027 // Create the CaseBlock record that will be used to lower the branch. 12028 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 12029 getCurSDLoc(), LeftProb, RightProb); 12030 12031 if (W.MBB == SwitchMBB) 12032 visitSwitchCase(CB, SwitchMBB); 12033 else 12034 SL->SwitchCases.push_back(CB); 12035 } 12036 12037 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 12038 // from the swith statement. 12039 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 12040 BranchProbability PeeledCaseProb) { 12041 if (PeeledCaseProb == BranchProbability::getOne()) 12042 return BranchProbability::getZero(); 12043 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 12044 12045 uint32_t Numerator = CaseProb.getNumerator(); 12046 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 12047 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 12048 } 12049 12050 // Try to peel the top probability case if it exceeds the threshold. 12051 // Return current MachineBasicBlock for the switch statement if the peeling 12052 // does not occur. 12053 // If the peeling is performed, return the newly created MachineBasicBlock 12054 // for the peeled switch statement. Also update Clusters to remove the peeled 12055 // case. PeeledCaseProb is the BranchProbability for the peeled case. 12056 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 12057 const SwitchInst &SI, CaseClusterVector &Clusters, 12058 BranchProbability &PeeledCaseProb) { 12059 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12060 // Don't perform if there is only one cluster or optimizing for size. 12061 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 12062 TM.getOptLevel() == CodeGenOptLevel::None || 12063 SwitchMBB->getParent()->getFunction().hasMinSize()) 12064 return SwitchMBB; 12065 12066 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 12067 unsigned PeeledCaseIndex = 0; 12068 bool SwitchPeeled = false; 12069 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 12070 CaseCluster &CC = Clusters[Index]; 12071 if (CC.Prob < TopCaseProb) 12072 continue; 12073 TopCaseProb = CC.Prob; 12074 PeeledCaseIndex = Index; 12075 SwitchPeeled = true; 12076 } 12077 if (!SwitchPeeled) 12078 return SwitchMBB; 12079 12080 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 12081 << TopCaseProb << "\n"); 12082 12083 // Record the MBB for the peeled switch statement. 12084 MachineFunction::iterator BBI(SwitchMBB); 12085 ++BBI; 12086 MachineBasicBlock *PeeledSwitchMBB = 12087 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 12088 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 12089 12090 ExportFromCurrentBlock(SI.getCondition()); 12091 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 12092 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 12093 nullptr, nullptr, TopCaseProb.getCompl()}; 12094 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 12095 12096 Clusters.erase(PeeledCaseIt); 12097 for (CaseCluster &CC : Clusters) { 12098 LLVM_DEBUG( 12099 dbgs() << "Scale the probablity for one cluster, before scaling: " 12100 << CC.Prob << "\n"); 12101 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 12102 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 12103 } 12104 PeeledCaseProb = TopCaseProb; 12105 return PeeledSwitchMBB; 12106 } 12107 12108 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 12109 // Extract cases from the switch. 12110 BranchProbabilityInfo *BPI = FuncInfo.BPI; 12111 CaseClusterVector Clusters; 12112 Clusters.reserve(SI.getNumCases()); 12113 for (auto I : SI.cases()) { 12114 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 12115 const ConstantInt *CaseVal = I.getCaseValue(); 12116 BranchProbability Prob = 12117 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 12118 : BranchProbability(1, SI.getNumCases() + 1); 12119 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 12120 } 12121 12122 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 12123 12124 // Cluster adjacent cases with the same destination. We do this at all 12125 // optimization levels because it's cheap to do and will make codegen faster 12126 // if there are many clusters. 12127 sortAndRangeify(Clusters); 12128 12129 // The branch probablity of the peeled case. 12130 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 12131 MachineBasicBlock *PeeledSwitchMBB = 12132 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 12133 12134 // If there is only the default destination, jump there directly. 12135 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 12136 if (Clusters.empty()) { 12137 assert(PeeledSwitchMBB == SwitchMBB); 12138 SwitchMBB->addSuccessor(DefaultMBB); 12139 if (DefaultMBB != NextBlock(SwitchMBB)) { 12140 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 12141 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 12142 } 12143 return; 12144 } 12145 12146 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 12147 DAG.getBFI()); 12148 SL->findBitTestClusters(Clusters, &SI); 12149 12150 LLVM_DEBUG({ 12151 dbgs() << "Case clusters: "; 12152 for (const CaseCluster &C : Clusters) { 12153 if (C.Kind == CC_JumpTable) 12154 dbgs() << "JT:"; 12155 if (C.Kind == CC_BitTests) 12156 dbgs() << "BT:"; 12157 12158 C.Low->getValue().print(dbgs(), true); 12159 if (C.Low != C.High) { 12160 dbgs() << '-'; 12161 C.High->getValue().print(dbgs(), true); 12162 } 12163 dbgs() << ' '; 12164 } 12165 dbgs() << '\n'; 12166 }); 12167 12168 assert(!Clusters.empty()); 12169 SwitchWorkList WorkList; 12170 CaseClusterIt First = Clusters.begin(); 12171 CaseClusterIt Last = Clusters.end() - 1; 12172 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 12173 // Scale the branchprobability for DefaultMBB if the peel occurs and 12174 // DefaultMBB is not replaced. 12175 if (PeeledCaseProb != BranchProbability::getZero() && 12176 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 12177 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 12178 WorkList.push_back( 12179 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 12180 12181 while (!WorkList.empty()) { 12182 SwitchWorkListItem W = WorkList.pop_back_val(); 12183 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 12184 12185 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 12186 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 12187 // For optimized builds, lower large range as a balanced binary tree. 12188 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 12189 continue; 12190 } 12191 12192 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 12193 } 12194 } 12195 12196 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 12197 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12198 auto DL = getCurSDLoc(); 12199 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12200 setValue(&I, DAG.getStepVector(DL, ResultVT)); 12201 } 12202 12203 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 12204 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12205 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12206 12207 SDLoc DL = getCurSDLoc(); 12208 SDValue V = getValue(I.getOperand(0)); 12209 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 12210 12211 if (VT.isScalableVector()) { 12212 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 12213 return; 12214 } 12215 12216 // Use VECTOR_SHUFFLE for the fixed-length vector 12217 // to maintain existing behavior. 12218 SmallVector<int, 8> Mask; 12219 unsigned NumElts = VT.getVectorMinNumElements(); 12220 for (unsigned i = 0; i != NumElts; ++i) 12221 Mask.push_back(NumElts - 1 - i); 12222 12223 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 12224 } 12225 12226 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 12227 auto DL = getCurSDLoc(); 12228 SDValue InVec = getValue(I.getOperand(0)); 12229 EVT OutVT = 12230 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 12231 12232 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 12233 12234 // ISD Node needs the input vectors split into two equal parts 12235 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12236 DAG.getVectorIdxConstant(0, DL)); 12237 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 12238 DAG.getVectorIdxConstant(OutNumElts, DL)); 12239 12240 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12241 // legalisation and combines. 12242 if (OutVT.isFixedLengthVector()) { 12243 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12244 createStrideMask(0, 2, OutNumElts)); 12245 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 12246 createStrideMask(1, 2, OutNumElts)); 12247 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 12248 setValue(&I, Res); 12249 return; 12250 } 12251 12252 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 12253 DAG.getVTList(OutVT, OutVT), Lo, Hi); 12254 setValue(&I, Res); 12255 } 12256 12257 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12258 auto DL = getCurSDLoc(); 12259 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12260 SDValue InVec0 = getValue(I.getOperand(0)); 12261 SDValue InVec1 = getValue(I.getOperand(1)); 12262 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12263 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12264 12265 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12266 // legalisation and combines. 12267 if (OutVT.isFixedLengthVector()) { 12268 unsigned NumElts = InVT.getVectorMinNumElements(); 12269 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12270 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12271 createInterleaveMask(NumElts, 2))); 12272 return; 12273 } 12274 12275 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12276 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12277 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12278 Res.getValue(1)); 12279 setValue(&I, Res); 12280 } 12281 12282 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12283 SmallVector<EVT, 4> ValueVTs; 12284 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12285 ValueVTs); 12286 unsigned NumValues = ValueVTs.size(); 12287 if (NumValues == 0) return; 12288 12289 SmallVector<SDValue, 4> Values(NumValues); 12290 SDValue Op = getValue(I.getOperand(0)); 12291 12292 for (unsigned i = 0; i != NumValues; ++i) 12293 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12294 SDValue(Op.getNode(), Op.getResNo() + i)); 12295 12296 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12297 DAG.getVTList(ValueVTs), Values)); 12298 } 12299 12300 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12301 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12302 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12303 12304 SDLoc DL = getCurSDLoc(); 12305 SDValue V1 = getValue(I.getOperand(0)); 12306 SDValue V2 = getValue(I.getOperand(1)); 12307 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12308 12309 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12310 if (VT.isScalableVector()) { 12311 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12312 DAG.getVectorIdxConstant(Imm, DL))); 12313 return; 12314 } 12315 12316 unsigned NumElts = VT.getVectorNumElements(); 12317 12318 uint64_t Idx = (NumElts + Imm) % NumElts; 12319 12320 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12321 SmallVector<int, 8> Mask; 12322 for (unsigned i = 0; i < NumElts; ++i) 12323 Mask.push_back(Idx + i); 12324 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12325 } 12326 12327 // Consider the following MIR after SelectionDAG, which produces output in 12328 // phyregs in the first case or virtregs in the second case. 12329 // 12330 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12331 // %5:gr32 = COPY $ebx 12332 // %6:gr32 = COPY $edx 12333 // %1:gr32 = COPY %6:gr32 12334 // %0:gr32 = COPY %5:gr32 12335 // 12336 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12337 // %1:gr32 = COPY %6:gr32 12338 // %0:gr32 = COPY %5:gr32 12339 // 12340 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12341 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12342 // 12343 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12344 // to a single virtreg (such as %0). The remaining outputs monotonically 12345 // increase in virtreg number from there. If a callbr has no outputs, then it 12346 // should not have a corresponding callbr landingpad; in fact, the callbr 12347 // landingpad would not even be able to refer to such a callbr. 12348 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12349 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12350 // There is definitely at least one copy. 12351 assert(MI->getOpcode() == TargetOpcode::COPY && 12352 "start of copy chain MUST be COPY"); 12353 Reg = MI->getOperand(1).getReg(); 12354 MI = MRI.def_begin(Reg)->getParent(); 12355 // There may be an optional second copy. 12356 if (MI->getOpcode() == TargetOpcode::COPY) { 12357 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12358 Reg = MI->getOperand(1).getReg(); 12359 assert(Reg.isPhysical() && "expected COPY of physical register"); 12360 MI = MRI.def_begin(Reg)->getParent(); 12361 } 12362 // The start of the chain must be an INLINEASM_BR. 12363 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12364 "end of copy chain MUST be INLINEASM_BR"); 12365 return Reg; 12366 } 12367 12368 // We must do this walk rather than the simpler 12369 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12370 // otherwise we will end up with copies of virtregs only valid along direct 12371 // edges. 12372 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12373 SmallVector<EVT, 8> ResultVTs; 12374 SmallVector<SDValue, 8> ResultValues; 12375 const auto *CBR = 12376 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12377 12378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12379 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12380 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12381 12382 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12383 SDValue Chain = DAG.getRoot(); 12384 12385 // Re-parse the asm constraints string. 12386 TargetLowering::AsmOperandInfoVector TargetConstraints = 12387 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12388 for (auto &T : TargetConstraints) { 12389 SDISelAsmOperandInfo OpInfo(T); 12390 if (OpInfo.Type != InlineAsm::isOutput) 12391 continue; 12392 12393 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12394 // individual constraint. 12395 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12396 12397 switch (OpInfo.ConstraintType) { 12398 case TargetLowering::C_Register: 12399 case TargetLowering::C_RegisterClass: { 12400 // Fill in OpInfo.AssignedRegs.Regs. 12401 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12402 12403 // getRegistersForValue may produce 1 to many registers based on whether 12404 // the OpInfo.ConstraintVT is legal on the target or not. 12405 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12406 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12407 if (Register::isPhysicalRegister(OriginalDef)) 12408 FuncInfo.MBB->addLiveIn(OriginalDef); 12409 // Update the assigned registers to use the original defs. 12410 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12411 } 12412 12413 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12414 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12415 ResultValues.push_back(V); 12416 ResultVTs.push_back(OpInfo.ConstraintVT); 12417 break; 12418 } 12419 case TargetLowering::C_Other: { 12420 SDValue Flag; 12421 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12422 OpInfo, DAG); 12423 ++InitialDef; 12424 ResultValues.push_back(V); 12425 ResultVTs.push_back(OpInfo.ConstraintVT); 12426 break; 12427 } 12428 default: 12429 break; 12430 } 12431 } 12432 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12433 DAG.getVTList(ResultVTs), ResultValues); 12434 setValue(&I, V); 12435 } 12436