1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 42 #include "llvm/CodeGen/MachineMemOperand.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachineOperand.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/CodeGen/RuntimeLibcalls.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsAMDGPU.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CommandLine.h" 94 #include "llvm/Support/Compiler.h" 95 #include "llvm/Support/Debug.h" 96 #include "llvm/Support/MathExtras.h" 97 #include "llvm/Support/raw_ostream.h" 98 #include "llvm/Target/TargetIntrinsicInfo.h" 99 #include "llvm/Target/TargetMachine.h" 100 #include "llvm/Target/TargetOptions.h" 101 #include "llvm/TargetParser/Triple.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <iterator> 105 #include <limits> 106 #include <optional> 107 #include <tuple> 108 109 using namespace llvm; 110 using namespace PatternMatch; 111 using namespace SwitchCG; 112 113 #define DEBUG_TYPE "isel" 114 115 /// LimitFloatPrecision - Generate low-precision inline sequences for 116 /// some float libcalls (6, 8 or 12 bits). 117 static unsigned LimitFloatPrecision; 118 119 static cl::opt<bool> 120 InsertAssertAlign("insert-assert-align", cl::init(true), 121 cl::desc("Insert the experimental `assertalign` node."), 122 cl::ReallyHidden); 123 124 static cl::opt<unsigned, true> 125 LimitFPPrecision("limit-float-precision", 126 cl::desc("Generate low-precision inline sequences " 127 "for some float libcalls"), 128 cl::location(LimitFloatPrecision), cl::Hidden, 129 cl::init(0)); 130 131 static cl::opt<unsigned> SwitchPeelThreshold( 132 "switch-peel-threshold", cl::Hidden, cl::init(66), 133 cl::desc("Set the case probability threshold for peeling the case from a " 134 "switch statement. A value greater than 100 will void this " 135 "optimization")); 136 137 // Limit the width of DAG chains. This is important in general to prevent 138 // DAG-based analysis from blowing up. For example, alias analysis and 139 // load clustering may not complete in reasonable time. It is difficult to 140 // recognize and avoid this situation within each individual analysis, and 141 // future analyses are likely to have the same behavior. Limiting DAG width is 142 // the safe approach and will be especially important with global DAGs. 143 // 144 // MaxParallelChains default is arbitrarily high to avoid affecting 145 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 146 // sequence over this should have been converted to llvm.memcpy by the 147 // frontend. It is easy to induce this behavior with .ll code such as: 148 // %buffer = alloca [4096 x i8] 149 // %data = load [4096 x i8]* %argPtr 150 // store [4096 x i8] %data, [4096 x i8]* %buffer 151 static const unsigned MaxParallelChains = 64; 152 153 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 154 const SDValue *Parts, unsigned NumParts, 155 MVT PartVT, EVT ValueVT, const Value *V, 156 SDValue InChain, 157 std::optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue 165 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 166 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 167 SDValue InChain, 168 std::optional<CallingConv::ID> CC = std::nullopt, 169 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 170 // Let the target assemble the parts if it wants to 171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 172 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 173 PartVT, ValueVT, CC)) 174 return Val; 175 176 if (ValueVT.isVector()) 177 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 178 InChain, CC); 179 180 assert(NumParts > 0 && "No parts to assemble!"); 181 SDValue Val = Parts[0]; 182 183 if (NumParts > 1) { 184 // Assemble the value from multiple parts. 185 if (ValueVT.isInteger()) { 186 unsigned PartBits = PartVT.getSizeInBits(); 187 unsigned ValueBits = ValueVT.getSizeInBits(); 188 189 // Assemble the power of 2 part. 190 unsigned RoundParts = llvm::bit_floor(NumParts); 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V, 200 InChain); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2, 202 PartVT, HalfVT, V, InChain); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, InChain, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 227 DAG.getConstant(Lo.getValueSizeInBits(), DL, 228 TLI.getShiftAmountTy( 229 TotalVT, DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, 249 InChain, CC); 250 } 251 } 252 253 // There is now one part, held in Val. Correct it to match ValueVT. 254 // PartEVT is the type of the register class that holds the value. 255 // ValueVT is the type of the inline asm operation. 256 EVT PartEVT = Val.getValueType(); 257 258 if (PartEVT == ValueVT) 259 return Val; 260 261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 262 ValueVT.bitsLT(PartEVT)) { 263 // For an FP value in an integer part, we need to truncate to the right 264 // width first. 265 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 266 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 267 } 268 269 // Handle types that have the same size. 270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 271 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 272 273 // Handle types with different sizes. 274 if (PartEVT.isInteger() && ValueVT.isInteger()) { 275 if (ValueVT.bitsLT(PartEVT)) { 276 // For a truncate, see if we have any information to 277 // indicate whether the truncated bits will always be 278 // zero or sign-extension. 279 if (AssertOp) 280 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 281 DAG.getValueType(ValueVT)); 282 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 283 } 284 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 285 } 286 287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 288 // FP_ROUND's are always exact here. 289 if (ValueVT.bitsLT(Val.getValueType())) { 290 291 SDValue NoChange = 292 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 293 294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr( 295 llvm::Attribute::StrictFP)) { 296 return DAG.getNode(ISD::STRICT_FP_ROUND, DL, 297 DAG.getVTList(ValueVT, MVT::Other), InChain, Val, 298 NoChange); 299 } 300 301 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange); 302 } 303 304 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 305 } 306 307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 308 // then truncating. 309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 310 ValueVT.bitsLT(PartEVT)) { 311 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 313 } 314 315 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 316 } 317 318 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 319 const Twine &ErrMsg) { 320 const Instruction *I = dyn_cast_or_null<Instruction>(V); 321 if (!V) 322 return Ctx.emitError(ErrMsg); 323 324 const char *AsmError = ", possible invalid constraint for vector type"; 325 if (const CallInst *CI = dyn_cast<CallInst>(I)) 326 if (CI->isInlineAsm()) 327 return Ctx.emitError(I, ErrMsg + AsmError); 328 329 return Ctx.emitError(I, ErrMsg); 330 } 331 332 /// getCopyFromPartsVector - Create a value that contains the specified legal 333 /// parts combined into the value they represent. If the parts combine to a 334 /// type larger than ValueVT then AssertOp can be used to specify whether the 335 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 336 /// ValueVT (ISD::AssertSext). 337 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 338 const SDValue *Parts, unsigned NumParts, 339 MVT PartVT, EVT ValueVT, const Value *V, 340 SDValue InChain, 341 std::optional<CallingConv::ID> CallConv) { 342 assert(ValueVT.isVector() && "Not a vector value"); 343 assert(NumParts > 0 && "No parts to assemble!"); 344 const bool IsABIRegCopy = CallConv.has_value(); 345 346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 347 SDValue Val = Parts[0]; 348 349 // Handle a multi-element vector. 350 if (NumParts > 1) { 351 EVT IntermediateVT; 352 MVT RegisterVT; 353 unsigned NumIntermediates; 354 unsigned NumRegs; 355 356 if (IsABIRegCopy) { 357 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 358 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 359 NumIntermediates, RegisterVT); 360 } else { 361 NumRegs = 362 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 363 NumIntermediates, RegisterVT); 364 } 365 366 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 367 NumParts = NumRegs; // Silence a compiler warning. 368 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 369 assert(RegisterVT.getSizeInBits() == 370 Parts[0].getSimpleValueType().getSizeInBits() && 371 "Part type sizes don't match!"); 372 373 // Assemble the parts into intermediate operands. 374 SmallVector<SDValue, 8> Ops(NumIntermediates); 375 if (NumIntermediates == NumParts) { 376 // If the register was not expanded, truncate or copy the value, 377 // as appropriate. 378 for (unsigned i = 0; i != NumParts; ++i) 379 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT, 380 V, InChain, CallConv); 381 } else if (NumParts > 0) { 382 // If the intermediate type was expanded, build the intermediate 383 // operands from the parts. 384 assert(NumParts % NumIntermediates == 0 && 385 "Must expand into a divisible number of parts!"); 386 unsigned Factor = NumParts / NumIntermediates; 387 for (unsigned i = 0; i != NumIntermediates; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT, 389 IntermediateVT, V, InChain, CallConv); 390 } 391 392 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 393 // intermediate operands. 394 EVT BuiltVectorTy = 395 IntermediateVT.isVector() 396 ? EVT::getVectorVT( 397 *DAG.getContext(), IntermediateVT.getScalarType(), 398 IntermediateVT.getVectorElementCount() * NumParts) 399 : EVT::getVectorVT(*DAG.getContext(), 400 IntermediateVT.getScalarType(), 401 NumIntermediates); 402 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 403 : ISD::BUILD_VECTOR, 404 DL, BuiltVectorTy, Ops); 405 } 406 407 // There is now one part, held in Val. Correct it to match ValueVT. 408 EVT PartEVT = Val.getValueType(); 409 410 if (PartEVT == ValueVT) 411 return Val; 412 413 if (PartEVT.isVector()) { 414 // Vector/Vector bitcast. 415 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 416 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 417 418 // If the parts vector has more elements than the value vector, then we 419 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 420 // Extract the elements we want. 421 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 422 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 423 ValueVT.getVectorElementCount().getKnownMinValue()) && 424 (PartEVT.getVectorElementCount().isScalable() == 425 ValueVT.getVectorElementCount().isScalable()) && 426 "Cannot narrow, it would be a lossy transformation"); 427 PartEVT = 428 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 429 ValueVT.getVectorElementCount()); 430 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 431 DAG.getVectorIdxConstant(0, DL)); 432 if (PartEVT == ValueVT) 433 return Val; 434 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 437 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 438 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 439 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 440 } 441 442 // Promoted vector extract 443 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 444 } 445 446 // Trivial bitcast if the types are the same size and the destination 447 // vector type is legal. 448 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 449 TLI.isTypeLegal(ValueVT)) 450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 451 452 if (ValueVT.getVectorNumElements() != 1) { 453 // Certain ABIs require that vectors are passed as integers. For vectors 454 // are the same size, this is an obvious bitcast. 455 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 456 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 457 } else if (ValueVT.bitsLT(PartEVT)) { 458 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 459 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 460 // Drop the extra bits. 461 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 462 return DAG.getBitcast(ValueVT, Val); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 473 unsigned ValueSize = ValueSVT.getSizeInBits(); 474 if (ValueSize == PartEVT.getSizeInBits()) { 475 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 476 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 477 // It's possible a scalar floating point type gets softened to integer and 478 // then promoted to a larger integer. If PartEVT is the larger integer 479 // we need to truncate it and then bitcast to the FP type. 480 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 481 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 482 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 483 Val = DAG.getBitcast(ValueSVT, Val); 484 } else { 485 Val = ValueVT.isFloatingPoint() 486 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 487 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 488 } 489 } 490 491 return DAG.getBuildVector(ValueVT, DL, Val); 492 } 493 494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 495 SDValue Val, SDValue *Parts, unsigned NumParts, 496 MVT PartVT, const Value *V, 497 std::optional<CallingConv::ID> CallConv); 498 499 /// getCopyToParts - Create a series of nodes that contain the specified value 500 /// split into legal parts. If the parts contain more bits than Val, then, for 501 /// integers, ExtendKind can be used to specify how to generate the extra bits. 502 static void 503 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 504 unsigned NumParts, MVT PartVT, const Value *V, 505 std::optional<CallingConv::ID> CallConv = std::nullopt, 506 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 507 // Let the target split the parts if it wants to 508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 509 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 510 CallConv)) 511 return; 512 EVT ValueVT = Val.getValueType(); 513 514 // Handle the vector case separately. 515 if (ValueVT.isVector()) 516 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 517 CallConv); 518 519 unsigned OrigNumParts = NumParts; 520 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 521 "Copying to an illegal type!"); 522 523 if (NumParts == 0) 524 return; 525 526 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 527 EVT PartEVT = PartVT; 528 if (PartEVT == ValueVT) { 529 assert(NumParts == 1 && "No-op copy with multiple parts!"); 530 Parts[0] = Val; 531 return; 532 } 533 534 unsigned PartBits = PartVT.getSizeInBits(); 535 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 536 // If the parts cover more bits than the value has, promote the value. 537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 538 assert(NumParts == 1 && "Do not know what to promote to!"); 539 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 540 } else { 541 if (ValueVT.isFloatingPoint()) { 542 // FP values need to be bitcast, then extended if they are being put 543 // into a larger container. 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 545 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 546 } 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 } else if (PartBits == ValueVT.getSizeInBits()) { 556 // Different types of the same size. 557 assert(NumParts == 1 && PartEVT != ValueVT); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 560 // If the parts cover less bits than value has, truncate the value. 561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 562 ValueVT.isInteger() && 563 "Unknown mismatch!"); 564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 565 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 566 if (PartVT == MVT::x86mmx) 567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 568 } 569 570 // The value may have changed - recompute ValueVT. 571 ValueVT = Val.getValueType(); 572 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 573 "Failed to tile the value with PartVT!"); 574 575 if (NumParts == 1) { 576 if (PartEVT != ValueVT) { 577 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 578 "scalar-to-vector conversion failed"); 579 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 580 } 581 582 Parts[0] = Val; 583 return; 584 } 585 586 // Expand the value into multiple parts. 587 if (NumParts & (NumParts - 1)) { 588 // The number of parts is not a power of 2. Split off and copy the tail. 589 assert(PartVT.isInteger() && ValueVT.isInteger() && 590 "Do not know what to expand to!"); 591 unsigned RoundParts = llvm::bit_floor(NumParts); 592 unsigned RoundBits = RoundParts * PartBits; 593 unsigned OddParts = NumParts - RoundParts; 594 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 595 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 596 597 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 598 CallConv); 599 600 if (DAG.getDataLayout().isBigEndian()) 601 // The odd parts were reversed by getCopyToParts - unreverse them. 602 std::reverse(Parts + RoundParts, Parts + NumParts); 603 604 NumParts = RoundParts; 605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 606 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 607 } 608 609 // The number of parts is a power of 2. Repeatedly bisect the value using 610 // EXTRACT_ELEMENT. 611 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 612 EVT::getIntegerVT(*DAG.getContext(), 613 ValueVT.getSizeInBits()), 614 Val); 615 616 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 617 for (unsigned i = 0; i < NumParts; i += StepSize) { 618 unsigned ThisBits = StepSize * PartBits / 2; 619 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 620 SDValue &Part0 = Parts[i]; 621 SDValue &Part1 = Parts[i+StepSize/2]; 622 623 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 625 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 627 628 if (ThisBits == PartBits && ThisVT != PartVT) { 629 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 630 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 631 } 632 } 633 } 634 635 if (DAG.getDataLayout().isBigEndian()) 636 std::reverse(Parts, Parts + OrigNumParts); 637 } 638 639 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 640 const SDLoc &DL, EVT PartVT) { 641 if (!PartVT.isVector()) 642 return SDValue(); 643 644 EVT ValueVT = Val.getValueType(); 645 EVT PartEVT = PartVT.getVectorElementType(); 646 EVT ValueEVT = ValueVT.getVectorElementType(); 647 ElementCount PartNumElts = PartVT.getVectorElementCount(); 648 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 649 650 // We only support widening vectors with equivalent element types and 651 // fixed/scalable properties. If a target needs to widen a fixed-length type 652 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 653 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 654 PartNumElts.isScalable() != ValueNumElts.isScalable()) 655 return SDValue(); 656 657 // Have a try for bf16 because some targets share its ABI with fp16. 658 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 659 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 660 "Cannot widen to illegal type"); 661 Val = DAG.getNode(ISD::BITCAST, DL, 662 ValueVT.changeVectorElementType(MVT::f16), Val); 663 } else if (PartEVT != ValueEVT) { 664 return SDValue(); 665 } 666 667 // Widening a scalable vector to another scalable vector is done by inserting 668 // the vector into a larger undef one. 669 if (PartNumElts.isScalable()) 670 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 671 Val, DAG.getVectorIdxConstant(0, DL)); 672 673 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 674 // undef elements. 675 SmallVector<SDValue, 16> Ops; 676 DAG.ExtractVectorElements(Val, Ops); 677 SDValue EltUndef = DAG.getUNDEF(PartEVT); 678 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 679 680 // FIXME: Use CONCAT for 2x -> 4x. 681 return DAG.getBuildVector(PartVT, DL, Ops); 682 } 683 684 /// getCopyToPartsVector - Create a series of nodes that contain the specified 685 /// value split into legal parts. 686 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 687 SDValue Val, SDValue *Parts, unsigned NumParts, 688 MVT PartVT, const Value *V, 689 std::optional<CallingConv::ID> CallConv) { 690 EVT ValueVT = Val.getValueType(); 691 assert(ValueVT.isVector() && "Not a vector"); 692 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 693 const bool IsABIRegCopy = CallConv.has_value(); 694 695 if (NumParts == 1) { 696 EVT PartEVT = PartVT; 697 if (PartEVT == ValueVT) { 698 // Nothing to do. 699 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 700 // Bitconvert vector->vector case. 701 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 702 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 703 Val = Widened; 704 } else if (PartVT.isVector() && 705 PartEVT.getVectorElementType().bitsGE( 706 ValueVT.getVectorElementType()) && 707 PartEVT.getVectorElementCount() == 708 ValueVT.getVectorElementCount()) { 709 710 // Promoted vector extract 711 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 712 } else if (PartEVT.isVector() && 713 PartEVT.getVectorElementType() != 714 ValueVT.getVectorElementType() && 715 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 716 TargetLowering::TypeWidenVector) { 717 // Combination of widening and promotion. 718 EVT WidenVT = 719 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 720 PartVT.getVectorElementCount()); 721 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 722 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 723 } else { 724 // Don't extract an integer from a float vector. This can happen if the 725 // FP type gets softened to integer and then promoted. The promotion 726 // prevents it from being picked up by the earlier bitcast case. 727 if (ValueVT.getVectorElementCount().isScalar() && 728 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 729 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 730 DAG.getVectorIdxConstant(0, DL)); 731 } else { 732 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 733 assert(PartVT.getFixedSizeInBits() > ValueSize && 734 "lossy conversion of vector to scalar type"); 735 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 736 Val = DAG.getBitcast(IntermediateType, Val); 737 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 738 } 739 } 740 741 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 742 Parts[0] = Val; 743 return; 744 } 745 746 // Handle a multi-element vector. 747 EVT IntermediateVT; 748 MVT RegisterVT; 749 unsigned NumIntermediates; 750 unsigned NumRegs; 751 if (IsABIRegCopy) { 752 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 753 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 754 RegisterVT); 755 } else { 756 NumRegs = 757 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 758 NumIntermediates, RegisterVT); 759 } 760 761 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 762 NumParts = NumRegs; // Silence a compiler warning. 763 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 764 765 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 766 "Mixing scalable and fixed vectors when copying in parts"); 767 768 std::optional<ElementCount> DestEltCnt; 769 770 if (IntermediateVT.isVector()) 771 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 772 else 773 DestEltCnt = ElementCount::getFixed(NumIntermediates); 774 775 EVT BuiltVectorTy = EVT::getVectorVT( 776 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 777 778 if (ValueVT == BuiltVectorTy) { 779 // Nothing to do. 780 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 781 // Bitconvert vector->vector case. 782 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 783 } else { 784 if (BuiltVectorTy.getVectorElementType().bitsGT( 785 ValueVT.getVectorElementType())) { 786 // Integer promotion. 787 ValueVT = EVT::getVectorVT(*DAG.getContext(), 788 BuiltVectorTy.getVectorElementType(), 789 ValueVT.getVectorElementCount()); 790 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 791 } 792 793 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 794 Val = Widened; 795 } 796 } 797 798 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 799 800 // Split the vector into intermediate operands. 801 SmallVector<SDValue, 8> Ops(NumIntermediates); 802 for (unsigned i = 0; i != NumIntermediates; ++i) { 803 if (IntermediateVT.isVector()) { 804 // This does something sensible for scalable vectors - see the 805 // definition of EXTRACT_SUBVECTOR for further details. 806 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 807 Ops[i] = 808 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 809 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 810 } else { 811 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 812 DAG.getVectorIdxConstant(i, DL)); 813 } 814 } 815 816 // Split the intermediate operands into legal parts. 817 if (NumParts == NumIntermediates) { 818 // If the register was not expanded, promote or copy the value, 819 // as appropriate. 820 for (unsigned i = 0; i != NumParts; ++i) 821 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 822 } else if (NumParts > 0) { 823 // If the intermediate type was expanded, split each the value into 824 // legal parts. 825 assert(NumIntermediates != 0 && "division by zero"); 826 assert(NumParts % NumIntermediates == 0 && 827 "Must expand into a divisible number of parts!"); 828 unsigned Factor = NumParts / NumIntermediates; 829 for (unsigned i = 0; i != NumIntermediates; ++i) 830 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 831 CallConv); 832 } 833 } 834 835 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 836 EVT valuevt, std::optional<CallingConv::ID> CC) 837 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 838 RegCount(1, regs.size()), CallConv(CC) {} 839 840 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 841 const DataLayout &DL, unsigned Reg, Type *Ty, 842 std::optional<CallingConv::ID> CC) { 843 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 844 845 CallConv = CC; 846 847 for (EVT ValueVT : ValueVTs) { 848 unsigned NumRegs = 849 isABIMangled() 850 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 851 : TLI.getNumRegisters(Context, ValueVT); 852 MVT RegisterVT = 853 isABIMangled() 854 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 855 : TLI.getRegisterType(Context, ValueVT); 856 for (unsigned i = 0; i != NumRegs; ++i) 857 Regs.push_back(Reg + i); 858 RegVTs.push_back(RegisterVT); 859 RegCount.push_back(NumRegs); 860 Reg += NumRegs; 861 } 862 } 863 864 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 865 FunctionLoweringInfo &FuncInfo, 866 const SDLoc &dl, SDValue &Chain, 867 SDValue *Glue, const Value *V) const { 868 // A Value with type {} or [0 x %t] needs no registers. 869 if (ValueVTs.empty()) 870 return SDValue(); 871 872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 873 874 // Assemble the legal parts into the final values. 875 SmallVector<SDValue, 4> Values(ValueVTs.size()); 876 SmallVector<SDValue, 8> Parts; 877 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 878 // Copy the legal parts from the registers. 879 EVT ValueVT = ValueVTs[Value]; 880 unsigned NumRegs = RegCount[Value]; 881 MVT RegisterVT = isABIMangled() 882 ? TLI.getRegisterTypeForCallingConv( 883 *DAG.getContext(), *CallConv, RegVTs[Value]) 884 : RegVTs[Value]; 885 886 Parts.resize(NumRegs); 887 for (unsigned i = 0; i != NumRegs; ++i) { 888 SDValue P; 889 if (!Glue) { 890 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 891 } else { 892 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 893 *Glue = P.getValue(2); 894 } 895 896 Chain = P.getValue(1); 897 Parts[i] = P; 898 899 // If the source register was virtual and if we know something about it, 900 // add an assert node. 901 if (!Register::isVirtualRegister(Regs[Part + i]) || 902 !RegisterVT.isInteger()) 903 continue; 904 905 const FunctionLoweringInfo::LiveOutInfo *LOI = 906 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 907 if (!LOI) 908 continue; 909 910 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 911 unsigned NumSignBits = LOI->NumSignBits; 912 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 913 914 if (NumZeroBits == RegSize) { 915 // The current value is a zero. 916 // Explicitly express that as it would be easier for 917 // optimizations to kick in. 918 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 919 continue; 920 } 921 922 // FIXME: We capture more information than the dag can represent. For 923 // now, just use the tightest assertzext/assertsext possible. 924 bool isSExt; 925 EVT FromVT(MVT::Other); 926 if (NumZeroBits) { 927 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 928 isSExt = false; 929 } else if (NumSignBits > 1) { 930 FromVT = 931 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 932 isSExt = true; 933 } else { 934 continue; 935 } 936 // Add an assertion node. 937 assert(FromVT != MVT::Other); 938 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 939 RegisterVT, P, DAG.getValueType(FromVT)); 940 } 941 942 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 943 RegisterVT, ValueVT, V, Chain, CallConv); 944 Part += NumRegs; 945 Parts.clear(); 946 } 947 948 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 949 } 950 951 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 952 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 953 const Value *V, 954 ISD::NodeType PreferredExtendType) const { 955 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 956 ISD::NodeType ExtendKind = PreferredExtendType; 957 958 // Get the list of the values's legal parts. 959 unsigned NumRegs = Regs.size(); 960 SmallVector<SDValue, 8> Parts(NumRegs); 961 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 962 unsigned NumParts = RegCount[Value]; 963 964 MVT RegisterVT = isABIMangled() 965 ? TLI.getRegisterTypeForCallingConv( 966 *DAG.getContext(), *CallConv, RegVTs[Value]) 967 : RegVTs[Value]; 968 969 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 970 ExtendKind = ISD::ZERO_EXTEND; 971 972 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 973 NumParts, RegisterVT, V, CallConv, ExtendKind); 974 Part += NumParts; 975 } 976 977 // Copy the parts into the registers. 978 SmallVector<SDValue, 8> Chains(NumRegs); 979 for (unsigned i = 0; i != NumRegs; ++i) { 980 SDValue Part; 981 if (!Glue) { 982 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 983 } else { 984 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 985 *Glue = Part.getValue(1); 986 } 987 988 Chains[i] = Part.getValue(0); 989 } 990 991 if (NumRegs == 1 || Glue) 992 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 993 // flagged to it. That is the CopyToReg nodes and the user are considered 994 // a single scheduling unit. If we create a TokenFactor and return it as 995 // chain, then the TokenFactor is both a predecessor (operand) of the 996 // user as well as a successor (the TF operands are flagged to the user). 997 // c1, f1 = CopyToReg 998 // c2, f2 = CopyToReg 999 // c3 = TokenFactor c1, c2 1000 // ... 1001 // = op c3, ..., f2 1002 Chain = Chains[NumRegs-1]; 1003 else 1004 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 1005 } 1006 1007 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, 1008 unsigned MatchingIdx, const SDLoc &dl, 1009 SelectionDAG &DAG, 1010 std::vector<SDValue> &Ops) const { 1011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1012 1013 InlineAsm::Flag Flag(Code, Regs.size()); 1014 if (HasMatching) 1015 Flag.setMatchingOp(MatchingIdx); 1016 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1017 // Put the register class of the virtual registers in the flag word. That 1018 // way, later passes can recompute register class constraints for inline 1019 // assembly as well as normal instructions. 1020 // Don't do this for tied operands that can use the regclass information 1021 // from the def. 1022 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1023 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1024 Flag.setRegClass(RC->getID()); 1025 } 1026 1027 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1028 Ops.push_back(Res); 1029 1030 if (Code == InlineAsm::Kind::Clobber) { 1031 // Clobbers should always have a 1:1 mapping with registers, and may 1032 // reference registers that have illegal (e.g. vector) types. Hence, we 1033 // shouldn't try to apply any sort of splitting logic to them. 1034 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1035 "No 1:1 mapping from clobbers to regs?"); 1036 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1037 (void)SP; 1038 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1039 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1040 assert( 1041 (Regs[I] != SP || 1042 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1043 "If we clobbered the stack pointer, MFI should know about it."); 1044 } 1045 return; 1046 } 1047 1048 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1049 MVT RegisterVT = RegVTs[Value]; 1050 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1051 RegisterVT); 1052 for (unsigned i = 0; i != NumRegs; ++i) { 1053 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1054 unsigned TheReg = Regs[Reg++]; 1055 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1056 } 1057 } 1058 } 1059 1060 SmallVector<std::pair<unsigned, TypeSize>, 4> 1061 RegsForValue::getRegsAndSizes() const { 1062 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1063 unsigned I = 0; 1064 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1065 unsigned RegCount = std::get<0>(CountAndVT); 1066 MVT RegisterVT = std::get<1>(CountAndVT); 1067 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1068 for (unsigned E = I + RegCount; I != E; ++I) 1069 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1070 } 1071 return OutVec; 1072 } 1073 1074 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1075 AssumptionCache *ac, 1076 const TargetLibraryInfo *li) { 1077 AA = aa; 1078 AC = ac; 1079 GFI = gfi; 1080 LibInfo = li; 1081 Context = DAG.getContext(); 1082 LPadToCallSiteMap.clear(); 1083 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1084 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1085 *DAG.getMachineFunction().getFunction().getParent()); 1086 } 1087 1088 void SelectionDAGBuilder::clear() { 1089 NodeMap.clear(); 1090 UnusedArgNodeMap.clear(); 1091 PendingLoads.clear(); 1092 PendingExports.clear(); 1093 PendingConstrainedFP.clear(); 1094 PendingConstrainedFPStrict.clear(); 1095 CurInst = nullptr; 1096 HasTailCall = false; 1097 SDNodeOrder = LowestSDNodeOrder; 1098 StatepointLowering.clear(); 1099 } 1100 1101 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1102 DanglingDebugInfoMap.clear(); 1103 } 1104 1105 // Update DAG root to include dependencies on Pending chains. 1106 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1107 SDValue Root = DAG.getRoot(); 1108 1109 if (Pending.empty()) 1110 return Root; 1111 1112 // Add current root to PendingChains, unless we already indirectly 1113 // depend on it. 1114 if (Root.getOpcode() != ISD::EntryToken) { 1115 unsigned i = 0, e = Pending.size(); 1116 for (; i != e; ++i) { 1117 assert(Pending[i].getNode()->getNumOperands() > 1); 1118 if (Pending[i].getNode()->getOperand(0) == Root) 1119 break; // Don't add the root if we already indirectly depend on it. 1120 } 1121 1122 if (i == e) 1123 Pending.push_back(Root); 1124 } 1125 1126 if (Pending.size() == 1) 1127 Root = Pending[0]; 1128 else 1129 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1130 1131 DAG.setRoot(Root); 1132 Pending.clear(); 1133 return Root; 1134 } 1135 1136 SDValue SelectionDAGBuilder::getMemoryRoot() { 1137 return updateRoot(PendingLoads); 1138 } 1139 1140 SDValue SelectionDAGBuilder::getRoot() { 1141 // Chain up all pending constrained intrinsics together with all 1142 // pending loads, by simply appending them to PendingLoads and 1143 // then calling getMemoryRoot(). 1144 PendingLoads.reserve(PendingLoads.size() + 1145 PendingConstrainedFP.size() + 1146 PendingConstrainedFPStrict.size()); 1147 PendingLoads.append(PendingConstrainedFP.begin(), 1148 PendingConstrainedFP.end()); 1149 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1150 PendingConstrainedFPStrict.end()); 1151 PendingConstrainedFP.clear(); 1152 PendingConstrainedFPStrict.clear(); 1153 return getMemoryRoot(); 1154 } 1155 1156 SDValue SelectionDAGBuilder::getControlRoot() { 1157 // We need to emit pending fpexcept.strict constrained intrinsics, 1158 // so append them to the PendingExports list. 1159 PendingExports.append(PendingConstrainedFPStrict.begin(), 1160 PendingConstrainedFPStrict.end()); 1161 PendingConstrainedFPStrict.clear(); 1162 return updateRoot(PendingExports); 1163 } 1164 1165 void SelectionDAGBuilder::handleDebugDeclare(Value *Address, 1166 DILocalVariable *Variable, 1167 DIExpression *Expression, 1168 DebugLoc DL) { 1169 assert(Variable && "Missing variable"); 1170 1171 // Check if address has undef value. 1172 if (!Address || isa<UndefValue>(Address) || 1173 (Address->use_empty() && !isa<Argument>(Address))) { 1174 LLVM_DEBUG( 1175 dbgs() 1176 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n"); 1177 return; 1178 } 1179 1180 bool IsParameter = Variable->isParameter() || isa<Argument>(Address); 1181 1182 SDValue &N = NodeMap[Address]; 1183 if (!N.getNode() && isa<Argument>(Address)) 1184 // Check unused arguments map. 1185 N = UnusedArgNodeMap[Address]; 1186 SDDbgValue *SDV; 1187 if (N.getNode()) { 1188 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 1189 Address = BCI->getOperand(0); 1190 // Parameters are handled specially. 1191 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 1192 if (IsParameter && FINode) { 1193 // Byval parameter. We have a frame index at this point. 1194 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 1195 /*IsIndirect*/ true, DL, SDNodeOrder); 1196 } else if (isa<Argument>(Address)) { 1197 // Address is an argument, so try to emit its dbg value using 1198 // virtual register info from the FuncInfo.ValueMap. 1199 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1200 FuncArgumentDbgValueKind::Declare, N); 1201 return; 1202 } else { 1203 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 1204 true, DL, SDNodeOrder); 1205 } 1206 DAG.AddDbgValue(SDV, IsParameter); 1207 } else { 1208 // If Address is an argument then try to emit its dbg value using 1209 // virtual register info from the FuncInfo.ValueMap. 1210 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL, 1211 FuncArgumentDbgValueKind::Declare, N)) { 1212 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info" 1213 << " (could not emit func-arg dbg_value)\n"); 1214 } 1215 } 1216 return; 1217 } 1218 1219 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) { 1220 // Add SDDbgValue nodes for any var locs here. Do so before updating 1221 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1222 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1223 // Add SDDbgValue nodes for any var locs here. Do so before updating 1224 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1225 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1226 It != End; ++It) { 1227 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1228 dropDanglingDebugInfo(Var, It->Expr); 1229 if (It->Values.isKillLocation(It->Expr)) { 1230 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1231 continue; 1232 } 1233 SmallVector<Value *> Values(It->Values.location_ops()); 1234 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1235 It->Values.hasArgList())) { 1236 SmallVector<Value *, 4> Vals; 1237 for (Value *V : It->Values.location_ops()) 1238 Vals.push_back(V); 1239 addDanglingDebugInfo(Vals, 1240 FnVarLocs->getDILocalVariable(It->VariableID), 1241 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder); 1242 } 1243 } 1244 // We must early-exit here to prevent any DPValues from being emitted below, 1245 // as we have just emitted the debug values resulting from assignment 1246 // tracking analysis, making any existing DPValues redundant (and probably 1247 // less correct). 1248 return; 1249 } 1250 1251 // Is there is any debug-info attached to this instruction, in the form of 1252 // DPValue non-instruction debug-info records. 1253 for (DbgRecord &DPR : I.getDbgValueRange()) { 1254 DPValue &DPV = cast<DPValue>(DPR); 1255 DILocalVariable *Variable = DPV.getVariable(); 1256 DIExpression *Expression = DPV.getExpression(); 1257 dropDanglingDebugInfo(Variable, Expression); 1258 1259 if (DPV.getType() == DPValue::LocationType::Declare) { 1260 if (FuncInfo.PreprocessedDPVDeclares.contains(&DPV)) 1261 continue; 1262 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DPV 1263 << "\n"); 1264 handleDebugDeclare(DPV.getVariableLocationOp(0), Variable, Expression, 1265 DPV.getDebugLoc()); 1266 continue; 1267 } 1268 1269 // A DPValue with no locations is a kill location. 1270 SmallVector<Value *, 4> Values(DPV.location_ops()); 1271 if (Values.empty()) { 1272 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1273 SDNodeOrder); 1274 continue; 1275 } 1276 1277 // A DPValue with an undef or absent location is also a kill location. 1278 if (llvm::any_of(Values, 1279 [](Value *V) { return !V || isa<UndefValue>(V); })) { 1280 handleKillDebugValue(Variable, Expression, DPV.getDebugLoc(), 1281 SDNodeOrder); 1282 continue; 1283 } 1284 1285 bool IsVariadic = DPV.hasArgList(); 1286 if (!handleDebugValue(Values, Variable, Expression, DPV.getDebugLoc(), 1287 SDNodeOrder, IsVariadic)) { 1288 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 1289 DPV.getDebugLoc(), SDNodeOrder); 1290 } 1291 } 1292 } 1293 1294 void SelectionDAGBuilder::visit(const Instruction &I) { 1295 visitDbgInfo(I); 1296 1297 // Set up outgoing PHI node register values before emitting the terminator. 1298 if (I.isTerminator()) { 1299 HandlePHINodesInSuccessorBlocks(I.getParent()); 1300 } 1301 1302 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1303 if (!isa<DbgInfoIntrinsic>(I)) 1304 ++SDNodeOrder; 1305 1306 CurInst = &I; 1307 1308 // Set inserted listener only if required. 1309 bool NodeInserted = false; 1310 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1311 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1312 if (PCSectionsMD) { 1313 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1314 DAG, [&](SDNode *) { NodeInserted = true; }); 1315 } 1316 1317 visit(I.getOpcode(), I); 1318 1319 if (!I.isTerminator() && !HasTailCall && 1320 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1321 CopyToExportRegsIfNeeded(&I); 1322 1323 // Handle metadata. 1324 if (PCSectionsMD) { 1325 auto It = NodeMap.find(&I); 1326 if (It != NodeMap.end()) { 1327 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1328 } else if (NodeInserted) { 1329 // This should not happen; if it does, don't let it go unnoticed so we can 1330 // fix it. Relevant visit*() function is probably missing a setValue(). 1331 errs() << "warning: loosing !pcsections metadata [" 1332 << I.getModule()->getName() << "]\n"; 1333 LLVM_DEBUG(I.dump()); 1334 assert(false); 1335 } 1336 } 1337 1338 CurInst = nullptr; 1339 } 1340 1341 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1342 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1343 } 1344 1345 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1346 // Note: this doesn't use InstVisitor, because it has to work with 1347 // ConstantExpr's in addition to instructions. 1348 switch (Opcode) { 1349 default: llvm_unreachable("Unknown instruction type encountered!"); 1350 // Build the switch statement using the Instruction.def file. 1351 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1352 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1353 #include "llvm/IR/Instruction.def" 1354 } 1355 } 1356 1357 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1358 DILocalVariable *Variable, 1359 DebugLoc DL, unsigned Order, 1360 SmallVectorImpl<Value *> &Values, 1361 DIExpression *Expression) { 1362 // For variadic dbg_values we will now insert an undef. 1363 // FIXME: We can potentially recover these! 1364 SmallVector<SDDbgOperand, 2> Locs; 1365 for (const Value *V : Values) { 1366 auto *Undef = UndefValue::get(V->getType()); 1367 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1368 } 1369 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1370 /*IsIndirect=*/false, DL, Order, 1371 /*IsVariadic=*/true); 1372 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1373 return true; 1374 } 1375 1376 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values, 1377 DILocalVariable *Var, 1378 DIExpression *Expr, 1379 bool IsVariadic, DebugLoc DL, 1380 unsigned Order) { 1381 if (IsVariadic) { 1382 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr); 1383 return; 1384 } 1385 // TODO: Dangling debug info will eventually either be resolved or produce 1386 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1387 // between the original dbg.value location and its resolved DBG_VALUE, 1388 // which we should ideally fill with an extra Undef DBG_VALUE. 1389 assert(Values.size() == 1); 1390 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order); 1391 } 1392 1393 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1394 const DIExpression *Expr) { 1395 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1396 DIVariable *DanglingVariable = DDI.getVariable(); 1397 DIExpression *DanglingExpr = DDI.getExpression(); 1398 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1399 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " 1400 << printDDI(nullptr, DDI) << "\n"); 1401 return true; 1402 } 1403 return false; 1404 }; 1405 1406 for (auto &DDIMI : DanglingDebugInfoMap) { 1407 DanglingDebugInfoVector &DDIV = DDIMI.second; 1408 1409 // If debug info is to be dropped, run it through final checks to see 1410 // whether it can be salvaged. 1411 for (auto &DDI : DDIV) 1412 if (isMatchingDbgValue(DDI)) 1413 salvageUnresolvedDbgValue(DDIMI.first, DDI); 1414 1415 erase_if(DDIV, isMatchingDbgValue); 1416 } 1417 } 1418 1419 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1420 // generate the debug data structures now that we've seen its definition. 1421 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1422 SDValue Val) { 1423 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1424 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1425 return; 1426 1427 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1428 for (auto &DDI : DDIV) { 1429 DebugLoc DL = DDI.getDebugLoc(); 1430 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1431 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1432 DILocalVariable *Variable = DDI.getVariable(); 1433 DIExpression *Expr = DDI.getExpression(); 1434 assert(Variable->isValidLocationForIntrinsic(DL) && 1435 "Expected inlined-at fields to agree"); 1436 SDDbgValue *SDV; 1437 if (Val.getNode()) { 1438 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1439 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1440 // we couldn't resolve it directly when examining the DbgValue intrinsic 1441 // in the first place we should not be more successful here). Unless we 1442 // have some test case that prove this to be correct we should avoid 1443 // calling EmitFuncArgumentDbgValue here. 1444 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1445 FuncArgumentDbgValueKind::Value, Val)) { 1446 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " 1447 << printDDI(V, DDI) << "\n"); 1448 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1449 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1450 // inserted after the definition of Val when emitting the instructions 1451 // after ISel. An alternative could be to teach 1452 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1453 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1454 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1455 << ValSDNodeOrder << "\n"); 1456 SDV = getDbgValue(Val, Variable, Expr, DL, 1457 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1458 DAG.AddDbgValue(SDV, false); 1459 } else 1460 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1461 << printDDI(V, DDI) 1462 << " in EmitFuncArgumentDbgValue\n"); 1463 } else { 1464 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI) 1465 << "\n"); 1466 auto Undef = UndefValue::get(V->getType()); 1467 auto SDV = 1468 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1469 DAG.AddDbgValue(SDV, false); 1470 } 1471 } 1472 DDIV.clear(); 1473 } 1474 1475 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V, 1476 DanglingDebugInfo &DDI) { 1477 // TODO: For the variadic implementation, instead of only checking the fail 1478 // state of `handleDebugValue`, we need know specifically which values were 1479 // invalid, so that we attempt to salvage only those values when processing 1480 // a DIArgList. 1481 const Value *OrigV = V; 1482 DILocalVariable *Var = DDI.getVariable(); 1483 DIExpression *Expr = DDI.getExpression(); 1484 DebugLoc DL = DDI.getDebugLoc(); 1485 unsigned SDOrder = DDI.getSDNodeOrder(); 1486 1487 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1488 // that DW_OP_stack_value is desired. 1489 bool StackValue = true; 1490 1491 // Can this Value can be encoded without any further work? 1492 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1493 return; 1494 1495 // Attempt to salvage back through as many instructions as possible. Bail if 1496 // a non-instruction is seen, such as a constant expression or global 1497 // variable. FIXME: Further work could recover those too. 1498 while (isa<Instruction>(V)) { 1499 const Instruction &VAsInst = *cast<const Instruction>(V); 1500 // Temporary "0", awaiting real implementation. 1501 SmallVector<uint64_t, 16> Ops; 1502 SmallVector<Value *, 4> AdditionalValues; 1503 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst), 1504 Expr->getNumLocationOperands(), Ops, 1505 AdditionalValues); 1506 // If we cannot salvage any further, and haven't yet found a suitable debug 1507 // expression, bail out. 1508 if (!V) 1509 break; 1510 1511 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1512 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1513 // here for variadic dbg_values, remove that condition. 1514 if (!AdditionalValues.empty()) 1515 break; 1516 1517 // New value and expr now represent this debuginfo. 1518 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1519 1520 // Some kind of simplification occurred: check whether the operand of the 1521 // salvaged debug expression can be encoded in this DAG. 1522 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1523 LLVM_DEBUG( 1524 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1525 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1526 return; 1527 } 1528 } 1529 1530 // This was the final opportunity to salvage this debug information, and it 1531 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1532 // any earlier variable location. 1533 assert(OrigV && "V shouldn't be null"); 1534 auto *Undef = UndefValue::get(OrigV->getType()); 1535 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1536 DAG.AddDbgValue(SDV, false); 1537 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " 1538 << printDDI(OrigV, DDI) << "\n"); 1539 } 1540 1541 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1542 DIExpression *Expr, 1543 DebugLoc DbgLoc, 1544 unsigned Order) { 1545 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1546 DIExpression *NewExpr = 1547 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1548 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1549 /*IsVariadic*/ false); 1550 } 1551 1552 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1553 DILocalVariable *Var, 1554 DIExpression *Expr, DebugLoc DbgLoc, 1555 unsigned Order, bool IsVariadic) { 1556 if (Values.empty()) 1557 return true; 1558 1559 // Filter EntryValue locations out early. 1560 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc)) 1561 return true; 1562 1563 SmallVector<SDDbgOperand> LocationOps; 1564 SmallVector<SDNode *> Dependencies; 1565 for (const Value *V : Values) { 1566 // Constant value. 1567 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1568 isa<ConstantPointerNull>(V)) { 1569 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1570 continue; 1571 } 1572 1573 // Look through IntToPtr constants. 1574 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1575 if (CE->getOpcode() == Instruction::IntToPtr) { 1576 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1577 continue; 1578 } 1579 1580 // If the Value is a frame index, we can create a FrameIndex debug value 1581 // without relying on the DAG at all. 1582 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1583 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1584 if (SI != FuncInfo.StaticAllocaMap.end()) { 1585 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1586 continue; 1587 } 1588 } 1589 1590 // Do not use getValue() in here; we don't want to generate code at 1591 // this point if it hasn't been done yet. 1592 SDValue N = NodeMap[V]; 1593 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1594 N = UnusedArgNodeMap[V]; 1595 if (N.getNode()) { 1596 // Only emit func arg dbg value for non-variadic dbg.values for now. 1597 if (!IsVariadic && 1598 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1599 FuncArgumentDbgValueKind::Value, N)) 1600 return true; 1601 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1602 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1603 // describe stack slot locations. 1604 // 1605 // Consider "int x = 0; int *px = &x;". There are two kinds of 1606 // interesting debug values here after optimization: 1607 // 1608 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1609 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1610 // 1611 // Both describe the direct values of their associated variables. 1612 Dependencies.push_back(N.getNode()); 1613 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1614 continue; 1615 } 1616 LocationOps.emplace_back( 1617 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1618 continue; 1619 } 1620 1621 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1622 // Special rules apply for the first dbg.values of parameter variables in a 1623 // function. Identify them by the fact they reference Argument Values, that 1624 // they're parameters, and they are parameters of the current function. We 1625 // need to let them dangle until they get an SDNode. 1626 bool IsParamOfFunc = 1627 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1628 if (IsParamOfFunc) 1629 return false; 1630 1631 // The value is not used in this block yet (or it would have an SDNode). 1632 // We still want the value to appear for the user if possible -- if it has 1633 // an associated VReg, we can refer to that instead. 1634 auto VMI = FuncInfo.ValueMap.find(V); 1635 if (VMI != FuncInfo.ValueMap.end()) { 1636 unsigned Reg = VMI->second; 1637 // If this is a PHI node, it may be split up into several MI PHI nodes 1638 // (in FunctionLoweringInfo::set). 1639 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1640 V->getType(), std::nullopt); 1641 if (RFV.occupiesMultipleRegs()) { 1642 // FIXME: We could potentially support variadic dbg_values here. 1643 if (IsVariadic) 1644 return false; 1645 unsigned Offset = 0; 1646 unsigned BitsToDescribe = 0; 1647 if (auto VarSize = Var->getSizeInBits()) 1648 BitsToDescribe = *VarSize; 1649 if (auto Fragment = Expr->getFragmentInfo()) 1650 BitsToDescribe = Fragment->SizeInBits; 1651 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1652 // Bail out if all bits are described already. 1653 if (Offset >= BitsToDescribe) 1654 break; 1655 // TODO: handle scalable vectors. 1656 unsigned RegisterSize = RegAndSize.second; 1657 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1658 ? BitsToDescribe - Offset 1659 : RegisterSize; 1660 auto FragmentExpr = DIExpression::createFragmentExpression( 1661 Expr, Offset, FragmentSize); 1662 if (!FragmentExpr) 1663 continue; 1664 SDDbgValue *SDV = DAG.getVRegDbgValue( 1665 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1666 DAG.AddDbgValue(SDV, false); 1667 Offset += RegisterSize; 1668 } 1669 return true; 1670 } 1671 // We can use simple vreg locations for variadic dbg_values as well. 1672 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1673 continue; 1674 } 1675 // We failed to create a SDDbgOperand for V. 1676 return false; 1677 } 1678 1679 // We have created a SDDbgOperand for each Value in Values. 1680 // Should use Order instead of SDNodeOrder? 1681 assert(!LocationOps.empty()); 1682 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1683 /*IsIndirect=*/false, DbgLoc, 1684 SDNodeOrder, IsVariadic); 1685 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1686 return true; 1687 } 1688 1689 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1690 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1691 for (auto &Pair : DanglingDebugInfoMap) 1692 for (auto &DDI : Pair.second) 1693 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI); 1694 clearDanglingDebugInfo(); 1695 } 1696 1697 /// getCopyFromRegs - If there was virtual register allocated for the value V 1698 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1699 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1700 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1701 SDValue Result; 1702 1703 if (It != FuncInfo.ValueMap.end()) { 1704 Register InReg = It->second; 1705 1706 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1707 DAG.getDataLayout(), InReg, Ty, 1708 std::nullopt); // This is not an ABI copy. 1709 SDValue Chain = DAG.getEntryNode(); 1710 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1711 V); 1712 resolveDanglingDebugInfo(V, Result); 1713 } 1714 1715 return Result; 1716 } 1717 1718 /// getValue - Return an SDValue for the given Value. 1719 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1720 // If we already have an SDValue for this value, use it. It's important 1721 // to do this first, so that we don't create a CopyFromReg if we already 1722 // have a regular SDValue. 1723 SDValue &N = NodeMap[V]; 1724 if (N.getNode()) return N; 1725 1726 // If there's a virtual register allocated and initialized for this 1727 // value, use it. 1728 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1729 return copyFromReg; 1730 1731 // Otherwise create a new SDValue and remember it. 1732 SDValue Val = getValueImpl(V); 1733 NodeMap[V] = Val; 1734 resolveDanglingDebugInfo(V, Val); 1735 return Val; 1736 } 1737 1738 /// getNonRegisterValue - Return an SDValue for the given Value, but 1739 /// don't look in FuncInfo.ValueMap for a virtual register. 1740 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1741 // If we already have an SDValue for this value, use it. 1742 SDValue &N = NodeMap[V]; 1743 if (N.getNode()) { 1744 if (isIntOrFPConstant(N)) { 1745 // Remove the debug location from the node as the node is about to be used 1746 // in a location which may differ from the original debug location. This 1747 // is relevant to Constant and ConstantFP nodes because they can appear 1748 // as constant expressions inside PHI nodes. 1749 N->setDebugLoc(DebugLoc()); 1750 } 1751 return N; 1752 } 1753 1754 // Otherwise create a new SDValue and remember it. 1755 SDValue Val = getValueImpl(V); 1756 NodeMap[V] = Val; 1757 resolveDanglingDebugInfo(V, Val); 1758 return Val; 1759 } 1760 1761 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1762 /// Create an SDValue for the given value. 1763 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1765 1766 if (const Constant *C = dyn_cast<Constant>(V)) { 1767 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1768 1769 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1770 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1771 1772 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1773 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1774 1775 if (isa<ConstantPointerNull>(C)) { 1776 unsigned AS = V->getType()->getPointerAddressSpace(); 1777 return DAG.getConstant(0, getCurSDLoc(), 1778 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1779 } 1780 1781 if (match(C, m_VScale())) 1782 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1783 1784 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1785 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1786 1787 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1788 return DAG.getUNDEF(VT); 1789 1790 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1791 visit(CE->getOpcode(), *CE); 1792 SDValue N1 = NodeMap[V]; 1793 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1794 return N1; 1795 } 1796 1797 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1798 SmallVector<SDValue, 4> Constants; 1799 for (const Use &U : C->operands()) { 1800 SDNode *Val = getValue(U).getNode(); 1801 // If the operand is an empty aggregate, there are no values. 1802 if (!Val) continue; 1803 // Add each leaf value from the operand to the Constants list 1804 // to form a flattened list of all the values. 1805 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1806 Constants.push_back(SDValue(Val, i)); 1807 } 1808 1809 return DAG.getMergeValues(Constants, getCurSDLoc()); 1810 } 1811 1812 if (const ConstantDataSequential *CDS = 1813 dyn_cast<ConstantDataSequential>(C)) { 1814 SmallVector<SDValue, 4> Ops; 1815 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1816 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1817 // Add each leaf value from the operand to the Constants list 1818 // to form a flattened list of all the values. 1819 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1820 Ops.push_back(SDValue(Val, i)); 1821 } 1822 1823 if (isa<ArrayType>(CDS->getType())) 1824 return DAG.getMergeValues(Ops, getCurSDLoc()); 1825 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1826 } 1827 1828 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1829 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1830 "Unknown struct or array constant!"); 1831 1832 SmallVector<EVT, 4> ValueVTs; 1833 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1834 unsigned NumElts = ValueVTs.size(); 1835 if (NumElts == 0) 1836 return SDValue(); // empty struct 1837 SmallVector<SDValue, 4> Constants(NumElts); 1838 for (unsigned i = 0; i != NumElts; ++i) { 1839 EVT EltVT = ValueVTs[i]; 1840 if (isa<UndefValue>(C)) 1841 Constants[i] = DAG.getUNDEF(EltVT); 1842 else if (EltVT.isFloatingPoint()) 1843 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1844 else 1845 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1846 } 1847 1848 return DAG.getMergeValues(Constants, getCurSDLoc()); 1849 } 1850 1851 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1852 return DAG.getBlockAddress(BA, VT); 1853 1854 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1855 return getValue(Equiv->getGlobalValue()); 1856 1857 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1858 return getValue(NC->getGlobalValue()); 1859 1860 if (VT == MVT::aarch64svcount) { 1861 assert(C->isNullValue() && "Can only zero this target type!"); 1862 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, 1863 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1)); 1864 } 1865 1866 VectorType *VecTy = cast<VectorType>(V->getType()); 1867 1868 // Now that we know the number and type of the elements, get that number of 1869 // elements into the Ops array based on what kind of constant it is. 1870 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1871 SmallVector<SDValue, 16> Ops; 1872 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1873 for (unsigned i = 0; i != NumElements; ++i) 1874 Ops.push_back(getValue(CV->getOperand(i))); 1875 1876 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1877 } 1878 1879 if (isa<ConstantAggregateZero>(C)) { 1880 EVT EltVT = 1881 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1882 1883 SDValue Op; 1884 if (EltVT.isFloatingPoint()) 1885 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1886 else 1887 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1888 1889 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1890 } 1891 1892 llvm_unreachable("Unknown vector constant"); 1893 } 1894 1895 // If this is a static alloca, generate it as the frameindex instead of 1896 // computation. 1897 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1898 DenseMap<const AllocaInst*, int>::iterator SI = 1899 FuncInfo.StaticAllocaMap.find(AI); 1900 if (SI != FuncInfo.StaticAllocaMap.end()) 1901 return DAG.getFrameIndex( 1902 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1903 } 1904 1905 // If this is an instruction which fast-isel has deferred, select it now. 1906 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1907 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1908 1909 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1910 Inst->getType(), std::nullopt); 1911 SDValue Chain = DAG.getEntryNode(); 1912 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1913 } 1914 1915 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1916 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1917 1918 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1919 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1920 1921 llvm_unreachable("Can't get register for value!"); 1922 } 1923 1924 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1925 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1926 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1927 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1928 bool IsSEH = isAsynchronousEHPersonality(Pers); 1929 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1930 if (!IsSEH) 1931 CatchPadMBB->setIsEHScopeEntry(); 1932 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1933 if (IsMSVCCXX || IsCoreCLR) 1934 CatchPadMBB->setIsEHFuncletEntry(); 1935 } 1936 1937 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1938 // Update machine-CFG edge. 1939 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1940 FuncInfo.MBB->addSuccessor(TargetMBB); 1941 TargetMBB->setIsEHCatchretTarget(true); 1942 DAG.getMachineFunction().setHasEHCatchret(true); 1943 1944 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1945 bool IsSEH = isAsynchronousEHPersonality(Pers); 1946 if (IsSEH) { 1947 // If this is not a fall-through branch or optimizations are switched off, 1948 // emit the branch. 1949 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1950 TM.getOptLevel() == CodeGenOptLevel::None) 1951 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1952 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1953 return; 1954 } 1955 1956 // Figure out the funclet membership for the catchret's successor. 1957 // This will be used by the FuncletLayout pass to determine how to order the 1958 // BB's. 1959 // A 'catchret' returns to the outer scope's color. 1960 Value *ParentPad = I.getCatchSwitchParentPad(); 1961 const BasicBlock *SuccessorColor; 1962 if (isa<ConstantTokenNone>(ParentPad)) 1963 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1964 else 1965 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1966 assert(SuccessorColor && "No parent funclet for catchret!"); 1967 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1968 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1969 1970 // Create the terminator node. 1971 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1972 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1973 DAG.getBasicBlock(SuccessorColorMBB)); 1974 DAG.setRoot(Ret); 1975 } 1976 1977 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1978 // Don't emit any special code for the cleanuppad instruction. It just marks 1979 // the start of an EH scope/funclet. 1980 FuncInfo.MBB->setIsEHScopeEntry(); 1981 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1982 if (Pers != EHPersonality::Wasm_CXX) { 1983 FuncInfo.MBB->setIsEHFuncletEntry(); 1984 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1985 } 1986 } 1987 1988 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1989 // not match, it is OK to add only the first unwind destination catchpad to the 1990 // successors, because there will be at least one invoke instruction within the 1991 // catch scope that points to the next unwind destination, if one exists, so 1992 // CFGSort cannot mess up with BB sorting order. 1993 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1994 // call within them, and catchpads only consisting of 'catch (...)' have a 1995 // '__cxa_end_catch' call within them, both of which generate invokes in case 1996 // the next unwind destination exists, i.e., the next unwind destination is not 1997 // the caller.) 1998 // 1999 // Having at most one EH pad successor is also simpler and helps later 2000 // transformations. 2001 // 2002 // For example, 2003 // current: 2004 // invoke void @foo to ... unwind label %catch.dispatch 2005 // catch.dispatch: 2006 // %0 = catchswitch within ... [label %catch.start] unwind label %next 2007 // catch.start: 2008 // ... 2009 // ... in this BB or some other child BB dominated by this BB there will be an 2010 // invoke that points to 'next' BB as an unwind destination 2011 // 2012 // next: ; We don't need to add this to 'current' BB's successor 2013 // ... 2014 static void findWasmUnwindDestinations( 2015 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2016 BranchProbability Prob, 2017 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2018 &UnwindDests) { 2019 while (EHPadBB) { 2020 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2021 if (isa<CleanupPadInst>(Pad)) { 2022 // Stop on cleanup pads. 2023 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2024 UnwindDests.back().first->setIsEHScopeEntry(); 2025 break; 2026 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2027 // Add the catchpad handlers to the possible destinations. We don't 2028 // continue to the unwind destination of the catchswitch for wasm. 2029 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2030 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2031 UnwindDests.back().first->setIsEHScopeEntry(); 2032 } 2033 break; 2034 } else { 2035 continue; 2036 } 2037 } 2038 } 2039 2040 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 2041 /// many places it could ultimately go. In the IR, we have a single unwind 2042 /// destination, but in the machine CFG, we enumerate all the possible blocks. 2043 /// This function skips over imaginary basic blocks that hold catchswitch 2044 /// instructions, and finds all the "real" machine 2045 /// basic block destinations. As those destinations may not be successors of 2046 /// EHPadBB, here we also calculate the edge probability to those destinations. 2047 /// The passed-in Prob is the edge probability to EHPadBB. 2048 static void findUnwindDestinations( 2049 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 2050 BranchProbability Prob, 2051 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2052 &UnwindDests) { 2053 EHPersonality Personality = 2054 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 2055 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2056 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2057 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2058 bool IsSEH = isAsynchronousEHPersonality(Personality); 2059 2060 if (IsWasmCXX) { 2061 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 2062 assert(UnwindDests.size() <= 1 && 2063 "There should be at most one unwind destination for wasm"); 2064 return; 2065 } 2066 2067 while (EHPadBB) { 2068 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2069 BasicBlock *NewEHPadBB = nullptr; 2070 if (isa<LandingPadInst>(Pad)) { 2071 // Stop on landingpads. They are not funclets. 2072 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2073 break; 2074 } else if (isa<CleanupPadInst>(Pad)) { 2075 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2076 // personalities. 2077 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 2078 UnwindDests.back().first->setIsEHScopeEntry(); 2079 UnwindDests.back().first->setIsEHFuncletEntry(); 2080 break; 2081 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2082 // Add the catchpad handlers to the possible destinations. 2083 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2084 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 2085 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2086 if (IsMSVCCXX || IsCoreCLR) 2087 UnwindDests.back().first->setIsEHFuncletEntry(); 2088 if (!IsSEH) 2089 UnwindDests.back().first->setIsEHScopeEntry(); 2090 } 2091 NewEHPadBB = CatchSwitch->getUnwindDest(); 2092 } else { 2093 continue; 2094 } 2095 2096 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2097 if (BPI && NewEHPadBB) 2098 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2099 EHPadBB = NewEHPadBB; 2100 } 2101 } 2102 2103 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 2104 // Update successor info. 2105 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2106 auto UnwindDest = I.getUnwindDest(); 2107 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2108 BranchProbability UnwindDestProb = 2109 (BPI && UnwindDest) 2110 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 2111 : BranchProbability::getZero(); 2112 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 2113 for (auto &UnwindDest : UnwindDests) { 2114 UnwindDest.first->setIsEHPad(); 2115 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 2116 } 2117 FuncInfo.MBB->normalizeSuccProbs(); 2118 2119 // Create the terminator node. 2120 SDValue Ret = 2121 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 2122 DAG.setRoot(Ret); 2123 } 2124 2125 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2126 report_fatal_error("visitCatchSwitch not yet implemented!"); 2127 } 2128 2129 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2130 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2131 auto &DL = DAG.getDataLayout(); 2132 SDValue Chain = getControlRoot(); 2133 SmallVector<ISD::OutputArg, 8> Outs; 2134 SmallVector<SDValue, 8> OutVals; 2135 2136 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2137 // lower 2138 // 2139 // %val = call <ty> @llvm.experimental.deoptimize() 2140 // ret <ty> %val 2141 // 2142 // differently. 2143 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2144 LowerDeoptimizingReturn(); 2145 return; 2146 } 2147 2148 if (!FuncInfo.CanLowerReturn) { 2149 unsigned DemoteReg = FuncInfo.DemoteRegister; 2150 const Function *F = I.getParent()->getParent(); 2151 2152 // Emit a store of the return value through the virtual register. 2153 // Leave Outs empty so that LowerReturn won't try to load return 2154 // registers the usual way. 2155 SmallVector<EVT, 1> PtrValueVTs; 2156 ComputeValueVTs(TLI, DL, 2157 PointerType::get(F->getContext(), 2158 DAG.getDataLayout().getAllocaAddrSpace()), 2159 PtrValueVTs); 2160 2161 SDValue RetPtr = 2162 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2163 SDValue RetOp = getValue(I.getOperand(0)); 2164 2165 SmallVector<EVT, 4> ValueVTs, MemVTs; 2166 SmallVector<uint64_t, 4> Offsets; 2167 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2168 &Offsets, 0); 2169 unsigned NumValues = ValueVTs.size(); 2170 2171 SmallVector<SDValue, 4> Chains(NumValues); 2172 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2173 for (unsigned i = 0; i != NumValues; ++i) { 2174 // An aggregate return value cannot wrap around the address space, so 2175 // offsets to its parts don't wrap either. 2176 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2177 TypeSize::getFixed(Offsets[i])); 2178 2179 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2180 if (MemVTs[i] != ValueVTs[i]) 2181 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2182 Chains[i] = DAG.getStore( 2183 Chain, getCurSDLoc(), Val, 2184 // FIXME: better loc info would be nice. 2185 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2186 commonAlignment(BaseAlign, Offsets[i])); 2187 } 2188 2189 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2190 MVT::Other, Chains); 2191 } else if (I.getNumOperands() != 0) { 2192 SmallVector<EVT, 4> ValueVTs; 2193 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2194 unsigned NumValues = ValueVTs.size(); 2195 if (NumValues) { 2196 SDValue RetOp = getValue(I.getOperand(0)); 2197 2198 const Function *F = I.getParent()->getParent(); 2199 2200 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2201 I.getOperand(0)->getType(), F->getCallingConv(), 2202 /*IsVarArg*/ false, DL); 2203 2204 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2205 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2206 ExtendKind = ISD::SIGN_EXTEND; 2207 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2208 ExtendKind = ISD::ZERO_EXTEND; 2209 2210 LLVMContext &Context = F->getContext(); 2211 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2212 2213 for (unsigned j = 0; j != NumValues; ++j) { 2214 EVT VT = ValueVTs[j]; 2215 2216 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2217 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2218 2219 CallingConv::ID CC = F->getCallingConv(); 2220 2221 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2222 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2223 SmallVector<SDValue, 4> Parts(NumParts); 2224 getCopyToParts(DAG, getCurSDLoc(), 2225 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2226 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2227 2228 // 'inreg' on function refers to return value 2229 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2230 if (RetInReg) 2231 Flags.setInReg(); 2232 2233 if (I.getOperand(0)->getType()->isPointerTy()) { 2234 Flags.setPointer(); 2235 Flags.setPointerAddrSpace( 2236 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2237 } 2238 2239 if (NeedsRegBlock) { 2240 Flags.setInConsecutiveRegs(); 2241 if (j == NumValues - 1) 2242 Flags.setInConsecutiveRegsLast(); 2243 } 2244 2245 // Propagate extension type if any 2246 if (ExtendKind == ISD::SIGN_EXTEND) 2247 Flags.setSExt(); 2248 else if (ExtendKind == ISD::ZERO_EXTEND) 2249 Flags.setZExt(); 2250 2251 for (unsigned i = 0; i < NumParts; ++i) { 2252 Outs.push_back(ISD::OutputArg(Flags, 2253 Parts[i].getValueType().getSimpleVT(), 2254 VT, /*isfixed=*/true, 0, 0)); 2255 OutVals.push_back(Parts[i]); 2256 } 2257 } 2258 } 2259 } 2260 2261 // Push in swifterror virtual register as the last element of Outs. This makes 2262 // sure swifterror virtual register will be returned in the swifterror 2263 // physical register. 2264 const Function *F = I.getParent()->getParent(); 2265 if (TLI.supportSwiftError() && 2266 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2267 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2268 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2269 Flags.setSwiftError(); 2270 Outs.push_back(ISD::OutputArg( 2271 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2272 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2273 // Create SDNode for the swifterror virtual register. 2274 OutVals.push_back( 2275 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2276 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2277 EVT(TLI.getPointerTy(DL)))); 2278 } 2279 2280 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2281 CallingConv::ID CallConv = 2282 DAG.getMachineFunction().getFunction().getCallingConv(); 2283 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2284 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2285 2286 // Verify that the target's LowerReturn behaved as expected. 2287 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2288 "LowerReturn didn't return a valid chain!"); 2289 2290 // Update the DAG with the new chain value resulting from return lowering. 2291 DAG.setRoot(Chain); 2292 } 2293 2294 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2295 /// created for it, emit nodes to copy the value into the virtual 2296 /// registers. 2297 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2298 // Skip empty types 2299 if (V->getType()->isEmptyTy()) 2300 return; 2301 2302 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2303 if (VMI != FuncInfo.ValueMap.end()) { 2304 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2305 "Unused value assigned virtual registers!"); 2306 CopyValueToVirtualRegister(V, VMI->second); 2307 } 2308 } 2309 2310 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2311 /// the current basic block, add it to ValueMap now so that we'll get a 2312 /// CopyTo/FromReg. 2313 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2314 // No need to export constants. 2315 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2316 2317 // Already exported? 2318 if (FuncInfo.isExportedInst(V)) return; 2319 2320 Register Reg = FuncInfo.InitializeRegForValue(V); 2321 CopyValueToVirtualRegister(V, Reg); 2322 } 2323 2324 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2325 const BasicBlock *FromBB) { 2326 // The operands of the setcc have to be in this block. We don't know 2327 // how to export them from some other block. 2328 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2329 // Can export from current BB. 2330 if (VI->getParent() == FromBB) 2331 return true; 2332 2333 // Is already exported, noop. 2334 return FuncInfo.isExportedInst(V); 2335 } 2336 2337 // If this is an argument, we can export it if the BB is the entry block or 2338 // if it is already exported. 2339 if (isa<Argument>(V)) { 2340 if (FromBB->isEntryBlock()) 2341 return true; 2342 2343 // Otherwise, can only export this if it is already exported. 2344 return FuncInfo.isExportedInst(V); 2345 } 2346 2347 // Otherwise, constants can always be exported. 2348 return true; 2349 } 2350 2351 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2352 BranchProbability 2353 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2354 const MachineBasicBlock *Dst) const { 2355 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2356 const BasicBlock *SrcBB = Src->getBasicBlock(); 2357 const BasicBlock *DstBB = Dst->getBasicBlock(); 2358 if (!BPI) { 2359 // If BPI is not available, set the default probability as 1 / N, where N is 2360 // the number of successors. 2361 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2362 return BranchProbability(1, SuccSize); 2363 } 2364 return BPI->getEdgeProbability(SrcBB, DstBB); 2365 } 2366 2367 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2368 MachineBasicBlock *Dst, 2369 BranchProbability Prob) { 2370 if (!FuncInfo.BPI) 2371 Src->addSuccessorWithoutProb(Dst); 2372 else { 2373 if (Prob.isUnknown()) 2374 Prob = getEdgeProbability(Src, Dst); 2375 Src->addSuccessor(Dst, Prob); 2376 } 2377 } 2378 2379 static bool InBlock(const Value *V, const BasicBlock *BB) { 2380 if (const Instruction *I = dyn_cast<Instruction>(V)) 2381 return I->getParent() == BB; 2382 return true; 2383 } 2384 2385 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2386 /// This function emits a branch and is used at the leaves of an OR or an 2387 /// AND operator tree. 2388 void 2389 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2390 MachineBasicBlock *TBB, 2391 MachineBasicBlock *FBB, 2392 MachineBasicBlock *CurBB, 2393 MachineBasicBlock *SwitchBB, 2394 BranchProbability TProb, 2395 BranchProbability FProb, 2396 bool InvertCond) { 2397 const BasicBlock *BB = CurBB->getBasicBlock(); 2398 2399 // If the leaf of the tree is a comparison, merge the condition into 2400 // the caseblock. 2401 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2402 // The operands of the cmp have to be in this block. We don't know 2403 // how to export them from some other block. If this is the first block 2404 // of the sequence, no exporting is needed. 2405 if (CurBB == SwitchBB || 2406 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2407 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2408 ISD::CondCode Condition; 2409 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2410 ICmpInst::Predicate Pred = 2411 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2412 Condition = getICmpCondCode(Pred); 2413 } else { 2414 const FCmpInst *FC = cast<FCmpInst>(Cond); 2415 FCmpInst::Predicate Pred = 2416 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2417 Condition = getFCmpCondCode(Pred); 2418 if (TM.Options.NoNaNsFPMath) 2419 Condition = getFCmpCodeWithoutNaN(Condition); 2420 } 2421 2422 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2423 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2424 SL->SwitchCases.push_back(CB); 2425 return; 2426 } 2427 } 2428 2429 // Create a CaseBlock record representing this branch. 2430 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2431 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2432 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2433 SL->SwitchCases.push_back(CB); 2434 } 2435 2436 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2437 MachineBasicBlock *TBB, 2438 MachineBasicBlock *FBB, 2439 MachineBasicBlock *CurBB, 2440 MachineBasicBlock *SwitchBB, 2441 Instruction::BinaryOps Opc, 2442 BranchProbability TProb, 2443 BranchProbability FProb, 2444 bool InvertCond) { 2445 // Skip over not part of the tree and remember to invert op and operands at 2446 // next level. 2447 Value *NotCond; 2448 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2449 InBlock(NotCond, CurBB->getBasicBlock())) { 2450 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2451 !InvertCond); 2452 return; 2453 } 2454 2455 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2456 const Value *BOpOp0, *BOpOp1; 2457 // Compute the effective opcode for Cond, taking into account whether it needs 2458 // to be inverted, e.g. 2459 // and (not (or A, B)), C 2460 // gets lowered as 2461 // and (and (not A, not B), C) 2462 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2463 if (BOp) { 2464 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2465 ? Instruction::And 2466 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2467 ? Instruction::Or 2468 : (Instruction::BinaryOps)0); 2469 if (InvertCond) { 2470 if (BOpc == Instruction::And) 2471 BOpc = Instruction::Or; 2472 else if (BOpc == Instruction::Or) 2473 BOpc = Instruction::And; 2474 } 2475 } 2476 2477 // If this node is not part of the or/and tree, emit it as a branch. 2478 // Note that all nodes in the tree should have same opcode. 2479 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2480 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2481 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2482 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2483 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2484 TProb, FProb, InvertCond); 2485 return; 2486 } 2487 2488 // Create TmpBB after CurBB. 2489 MachineFunction::iterator BBI(CurBB); 2490 MachineFunction &MF = DAG.getMachineFunction(); 2491 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2492 CurBB->getParent()->insert(++BBI, TmpBB); 2493 2494 if (Opc == Instruction::Or) { 2495 // Codegen X | Y as: 2496 // BB1: 2497 // jmp_if_X TBB 2498 // jmp TmpBB 2499 // TmpBB: 2500 // jmp_if_Y TBB 2501 // jmp FBB 2502 // 2503 2504 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2505 // The requirement is that 2506 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2507 // = TrueProb for original BB. 2508 // Assuming the original probabilities are A and B, one choice is to set 2509 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2510 // A/(1+B) and 2B/(1+B). This choice assumes that 2511 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2512 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2513 // TmpBB, but the math is more complicated. 2514 2515 auto NewTrueProb = TProb / 2; 2516 auto NewFalseProb = TProb / 2 + FProb; 2517 // Emit the LHS condition. 2518 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2519 NewFalseProb, InvertCond); 2520 2521 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2522 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2523 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2524 // Emit the RHS condition into TmpBB. 2525 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2526 Probs[1], InvertCond); 2527 } else { 2528 assert(Opc == Instruction::And && "Unknown merge op!"); 2529 // Codegen X & Y as: 2530 // BB1: 2531 // jmp_if_X TmpBB 2532 // jmp FBB 2533 // TmpBB: 2534 // jmp_if_Y TBB 2535 // jmp FBB 2536 // 2537 // This requires creation of TmpBB after CurBB. 2538 2539 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2540 // The requirement is that 2541 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2542 // = FalseProb for original BB. 2543 // Assuming the original probabilities are A and B, one choice is to set 2544 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2545 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2546 // TrueProb for BB1 * FalseProb for TmpBB. 2547 2548 auto NewTrueProb = TProb + FProb / 2; 2549 auto NewFalseProb = FProb / 2; 2550 // Emit the LHS condition. 2551 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2552 NewFalseProb, InvertCond); 2553 2554 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2555 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2556 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2557 // Emit the RHS condition into TmpBB. 2558 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2559 Probs[1], InvertCond); 2560 } 2561 } 2562 2563 /// If the set of cases should be emitted as a series of branches, return true. 2564 /// If we should emit this as a bunch of and/or'd together conditions, return 2565 /// false. 2566 bool 2567 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2568 if (Cases.size() != 2) return true; 2569 2570 // If this is two comparisons of the same values or'd or and'd together, they 2571 // will get folded into a single comparison, so don't emit two blocks. 2572 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2573 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2574 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2575 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2576 return false; 2577 } 2578 2579 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2580 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2581 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2582 Cases[0].CC == Cases[1].CC && 2583 isa<Constant>(Cases[0].CmpRHS) && 2584 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2585 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2586 return false; 2587 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2588 return false; 2589 } 2590 2591 return true; 2592 } 2593 2594 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2595 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2596 2597 // Update machine-CFG edges. 2598 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2599 2600 if (I.isUnconditional()) { 2601 // Update machine-CFG edges. 2602 BrMBB->addSuccessor(Succ0MBB); 2603 2604 // If this is not a fall-through branch or optimizations are switched off, 2605 // emit the branch. 2606 if (Succ0MBB != NextBlock(BrMBB) || 2607 TM.getOptLevel() == CodeGenOptLevel::None) { 2608 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 2609 getControlRoot(), DAG.getBasicBlock(Succ0MBB)); 2610 setValue(&I, Br); 2611 DAG.setRoot(Br); 2612 } 2613 2614 return; 2615 } 2616 2617 // If this condition is one of the special cases we handle, do special stuff 2618 // now. 2619 const Value *CondVal = I.getCondition(); 2620 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2621 2622 // If this is a series of conditions that are or'd or and'd together, emit 2623 // this as a sequence of branches instead of setcc's with and/or operations. 2624 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2625 // unpredictable branches, and vector extracts because those jumps are likely 2626 // expensive for any target), this should improve performance. 2627 // For example, instead of something like: 2628 // cmp A, B 2629 // C = seteq 2630 // cmp D, E 2631 // F = setle 2632 // or C, F 2633 // jnz foo 2634 // Emit: 2635 // cmp A, B 2636 // je foo 2637 // cmp D, E 2638 // jle foo 2639 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2640 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2641 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2642 Value *Vec; 2643 const Value *BOp0, *BOp1; 2644 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2645 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2646 Opcode = Instruction::And; 2647 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2648 Opcode = Instruction::Or; 2649 2650 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2651 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2652 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2653 getEdgeProbability(BrMBB, Succ0MBB), 2654 getEdgeProbability(BrMBB, Succ1MBB), 2655 /*InvertCond=*/false); 2656 // If the compares in later blocks need to use values not currently 2657 // exported from this block, export them now. This block should always 2658 // be the first entry. 2659 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2660 2661 // Allow some cases to be rejected. 2662 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2663 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2664 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2665 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2666 } 2667 2668 // Emit the branch for this block. 2669 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2670 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2671 return; 2672 } 2673 2674 // Okay, we decided not to do this, remove any inserted MBB's and clear 2675 // SwitchCases. 2676 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2677 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2678 2679 SL->SwitchCases.clear(); 2680 } 2681 } 2682 2683 // Create a CaseBlock record representing this branch. 2684 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2685 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2686 2687 // Use visitSwitchCase to actually insert the fast branch sequence for this 2688 // cond branch. 2689 visitSwitchCase(CB, BrMBB); 2690 } 2691 2692 /// visitSwitchCase - Emits the necessary code to represent a single node in 2693 /// the binary search tree resulting from lowering a switch instruction. 2694 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2695 MachineBasicBlock *SwitchBB) { 2696 SDValue Cond; 2697 SDValue CondLHS = getValue(CB.CmpLHS); 2698 SDLoc dl = CB.DL; 2699 2700 if (CB.CC == ISD::SETTRUE) { 2701 // Branch or fall through to TrueBB. 2702 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2703 SwitchBB->normalizeSuccProbs(); 2704 if (CB.TrueBB != NextBlock(SwitchBB)) { 2705 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2706 DAG.getBasicBlock(CB.TrueBB))); 2707 } 2708 return; 2709 } 2710 2711 auto &TLI = DAG.getTargetLoweringInfo(); 2712 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2713 2714 // Build the setcc now. 2715 if (!CB.CmpMHS) { 2716 // Fold "(X == true)" to X and "(X == false)" to !X to 2717 // handle common cases produced by branch lowering. 2718 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2719 CB.CC == ISD::SETEQ) 2720 Cond = CondLHS; 2721 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2722 CB.CC == ISD::SETEQ) { 2723 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2724 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2725 } else { 2726 SDValue CondRHS = getValue(CB.CmpRHS); 2727 2728 // If a pointer's DAG type is larger than its memory type then the DAG 2729 // values are zero-extended. This breaks signed comparisons so truncate 2730 // back to the underlying type before doing the compare. 2731 if (CondLHS.getValueType() != MemVT) { 2732 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2733 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2734 } 2735 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2736 } 2737 } else { 2738 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2739 2740 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2741 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2742 2743 SDValue CmpOp = getValue(CB.CmpMHS); 2744 EVT VT = CmpOp.getValueType(); 2745 2746 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2747 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2748 ISD::SETLE); 2749 } else { 2750 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2751 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2752 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2753 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2754 } 2755 } 2756 2757 // Update successor info 2758 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2759 // TrueBB and FalseBB are always different unless the incoming IR is 2760 // degenerate. This only happens when running llc on weird IR. 2761 if (CB.TrueBB != CB.FalseBB) 2762 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2763 SwitchBB->normalizeSuccProbs(); 2764 2765 // If the lhs block is the next block, invert the condition so that we can 2766 // fall through to the lhs instead of the rhs block. 2767 if (CB.TrueBB == NextBlock(SwitchBB)) { 2768 std::swap(CB.TrueBB, CB.FalseBB); 2769 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2770 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2771 } 2772 2773 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2774 MVT::Other, getControlRoot(), Cond, 2775 DAG.getBasicBlock(CB.TrueBB)); 2776 2777 setValue(CurInst, BrCond); 2778 2779 // Insert the false branch. Do this even if it's a fall through branch, 2780 // this makes it easier to do DAG optimizations which require inverting 2781 // the branch condition. 2782 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2783 DAG.getBasicBlock(CB.FalseBB)); 2784 2785 DAG.setRoot(BrCond); 2786 } 2787 2788 /// visitJumpTable - Emit JumpTable node in the current MBB 2789 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2790 // Emit the code for the jump table 2791 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2792 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2793 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2794 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy); 2795 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2796 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other, 2797 Index.getValue(1), Table, Index); 2798 DAG.setRoot(BrJumpTable); 2799 } 2800 2801 /// visitJumpTableHeader - This function emits necessary code to produce index 2802 /// in the JumpTable from switch case. 2803 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2804 JumpTableHeader &JTH, 2805 MachineBasicBlock *SwitchBB) { 2806 assert(JT.SL && "Should set SDLoc for SelectionDAG!"); 2807 const SDLoc &dl = *JT.SL; 2808 2809 // Subtract the lowest switch case value from the value being switched on. 2810 SDValue SwitchOp = getValue(JTH.SValue); 2811 EVT VT = SwitchOp.getValueType(); 2812 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2813 DAG.getConstant(JTH.First, dl, VT)); 2814 2815 // The SDNode we just created, which holds the value being switched on minus 2816 // the smallest case value, needs to be copied to a virtual register so it 2817 // can be used as an index into the jump table in a subsequent basic block. 2818 // This value may be smaller or larger than the target's pointer type, and 2819 // therefore require extension or truncating. 2820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2821 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2822 2823 unsigned JumpTableReg = 2824 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2825 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2826 JumpTableReg, SwitchOp); 2827 JT.Reg = JumpTableReg; 2828 2829 if (!JTH.FallthroughUnreachable) { 2830 // Emit the range check for the jump table, and branch to the default block 2831 // for the switch statement if the value being switched on exceeds the 2832 // largest case in the switch. 2833 SDValue CMP = DAG.getSetCC( 2834 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2835 Sub.getValueType()), 2836 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2837 2838 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2839 MVT::Other, CopyTo, CMP, 2840 DAG.getBasicBlock(JT.Default)); 2841 2842 // Avoid emitting unnecessary branches to the next block. 2843 if (JT.MBB != NextBlock(SwitchBB)) 2844 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2845 DAG.getBasicBlock(JT.MBB)); 2846 2847 DAG.setRoot(BrCond); 2848 } else { 2849 // Avoid emitting unnecessary branches to the next block. 2850 if (JT.MBB != NextBlock(SwitchBB)) 2851 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2852 DAG.getBasicBlock(JT.MBB))); 2853 else 2854 DAG.setRoot(CopyTo); 2855 } 2856 } 2857 2858 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2859 /// variable if there exists one. 2860 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2861 SDValue &Chain) { 2862 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2863 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2864 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2865 MachineFunction &MF = DAG.getMachineFunction(); 2866 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2867 MachineSDNode *Node = 2868 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2869 if (Global) { 2870 MachinePointerInfo MPInfo(Global); 2871 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2872 MachineMemOperand::MODereferenceable; 2873 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2874 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2875 DAG.setNodeMemRefs(Node, {MemRef}); 2876 } 2877 if (PtrTy != PtrMemTy) 2878 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2879 return SDValue(Node, 0); 2880 } 2881 2882 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2883 /// tail spliced into a stack protector check success bb. 2884 /// 2885 /// For a high level explanation of how this fits into the stack protector 2886 /// generation see the comment on the declaration of class 2887 /// StackProtectorDescriptor. 2888 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2889 MachineBasicBlock *ParentBB) { 2890 2891 // First create the loads to the guard/stack slot for the comparison. 2892 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2893 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2894 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2895 2896 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2897 int FI = MFI.getStackProtectorIndex(); 2898 2899 SDValue Guard; 2900 SDLoc dl = getCurSDLoc(); 2901 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2902 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2903 Align Align = 2904 DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0)); 2905 2906 // Generate code to load the content of the guard slot. 2907 SDValue GuardVal = DAG.getLoad( 2908 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2909 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2910 MachineMemOperand::MOVolatile); 2911 2912 if (TLI.useStackGuardXorFP()) 2913 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2914 2915 // Retrieve guard check function, nullptr if instrumentation is inlined. 2916 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2917 // The target provides a guard check function to validate the guard value. 2918 // Generate a call to that function with the content of the guard slot as 2919 // argument. 2920 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2921 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2922 2923 TargetLowering::ArgListTy Args; 2924 TargetLowering::ArgListEntry Entry; 2925 Entry.Node = GuardVal; 2926 Entry.Ty = FnTy->getParamType(0); 2927 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2928 Entry.IsInReg = true; 2929 Args.push_back(Entry); 2930 2931 TargetLowering::CallLoweringInfo CLI(DAG); 2932 CLI.setDebugLoc(getCurSDLoc()) 2933 .setChain(DAG.getEntryNode()) 2934 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2935 getValue(GuardCheckFn), std::move(Args)); 2936 2937 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2938 DAG.setRoot(Result.second); 2939 return; 2940 } 2941 2942 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2943 // Otherwise, emit a volatile load to retrieve the stack guard value. 2944 SDValue Chain = DAG.getEntryNode(); 2945 if (TLI.useLoadStackGuardNode()) { 2946 Guard = getLoadStackGuard(DAG, dl, Chain); 2947 } else { 2948 const Value *IRGuard = TLI.getSDagStackGuard(M); 2949 SDValue GuardPtr = getValue(IRGuard); 2950 2951 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2952 MachinePointerInfo(IRGuard, 0), Align, 2953 MachineMemOperand::MOVolatile); 2954 } 2955 2956 // Perform the comparison via a getsetcc. 2957 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2958 *DAG.getContext(), 2959 Guard.getValueType()), 2960 Guard, GuardVal, ISD::SETNE); 2961 2962 // If the guard/stackslot do not equal, branch to failure MBB. 2963 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2964 MVT::Other, GuardVal.getOperand(0), 2965 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2966 // Otherwise branch to success MBB. 2967 SDValue Br = DAG.getNode(ISD::BR, dl, 2968 MVT::Other, BrCond, 2969 DAG.getBasicBlock(SPD.getSuccessMBB())); 2970 2971 DAG.setRoot(Br); 2972 } 2973 2974 /// Codegen the failure basic block for a stack protector check. 2975 /// 2976 /// A failure stack protector machine basic block consists simply of a call to 2977 /// __stack_chk_fail(). 2978 /// 2979 /// For a high level explanation of how this fits into the stack protector 2980 /// generation see the comment on the declaration of class 2981 /// StackProtectorDescriptor. 2982 void 2983 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2984 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2985 TargetLowering::MakeLibCallOptions CallOptions; 2986 CallOptions.setDiscardResult(true); 2987 SDValue Chain = 2988 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2989 std::nullopt, CallOptions, getCurSDLoc()) 2990 .second; 2991 // On PS4/PS5, the "return address" must still be within the calling 2992 // function, even if it's at the very end, so emit an explicit TRAP here. 2993 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2994 if (TM.getTargetTriple().isPS()) 2995 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2996 // WebAssembly needs an unreachable instruction after a non-returning call, 2997 // because the function return type can be different from __stack_chk_fail's 2998 // return type (void). 2999 if (TM.getTargetTriple().isWasm()) 3000 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 3001 3002 DAG.setRoot(Chain); 3003 } 3004 3005 /// visitBitTestHeader - This function emits necessary code to produce value 3006 /// suitable for "bit tests" 3007 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 3008 MachineBasicBlock *SwitchBB) { 3009 SDLoc dl = getCurSDLoc(); 3010 3011 // Subtract the minimum value. 3012 SDValue SwitchOp = getValue(B.SValue); 3013 EVT VT = SwitchOp.getValueType(); 3014 SDValue RangeSub = 3015 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 3016 3017 // Determine the type of the test operands. 3018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3019 bool UsePtrType = false; 3020 if (!TLI.isTypeLegal(VT)) { 3021 UsePtrType = true; 3022 } else { 3023 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 3024 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 3025 // Switch table case range are encoded into series of masks. 3026 // Just use pointer type, it's guaranteed to fit. 3027 UsePtrType = true; 3028 break; 3029 } 3030 } 3031 SDValue Sub = RangeSub; 3032 if (UsePtrType) { 3033 VT = TLI.getPointerTy(DAG.getDataLayout()); 3034 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 3035 } 3036 3037 B.RegVT = VT.getSimpleVT(); 3038 B.Reg = FuncInfo.CreateReg(B.RegVT); 3039 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 3040 3041 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 3042 3043 if (!B.FallthroughUnreachable) 3044 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 3045 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 3046 SwitchBB->normalizeSuccProbs(); 3047 3048 SDValue Root = CopyTo; 3049 if (!B.FallthroughUnreachable) { 3050 // Conditional branch to the default block. 3051 SDValue RangeCmp = DAG.getSetCC(dl, 3052 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 3053 RangeSub.getValueType()), 3054 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 3055 ISD::SETUGT); 3056 3057 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 3058 DAG.getBasicBlock(B.Default)); 3059 } 3060 3061 // Avoid emitting unnecessary branches to the next block. 3062 if (MBB != NextBlock(SwitchBB)) 3063 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 3064 3065 DAG.setRoot(Root); 3066 } 3067 3068 /// visitBitTestCase - this function produces one "bit test" 3069 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 3070 MachineBasicBlock* NextMBB, 3071 BranchProbability BranchProbToNext, 3072 unsigned Reg, 3073 BitTestCase &B, 3074 MachineBasicBlock *SwitchBB) { 3075 SDLoc dl = getCurSDLoc(); 3076 MVT VT = BB.RegVT; 3077 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 3078 SDValue Cmp; 3079 unsigned PopCount = llvm::popcount(B.Mask); 3080 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3081 if (PopCount == 1) { 3082 // Testing for a single bit; just compare the shift count with what it 3083 // would need to be to shift a 1 bit in that position. 3084 Cmp = DAG.getSetCC( 3085 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3086 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 3087 ISD::SETEQ); 3088 } else if (PopCount == BB.Range) { 3089 // There is only one zero bit in the range, test for it directly. 3090 Cmp = DAG.getSetCC( 3091 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3092 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 3093 } else { 3094 // Make desired shift 3095 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 3096 DAG.getConstant(1, dl, VT), ShiftOp); 3097 3098 // Emit bit tests and jumps 3099 SDValue AndOp = DAG.getNode(ISD::AND, dl, 3100 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 3101 Cmp = DAG.getSetCC( 3102 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 3103 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 3104 } 3105 3106 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 3107 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 3108 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 3109 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 3110 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 3111 // one as they are relative probabilities (and thus work more like weights), 3112 // and hence we need to normalize them to let the sum of them become one. 3113 SwitchBB->normalizeSuccProbs(); 3114 3115 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 3116 MVT::Other, getControlRoot(), 3117 Cmp, DAG.getBasicBlock(B.TargetBB)); 3118 3119 // Avoid emitting unnecessary branches to the next block. 3120 if (NextMBB != NextBlock(SwitchBB)) 3121 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 3122 DAG.getBasicBlock(NextMBB)); 3123 3124 DAG.setRoot(BrAnd); 3125 } 3126 3127 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3128 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3129 3130 // Retrieve successors. Look through artificial IR level blocks like 3131 // catchswitch for successors. 3132 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3133 const BasicBlock *EHPadBB = I.getSuccessor(1); 3134 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3135 3136 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3137 // have to do anything here to lower funclet bundles. 3138 assert(!I.hasOperandBundlesOtherThan( 3139 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3140 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3141 LLVMContext::OB_cfguardtarget, 3142 LLVMContext::OB_clang_arc_attachedcall}) && 3143 "Cannot lower invokes with arbitrary operand bundles yet!"); 3144 3145 const Value *Callee(I.getCalledOperand()); 3146 const Function *Fn = dyn_cast<Function>(Callee); 3147 if (isa<InlineAsm>(Callee)) 3148 visitInlineAsm(I, EHPadBB); 3149 else if (Fn && Fn->isIntrinsic()) { 3150 switch (Fn->getIntrinsicID()) { 3151 default: 3152 llvm_unreachable("Cannot invoke this intrinsic"); 3153 case Intrinsic::donothing: 3154 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3155 case Intrinsic::seh_try_begin: 3156 case Intrinsic::seh_scope_begin: 3157 case Intrinsic::seh_try_end: 3158 case Intrinsic::seh_scope_end: 3159 if (EHPadMBB) 3160 // a block referenced by EH table 3161 // so dtor-funclet not removed by opts 3162 EHPadMBB->setMachineBlockAddressTaken(); 3163 break; 3164 case Intrinsic::experimental_patchpoint_void: 3165 case Intrinsic::experimental_patchpoint_i64: 3166 visitPatchpoint(I, EHPadBB); 3167 break; 3168 case Intrinsic::experimental_gc_statepoint: 3169 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3170 break; 3171 case Intrinsic::wasm_rethrow: { 3172 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3173 // special because it can be invoked, so we manually lower it to a DAG 3174 // node here. 3175 SmallVector<SDValue, 8> Ops; 3176 Ops.push_back(getRoot()); // inchain 3177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3178 Ops.push_back( 3179 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3180 TLI.getPointerTy(DAG.getDataLayout()))); 3181 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3182 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3183 break; 3184 } 3185 } 3186 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3187 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3188 // Eventually we will support lowering the @llvm.experimental.deoptimize 3189 // intrinsic, and right now there are no plans to support other intrinsics 3190 // with deopt state. 3191 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3192 } else { 3193 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3194 } 3195 3196 // If the value of the invoke is used outside of its defining block, make it 3197 // available as a virtual register. 3198 // We already took care of the exported value for the statepoint instruction 3199 // during call to the LowerStatepoint. 3200 if (!isa<GCStatepointInst>(I)) { 3201 CopyToExportRegsIfNeeded(&I); 3202 } 3203 3204 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3205 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3206 BranchProbability EHPadBBProb = 3207 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3208 : BranchProbability::getZero(); 3209 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3210 3211 // Update successor info. 3212 addSuccessorWithProb(InvokeMBB, Return); 3213 for (auto &UnwindDest : UnwindDests) { 3214 UnwindDest.first->setIsEHPad(); 3215 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3216 } 3217 InvokeMBB->normalizeSuccProbs(); 3218 3219 // Drop into normal successor. 3220 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3221 DAG.getBasicBlock(Return))); 3222 } 3223 3224 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3225 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3226 3227 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3228 // have to do anything here to lower funclet bundles. 3229 assert(!I.hasOperandBundlesOtherThan( 3230 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3231 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3232 3233 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3234 visitInlineAsm(I); 3235 CopyToExportRegsIfNeeded(&I); 3236 3237 // Retrieve successors. 3238 SmallPtrSet<BasicBlock *, 8> Dests; 3239 Dests.insert(I.getDefaultDest()); 3240 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3241 3242 // Update successor info. 3243 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3244 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3245 BasicBlock *Dest = I.getIndirectDest(i); 3246 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3247 Target->setIsInlineAsmBrIndirectTarget(); 3248 Target->setMachineBlockAddressTaken(); 3249 Target->setLabelMustBeEmitted(); 3250 // Don't add duplicate machine successors. 3251 if (Dests.insert(Dest).second) 3252 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3253 } 3254 CallBrMBB->normalizeSuccProbs(); 3255 3256 // Drop into default successor. 3257 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3258 MVT::Other, getControlRoot(), 3259 DAG.getBasicBlock(Return))); 3260 } 3261 3262 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3263 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3264 } 3265 3266 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3267 assert(FuncInfo.MBB->isEHPad() && 3268 "Call to landingpad not in landing pad!"); 3269 3270 // If there aren't registers to copy the values into (e.g., during SjLj 3271 // exceptions), then don't bother to create these DAG nodes. 3272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3273 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3274 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3275 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3276 return; 3277 3278 // If landingpad's return type is token type, we don't create DAG nodes 3279 // for its exception pointer and selector value. The extraction of exception 3280 // pointer or selector value from token type landingpads is not currently 3281 // supported. 3282 if (LP.getType()->isTokenTy()) 3283 return; 3284 3285 SmallVector<EVT, 2> ValueVTs; 3286 SDLoc dl = getCurSDLoc(); 3287 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3288 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3289 3290 // Get the two live-in registers as SDValues. The physregs have already been 3291 // copied into virtual registers. 3292 SDValue Ops[2]; 3293 if (FuncInfo.ExceptionPointerVirtReg) { 3294 Ops[0] = DAG.getZExtOrTrunc( 3295 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3296 FuncInfo.ExceptionPointerVirtReg, 3297 TLI.getPointerTy(DAG.getDataLayout())), 3298 dl, ValueVTs[0]); 3299 } else { 3300 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3301 } 3302 Ops[1] = DAG.getZExtOrTrunc( 3303 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3304 FuncInfo.ExceptionSelectorVirtReg, 3305 TLI.getPointerTy(DAG.getDataLayout())), 3306 dl, ValueVTs[1]); 3307 3308 // Merge into one. 3309 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3310 DAG.getVTList(ValueVTs), Ops); 3311 setValue(&LP, Res); 3312 } 3313 3314 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3315 MachineBasicBlock *Last) { 3316 // Update JTCases. 3317 for (JumpTableBlock &JTB : SL->JTCases) 3318 if (JTB.first.HeaderBB == First) 3319 JTB.first.HeaderBB = Last; 3320 3321 // Update BitTestCases. 3322 for (BitTestBlock &BTB : SL->BitTestCases) 3323 if (BTB.Parent == First) 3324 BTB.Parent = Last; 3325 } 3326 3327 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3328 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3329 3330 // Update machine-CFG edges with unique successors. 3331 SmallSet<BasicBlock*, 32> Done; 3332 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3333 BasicBlock *BB = I.getSuccessor(i); 3334 bool Inserted = Done.insert(BB).second; 3335 if (!Inserted) 3336 continue; 3337 3338 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3339 addSuccessorWithProb(IndirectBrMBB, Succ); 3340 } 3341 IndirectBrMBB->normalizeSuccProbs(); 3342 3343 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3344 MVT::Other, getControlRoot(), 3345 getValue(I.getAddress()))); 3346 } 3347 3348 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3349 if (!DAG.getTarget().Options.TrapUnreachable) 3350 return; 3351 3352 // We may be able to ignore unreachable behind a noreturn call. 3353 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3354 if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) { 3355 if (Call->doesNotReturn()) 3356 return; 3357 } 3358 } 3359 3360 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3361 } 3362 3363 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3364 SDNodeFlags Flags; 3365 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3366 Flags.copyFMF(*FPOp); 3367 3368 SDValue Op = getValue(I.getOperand(0)); 3369 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3370 Op, Flags); 3371 setValue(&I, UnNodeValue); 3372 } 3373 3374 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3375 SDNodeFlags Flags; 3376 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3377 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3378 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3379 } 3380 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3381 Flags.setExact(ExactOp->isExact()); 3382 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I)) 3383 Flags.setDisjoint(DisjointOp->isDisjoint()); 3384 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3385 Flags.copyFMF(*FPOp); 3386 3387 SDValue Op1 = getValue(I.getOperand(0)); 3388 SDValue Op2 = getValue(I.getOperand(1)); 3389 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3390 Op1, Op2, Flags); 3391 setValue(&I, BinNodeValue); 3392 } 3393 3394 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3395 SDValue Op1 = getValue(I.getOperand(0)); 3396 SDValue Op2 = getValue(I.getOperand(1)); 3397 3398 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3399 Op1.getValueType(), DAG.getDataLayout()); 3400 3401 // Coerce the shift amount to the right type if we can. This exposes the 3402 // truncate or zext to optimization early. 3403 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3404 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3405 "Unexpected shift type"); 3406 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3407 } 3408 3409 bool nuw = false; 3410 bool nsw = false; 3411 bool exact = false; 3412 3413 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3414 3415 if (const OverflowingBinaryOperator *OFBinOp = 3416 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3417 nuw = OFBinOp->hasNoUnsignedWrap(); 3418 nsw = OFBinOp->hasNoSignedWrap(); 3419 } 3420 if (const PossiblyExactOperator *ExactOp = 3421 dyn_cast<const PossiblyExactOperator>(&I)) 3422 exact = ExactOp->isExact(); 3423 } 3424 SDNodeFlags Flags; 3425 Flags.setExact(exact); 3426 Flags.setNoSignedWrap(nsw); 3427 Flags.setNoUnsignedWrap(nuw); 3428 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3429 Flags); 3430 setValue(&I, Res); 3431 } 3432 3433 void SelectionDAGBuilder::visitSDiv(const User &I) { 3434 SDValue Op1 = getValue(I.getOperand(0)); 3435 SDValue Op2 = getValue(I.getOperand(1)); 3436 3437 SDNodeFlags Flags; 3438 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3439 cast<PossiblyExactOperator>(&I)->isExact()); 3440 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3441 Op2, Flags)); 3442 } 3443 3444 void SelectionDAGBuilder::visitICmp(const User &I) { 3445 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3446 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3447 predicate = IC->getPredicate(); 3448 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3449 predicate = ICmpInst::Predicate(IC->getPredicate()); 3450 SDValue Op1 = getValue(I.getOperand(0)); 3451 SDValue Op2 = getValue(I.getOperand(1)); 3452 ISD::CondCode Opcode = getICmpCondCode(predicate); 3453 3454 auto &TLI = DAG.getTargetLoweringInfo(); 3455 EVT MemVT = 3456 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3457 3458 // If a pointer's DAG type is larger than its memory type then the DAG values 3459 // are zero-extended. This breaks signed comparisons so truncate back to the 3460 // underlying type before doing the compare. 3461 if (Op1.getValueType() != MemVT) { 3462 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3463 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3464 } 3465 3466 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3467 I.getType()); 3468 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3469 } 3470 3471 void SelectionDAGBuilder::visitFCmp(const User &I) { 3472 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3473 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3474 predicate = FC->getPredicate(); 3475 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3476 predicate = FCmpInst::Predicate(FC->getPredicate()); 3477 SDValue Op1 = getValue(I.getOperand(0)); 3478 SDValue Op2 = getValue(I.getOperand(1)); 3479 3480 ISD::CondCode Condition = getFCmpCondCode(predicate); 3481 auto *FPMO = cast<FPMathOperator>(&I); 3482 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3483 Condition = getFCmpCodeWithoutNaN(Condition); 3484 3485 SDNodeFlags Flags; 3486 Flags.copyFMF(*FPMO); 3487 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3488 3489 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3490 I.getType()); 3491 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3492 } 3493 3494 // Check if the condition of the select has one use or two users that are both 3495 // selects with the same condition. 3496 static bool hasOnlySelectUsers(const Value *Cond) { 3497 return llvm::all_of(Cond->users(), [](const Value *V) { 3498 return isa<SelectInst>(V); 3499 }); 3500 } 3501 3502 void SelectionDAGBuilder::visitSelect(const User &I) { 3503 SmallVector<EVT, 4> ValueVTs; 3504 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3505 ValueVTs); 3506 unsigned NumValues = ValueVTs.size(); 3507 if (NumValues == 0) return; 3508 3509 SmallVector<SDValue, 4> Values(NumValues); 3510 SDValue Cond = getValue(I.getOperand(0)); 3511 SDValue LHSVal = getValue(I.getOperand(1)); 3512 SDValue RHSVal = getValue(I.getOperand(2)); 3513 SmallVector<SDValue, 1> BaseOps(1, Cond); 3514 ISD::NodeType OpCode = 3515 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3516 3517 bool IsUnaryAbs = false; 3518 bool Negate = false; 3519 3520 SDNodeFlags Flags; 3521 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3522 Flags.copyFMF(*FPOp); 3523 3524 Flags.setUnpredictable( 3525 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3526 3527 // Min/max matching is only viable if all output VTs are the same. 3528 if (all_equal(ValueVTs)) { 3529 EVT VT = ValueVTs[0]; 3530 LLVMContext &Ctx = *DAG.getContext(); 3531 auto &TLI = DAG.getTargetLoweringInfo(); 3532 3533 // We care about the legality of the operation after it has been type 3534 // legalized. 3535 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3536 VT = TLI.getTypeToTransformTo(Ctx, VT); 3537 3538 // If the vselect is legal, assume we want to leave this as a vector setcc + 3539 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3540 // min/max is legal on the scalar type. 3541 bool UseScalarMinMax = VT.isVector() && 3542 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3543 3544 // ValueTracking's select pattern matching does not account for -0.0, 3545 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3546 // -0.0 is less than +0.0. 3547 Value *LHS, *RHS; 3548 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3549 ISD::NodeType Opc = ISD::DELETED_NODE; 3550 switch (SPR.Flavor) { 3551 case SPF_UMAX: Opc = ISD::UMAX; break; 3552 case SPF_UMIN: Opc = ISD::UMIN; break; 3553 case SPF_SMAX: Opc = ISD::SMAX; break; 3554 case SPF_SMIN: Opc = ISD::SMIN; break; 3555 case SPF_FMINNUM: 3556 switch (SPR.NaNBehavior) { 3557 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3558 case SPNB_RETURNS_NAN: break; 3559 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3560 case SPNB_RETURNS_ANY: 3561 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3562 (UseScalarMinMax && 3563 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3564 Opc = ISD::FMINNUM; 3565 break; 3566 } 3567 break; 3568 case SPF_FMAXNUM: 3569 switch (SPR.NaNBehavior) { 3570 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3571 case SPNB_RETURNS_NAN: break; 3572 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3573 case SPNB_RETURNS_ANY: 3574 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3575 (UseScalarMinMax && 3576 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3577 Opc = ISD::FMAXNUM; 3578 break; 3579 } 3580 break; 3581 case SPF_NABS: 3582 Negate = true; 3583 [[fallthrough]]; 3584 case SPF_ABS: 3585 IsUnaryAbs = true; 3586 Opc = ISD::ABS; 3587 break; 3588 default: break; 3589 } 3590 3591 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3592 (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) || 3593 (UseScalarMinMax && 3594 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3595 // If the underlying comparison instruction is used by any other 3596 // instruction, the consumed instructions won't be destroyed, so it is 3597 // not profitable to convert to a min/max. 3598 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3599 OpCode = Opc; 3600 LHSVal = getValue(LHS); 3601 RHSVal = getValue(RHS); 3602 BaseOps.clear(); 3603 } 3604 3605 if (IsUnaryAbs) { 3606 OpCode = Opc; 3607 LHSVal = getValue(LHS); 3608 BaseOps.clear(); 3609 } 3610 } 3611 3612 if (IsUnaryAbs) { 3613 for (unsigned i = 0; i != NumValues; ++i) { 3614 SDLoc dl = getCurSDLoc(); 3615 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3616 Values[i] = 3617 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3618 if (Negate) 3619 Values[i] = DAG.getNegative(Values[i], dl, VT); 3620 } 3621 } else { 3622 for (unsigned i = 0; i != NumValues; ++i) { 3623 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3624 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3625 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3626 Values[i] = DAG.getNode( 3627 OpCode, getCurSDLoc(), 3628 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3629 } 3630 } 3631 3632 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3633 DAG.getVTList(ValueVTs), Values)); 3634 } 3635 3636 void SelectionDAGBuilder::visitTrunc(const User &I) { 3637 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3638 SDValue N = getValue(I.getOperand(0)); 3639 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3640 I.getType()); 3641 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3642 } 3643 3644 void SelectionDAGBuilder::visitZExt(const User &I) { 3645 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3646 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3647 SDValue N = getValue(I.getOperand(0)); 3648 auto &TLI = DAG.getTargetLoweringInfo(); 3649 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3650 3651 SDNodeFlags Flags; 3652 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I)) 3653 Flags.setNonNeg(PNI->hasNonNeg()); 3654 3655 // Eagerly use nonneg information to canonicalize towards sign_extend if 3656 // that is the target's preference. 3657 // TODO: Let the target do this later. 3658 if (Flags.hasNonNeg() && 3659 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) { 3660 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3661 return; 3662 } 3663 3664 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags)); 3665 } 3666 3667 void SelectionDAGBuilder::visitSExt(const User &I) { 3668 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3669 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3670 SDValue N = getValue(I.getOperand(0)); 3671 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3672 I.getType()); 3673 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3674 } 3675 3676 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3677 // FPTrunc is never a no-op cast, no need to check 3678 SDValue N = getValue(I.getOperand(0)); 3679 SDLoc dl = getCurSDLoc(); 3680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3681 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3682 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3683 DAG.getTargetConstant( 3684 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3685 } 3686 3687 void SelectionDAGBuilder::visitFPExt(const User &I) { 3688 // FPExt is never a no-op cast, no need to check 3689 SDValue N = getValue(I.getOperand(0)); 3690 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3691 I.getType()); 3692 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3693 } 3694 3695 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3696 // FPToUI is never a no-op cast, no need to check 3697 SDValue N = getValue(I.getOperand(0)); 3698 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3699 I.getType()); 3700 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3701 } 3702 3703 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3704 // FPToSI is never a no-op cast, no need to check 3705 SDValue N = getValue(I.getOperand(0)); 3706 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3707 I.getType()); 3708 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3709 } 3710 3711 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3712 // UIToFP is never a no-op cast, no need to check 3713 SDValue N = getValue(I.getOperand(0)); 3714 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3715 I.getType()); 3716 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3717 } 3718 3719 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3720 // SIToFP is never a no-op cast, no need to check 3721 SDValue N = getValue(I.getOperand(0)); 3722 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3723 I.getType()); 3724 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3725 } 3726 3727 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3728 // What to do depends on the size of the integer and the size of the pointer. 3729 // We can either truncate, zero extend, or no-op, accordingly. 3730 SDValue N = getValue(I.getOperand(0)); 3731 auto &TLI = DAG.getTargetLoweringInfo(); 3732 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3733 I.getType()); 3734 EVT PtrMemVT = 3735 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3736 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3737 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3738 setValue(&I, N); 3739 } 3740 3741 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3742 // What to do depends on the size of the integer and the size of the pointer. 3743 // We can either truncate, zero extend, or no-op, accordingly. 3744 SDValue N = getValue(I.getOperand(0)); 3745 auto &TLI = DAG.getTargetLoweringInfo(); 3746 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3747 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3748 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3749 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3750 setValue(&I, N); 3751 } 3752 3753 void SelectionDAGBuilder::visitBitCast(const User &I) { 3754 SDValue N = getValue(I.getOperand(0)); 3755 SDLoc dl = getCurSDLoc(); 3756 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3757 I.getType()); 3758 3759 // BitCast assures us that source and destination are the same size so this is 3760 // either a BITCAST or a no-op. 3761 if (DestVT != N.getValueType()) 3762 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3763 DestVT, N)); // convert types. 3764 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3765 // might fold any kind of constant expression to an integer constant and that 3766 // is not what we are looking for. Only recognize a bitcast of a genuine 3767 // constant integer as an opaque constant. 3768 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3769 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3770 /*isOpaque*/true)); 3771 else 3772 setValue(&I, N); // noop cast. 3773 } 3774 3775 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3777 const Value *SV = I.getOperand(0); 3778 SDValue N = getValue(SV); 3779 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3780 3781 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3782 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3783 3784 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3785 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3786 3787 setValue(&I, N); 3788 } 3789 3790 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3792 SDValue InVec = getValue(I.getOperand(0)); 3793 SDValue InVal = getValue(I.getOperand(1)); 3794 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3795 TLI.getVectorIdxTy(DAG.getDataLayout())); 3796 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3797 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3798 InVec, InVal, InIdx)); 3799 } 3800 3801 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3803 SDValue InVec = getValue(I.getOperand(0)); 3804 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3805 TLI.getVectorIdxTy(DAG.getDataLayout())); 3806 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3807 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3808 InVec, InIdx)); 3809 } 3810 3811 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3812 SDValue Src1 = getValue(I.getOperand(0)); 3813 SDValue Src2 = getValue(I.getOperand(1)); 3814 ArrayRef<int> Mask; 3815 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3816 Mask = SVI->getShuffleMask(); 3817 else 3818 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3819 SDLoc DL = getCurSDLoc(); 3820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3821 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3822 EVT SrcVT = Src1.getValueType(); 3823 3824 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3825 VT.isScalableVector()) { 3826 // Canonical splat form of first element of first input vector. 3827 SDValue FirstElt = 3828 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3829 DAG.getVectorIdxConstant(0, DL)); 3830 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3831 return; 3832 } 3833 3834 // For now, we only handle splats for scalable vectors. 3835 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3836 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3837 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3838 3839 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3840 unsigned MaskNumElts = Mask.size(); 3841 3842 if (SrcNumElts == MaskNumElts) { 3843 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3844 return; 3845 } 3846 3847 // Normalize the shuffle vector since mask and vector length don't match. 3848 if (SrcNumElts < MaskNumElts) { 3849 // Mask is longer than the source vectors. We can use concatenate vector to 3850 // make the mask and vectors lengths match. 3851 3852 if (MaskNumElts % SrcNumElts == 0) { 3853 // Mask length is a multiple of the source vector length. 3854 // Check if the shuffle is some kind of concatenation of the input 3855 // vectors. 3856 unsigned NumConcat = MaskNumElts / SrcNumElts; 3857 bool IsConcat = true; 3858 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3859 for (unsigned i = 0; i != MaskNumElts; ++i) { 3860 int Idx = Mask[i]; 3861 if (Idx < 0) 3862 continue; 3863 // Ensure the indices in each SrcVT sized piece are sequential and that 3864 // the same source is used for the whole piece. 3865 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3866 (ConcatSrcs[i / SrcNumElts] >= 0 && 3867 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3868 IsConcat = false; 3869 break; 3870 } 3871 // Remember which source this index came from. 3872 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3873 } 3874 3875 // The shuffle is concatenating multiple vectors together. Just emit 3876 // a CONCAT_VECTORS operation. 3877 if (IsConcat) { 3878 SmallVector<SDValue, 8> ConcatOps; 3879 for (auto Src : ConcatSrcs) { 3880 if (Src < 0) 3881 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3882 else if (Src == 0) 3883 ConcatOps.push_back(Src1); 3884 else 3885 ConcatOps.push_back(Src2); 3886 } 3887 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3888 return; 3889 } 3890 } 3891 3892 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3893 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3894 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3895 PaddedMaskNumElts); 3896 3897 // Pad both vectors with undefs to make them the same length as the mask. 3898 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3899 3900 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3901 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3902 MOps1[0] = Src1; 3903 MOps2[0] = Src2; 3904 3905 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3906 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3907 3908 // Readjust mask for new input vector length. 3909 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3910 for (unsigned i = 0; i != MaskNumElts; ++i) { 3911 int Idx = Mask[i]; 3912 if (Idx >= (int)SrcNumElts) 3913 Idx -= SrcNumElts - PaddedMaskNumElts; 3914 MappedOps[i] = Idx; 3915 } 3916 3917 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3918 3919 // If the concatenated vector was padded, extract a subvector with the 3920 // correct number of elements. 3921 if (MaskNumElts != PaddedMaskNumElts) 3922 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3923 DAG.getVectorIdxConstant(0, DL)); 3924 3925 setValue(&I, Result); 3926 return; 3927 } 3928 3929 if (SrcNumElts > MaskNumElts) { 3930 // Analyze the access pattern of the vector to see if we can extract 3931 // two subvectors and do the shuffle. 3932 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3933 bool CanExtract = true; 3934 for (int Idx : Mask) { 3935 unsigned Input = 0; 3936 if (Idx < 0) 3937 continue; 3938 3939 if (Idx >= (int)SrcNumElts) { 3940 Input = 1; 3941 Idx -= SrcNumElts; 3942 } 3943 3944 // If all the indices come from the same MaskNumElts sized portion of 3945 // the sources we can use extract. Also make sure the extract wouldn't 3946 // extract past the end of the source. 3947 int NewStartIdx = alignDown(Idx, MaskNumElts); 3948 if (NewStartIdx + MaskNumElts > SrcNumElts || 3949 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3950 CanExtract = false; 3951 // Make sure we always update StartIdx as we use it to track if all 3952 // elements are undef. 3953 StartIdx[Input] = NewStartIdx; 3954 } 3955 3956 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3957 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3958 return; 3959 } 3960 if (CanExtract) { 3961 // Extract appropriate subvector and generate a vector shuffle 3962 for (unsigned Input = 0; Input < 2; ++Input) { 3963 SDValue &Src = Input == 0 ? Src1 : Src2; 3964 if (StartIdx[Input] < 0) 3965 Src = DAG.getUNDEF(VT); 3966 else { 3967 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3968 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3969 } 3970 } 3971 3972 // Calculate new mask. 3973 SmallVector<int, 8> MappedOps(Mask); 3974 for (int &Idx : MappedOps) { 3975 if (Idx >= (int)SrcNumElts) 3976 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3977 else if (Idx >= 0) 3978 Idx -= StartIdx[0]; 3979 } 3980 3981 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3982 return; 3983 } 3984 } 3985 3986 // We can't use either concat vectors or extract subvectors so fall back to 3987 // replacing the shuffle with extract and build vector. 3988 // to insert and build vector. 3989 EVT EltVT = VT.getVectorElementType(); 3990 SmallVector<SDValue,8> Ops; 3991 for (int Idx : Mask) { 3992 SDValue Res; 3993 3994 if (Idx < 0) { 3995 Res = DAG.getUNDEF(EltVT); 3996 } else { 3997 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3998 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3999 4000 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 4001 DAG.getVectorIdxConstant(Idx, DL)); 4002 } 4003 4004 Ops.push_back(Res); 4005 } 4006 4007 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 4008 } 4009 4010 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 4011 ArrayRef<unsigned> Indices = I.getIndices(); 4012 const Value *Op0 = I.getOperand(0); 4013 const Value *Op1 = I.getOperand(1); 4014 Type *AggTy = I.getType(); 4015 Type *ValTy = Op1->getType(); 4016 bool IntoUndef = isa<UndefValue>(Op0); 4017 bool FromUndef = isa<UndefValue>(Op1); 4018 4019 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4020 4021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4022 SmallVector<EVT, 4> AggValueVTs; 4023 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 4024 SmallVector<EVT, 4> ValValueVTs; 4025 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4026 4027 unsigned NumAggValues = AggValueVTs.size(); 4028 unsigned NumValValues = ValValueVTs.size(); 4029 SmallVector<SDValue, 4> Values(NumAggValues); 4030 4031 // Ignore an insertvalue that produces an empty object 4032 if (!NumAggValues) { 4033 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4034 return; 4035 } 4036 4037 SDValue Agg = getValue(Op0); 4038 unsigned i = 0; 4039 // Copy the beginning value(s) from the original aggregate. 4040 for (; i != LinearIndex; ++i) 4041 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4042 SDValue(Agg.getNode(), Agg.getResNo() + i); 4043 // Copy values from the inserted value(s). 4044 if (NumValValues) { 4045 SDValue Val = getValue(Op1); 4046 for (; i != LinearIndex + NumValValues; ++i) 4047 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4048 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 4049 } 4050 // Copy remaining value(s) from the original aggregate. 4051 for (; i != NumAggValues; ++i) 4052 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 4053 SDValue(Agg.getNode(), Agg.getResNo() + i); 4054 4055 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4056 DAG.getVTList(AggValueVTs), Values)); 4057 } 4058 4059 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 4060 ArrayRef<unsigned> Indices = I.getIndices(); 4061 const Value *Op0 = I.getOperand(0); 4062 Type *AggTy = Op0->getType(); 4063 Type *ValTy = I.getType(); 4064 bool OutOfUndef = isa<UndefValue>(Op0); 4065 4066 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 4067 4068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4069 SmallVector<EVT, 4> ValValueVTs; 4070 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 4071 4072 unsigned NumValValues = ValValueVTs.size(); 4073 4074 // Ignore a extractvalue that produces an empty object 4075 if (!NumValValues) { 4076 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 4077 return; 4078 } 4079 4080 SmallVector<SDValue, 4> Values(NumValValues); 4081 4082 SDValue Agg = getValue(Op0); 4083 // Copy out the selected value(s). 4084 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 4085 Values[i - LinearIndex] = 4086 OutOfUndef ? 4087 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 4088 SDValue(Agg.getNode(), Agg.getResNo() + i); 4089 4090 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 4091 DAG.getVTList(ValValueVTs), Values)); 4092 } 4093 4094 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 4095 Value *Op0 = I.getOperand(0); 4096 // Note that the pointer operand may be a vector of pointers. Take the scalar 4097 // element which holds a pointer. 4098 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 4099 SDValue N = getValue(Op0); 4100 SDLoc dl = getCurSDLoc(); 4101 auto &TLI = DAG.getTargetLoweringInfo(); 4102 4103 // Normalize Vector GEP - all scalar operands should be converted to the 4104 // splat vector. 4105 bool IsVectorGEP = I.getType()->isVectorTy(); 4106 ElementCount VectorElementCount = 4107 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 4108 : ElementCount::getFixed(0); 4109 4110 if (IsVectorGEP && !N.getValueType().isVector()) { 4111 LLVMContext &Context = *DAG.getContext(); 4112 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 4113 N = DAG.getSplat(VT, dl, N); 4114 } 4115 4116 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 4117 GTI != E; ++GTI) { 4118 const Value *Idx = GTI.getOperand(); 4119 if (StructType *StTy = GTI.getStructTypeOrNull()) { 4120 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 4121 if (Field) { 4122 // N = N + Offset 4123 uint64_t Offset = 4124 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 4125 4126 // In an inbounds GEP with an offset that is nonnegative even when 4127 // interpreted as signed, assume there is no unsigned overflow. 4128 SDNodeFlags Flags; 4129 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 4130 Flags.setNoUnsignedWrap(true); 4131 4132 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 4133 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 4134 } 4135 } else { 4136 // IdxSize is the width of the arithmetic according to IR semantics. 4137 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 4138 // (and fix up the result later). 4139 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4140 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4141 TypeSize ElementSize = 4142 GTI.getSequentialElementStride(DAG.getDataLayout()); 4143 // We intentionally mask away the high bits here; ElementSize may not 4144 // fit in IdxTy. 4145 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4146 bool ElementScalable = ElementSize.isScalable(); 4147 4148 // If this is a scalar constant or a splat vector of constants, 4149 // handle it quickly. 4150 const auto *C = dyn_cast<Constant>(Idx); 4151 if (C && isa<VectorType>(C->getType())) 4152 C = C->getSplatValue(); 4153 4154 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4155 if (CI && CI->isZero()) 4156 continue; 4157 if (CI && !ElementScalable) { 4158 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4159 LLVMContext &Context = *DAG.getContext(); 4160 SDValue OffsVal; 4161 if (IsVectorGEP) 4162 OffsVal = DAG.getConstant( 4163 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4164 else 4165 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4166 4167 // In an inbounds GEP with an offset that is nonnegative even when 4168 // interpreted as signed, assume there is no unsigned overflow. 4169 SDNodeFlags Flags; 4170 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4171 Flags.setNoUnsignedWrap(true); 4172 4173 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4174 4175 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4176 continue; 4177 } 4178 4179 // N = N + Idx * ElementMul; 4180 SDValue IdxN = getValue(Idx); 4181 4182 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4183 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4184 VectorElementCount); 4185 IdxN = DAG.getSplat(VT, dl, IdxN); 4186 } 4187 4188 // If the index is smaller or larger than intptr_t, truncate or extend 4189 // it. 4190 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4191 4192 if (ElementScalable) { 4193 EVT VScaleTy = N.getValueType().getScalarType(); 4194 SDValue VScale = DAG.getNode( 4195 ISD::VSCALE, dl, VScaleTy, 4196 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4197 if (IsVectorGEP) 4198 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4199 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4200 } else { 4201 // If this is a multiply by a power of two, turn it into a shl 4202 // immediately. This is a very common case. 4203 if (ElementMul != 1) { 4204 if (ElementMul.isPowerOf2()) { 4205 unsigned Amt = ElementMul.logBase2(); 4206 IdxN = DAG.getNode(ISD::SHL, dl, 4207 N.getValueType(), IdxN, 4208 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4209 } else { 4210 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4211 IdxN.getValueType()); 4212 IdxN = DAG.getNode(ISD::MUL, dl, 4213 N.getValueType(), IdxN, Scale); 4214 } 4215 } 4216 } 4217 4218 N = DAG.getNode(ISD::ADD, dl, 4219 N.getValueType(), N, IdxN); 4220 } 4221 } 4222 4223 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4224 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4225 if (IsVectorGEP) { 4226 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4227 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4228 } 4229 4230 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4231 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4232 4233 setValue(&I, N); 4234 } 4235 4236 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4237 // If this is a fixed sized alloca in the entry block of the function, 4238 // allocate it statically on the stack. 4239 if (FuncInfo.StaticAllocaMap.count(&I)) 4240 return; // getValue will auto-populate this. 4241 4242 SDLoc dl = getCurSDLoc(); 4243 Type *Ty = I.getAllocatedType(); 4244 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4245 auto &DL = DAG.getDataLayout(); 4246 TypeSize TySize = DL.getTypeAllocSize(Ty); 4247 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4248 4249 SDValue AllocSize = getValue(I.getArraySize()); 4250 4251 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace()); 4252 if (AllocSize.getValueType() != IntPtr) 4253 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4254 4255 if (TySize.isScalable()) 4256 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4257 DAG.getVScale(dl, IntPtr, 4258 APInt(IntPtr.getScalarSizeInBits(), 4259 TySize.getKnownMinValue()))); 4260 else { 4261 SDValue TySizeValue = 4262 DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64)); 4263 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4264 DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr)); 4265 } 4266 4267 // Handle alignment. If the requested alignment is less than or equal to 4268 // the stack alignment, ignore it. If the size is greater than or equal to 4269 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4270 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4271 if (*Alignment <= StackAlign) 4272 Alignment = std::nullopt; 4273 4274 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4275 // Round the size of the allocation up to the stack alignment size 4276 // by add SA-1 to the size. This doesn't overflow because we're computing 4277 // an address inside an alloca. 4278 SDNodeFlags Flags; 4279 Flags.setNoUnsignedWrap(true); 4280 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4281 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4282 4283 // Mask out the low bits for alignment purposes. 4284 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4285 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4286 4287 SDValue Ops[] = { 4288 getRoot(), AllocSize, 4289 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4290 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4291 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4292 setValue(&I, DSA); 4293 DAG.setRoot(DSA.getValue(1)); 4294 4295 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4296 } 4297 4298 static const MDNode *getRangeMetadata(const Instruction &I) { 4299 // If !noundef is not present, then !range violation results in a poison 4300 // value rather than immediate undefined behavior. In theory, transferring 4301 // these annotations to SDAG is fine, but in practice there are key SDAG 4302 // transforms that are known not to be poison-safe, such as folding logical 4303 // and/or to bitwise and/or. For now, only transfer !range if !noundef is 4304 // also present. 4305 if (!I.hasMetadata(LLVMContext::MD_noundef)) 4306 return nullptr; 4307 return I.getMetadata(LLVMContext::MD_range); 4308 } 4309 4310 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4311 if (I.isAtomic()) 4312 return visitAtomicLoad(I); 4313 4314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4315 const Value *SV = I.getOperand(0); 4316 if (TLI.supportSwiftError()) { 4317 // Swifterror values can come from either a function parameter with 4318 // swifterror attribute or an alloca with swifterror attribute. 4319 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4320 if (Arg->hasSwiftErrorAttr()) 4321 return visitLoadFromSwiftError(I); 4322 } 4323 4324 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4325 if (Alloca->isSwiftError()) 4326 return visitLoadFromSwiftError(I); 4327 } 4328 } 4329 4330 SDValue Ptr = getValue(SV); 4331 4332 Type *Ty = I.getType(); 4333 SmallVector<EVT, 4> ValueVTs, MemVTs; 4334 SmallVector<TypeSize, 4> Offsets; 4335 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4336 unsigned NumValues = ValueVTs.size(); 4337 if (NumValues == 0) 4338 return; 4339 4340 Align Alignment = I.getAlign(); 4341 AAMDNodes AAInfo = I.getAAMetadata(); 4342 const MDNode *Ranges = getRangeMetadata(I); 4343 bool isVolatile = I.isVolatile(); 4344 MachineMemOperand::Flags MMOFlags = 4345 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4346 4347 SDValue Root; 4348 bool ConstantMemory = false; 4349 if (isVolatile) 4350 // Serialize volatile loads with other side effects. 4351 Root = getRoot(); 4352 else if (NumValues > MaxParallelChains) 4353 Root = getMemoryRoot(); 4354 else if (AA && 4355 AA->pointsToConstantMemory(MemoryLocation( 4356 SV, 4357 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4358 AAInfo))) { 4359 // Do not serialize (non-volatile) loads of constant memory with anything. 4360 Root = DAG.getEntryNode(); 4361 ConstantMemory = true; 4362 MMOFlags |= MachineMemOperand::MOInvariant; 4363 } else { 4364 // Do not serialize non-volatile loads against each other. 4365 Root = DAG.getRoot(); 4366 } 4367 4368 SDLoc dl = getCurSDLoc(); 4369 4370 if (isVolatile) 4371 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4372 4373 SmallVector<SDValue, 4> Values(NumValues); 4374 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4375 4376 unsigned ChainI = 0; 4377 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4378 // Serializing loads here may result in excessive register pressure, and 4379 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4380 // could recover a bit by hoisting nodes upward in the chain by recognizing 4381 // they are side-effect free or do not alias. The optimizer should really 4382 // avoid this case by converting large object/array copies to llvm.memcpy 4383 // (MaxParallelChains should always remain as failsafe). 4384 if (ChainI == MaxParallelChains) { 4385 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4386 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4387 ArrayRef(Chains.data(), ChainI)); 4388 Root = Chain; 4389 ChainI = 0; 4390 } 4391 4392 // TODO: MachinePointerInfo only supports a fixed length offset. 4393 MachinePointerInfo PtrInfo = 4394 !Offsets[i].isScalable() || Offsets[i].isZero() 4395 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue()) 4396 : MachinePointerInfo(); 4397 4398 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4399 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, 4400 MMOFlags, AAInfo, Ranges); 4401 Chains[ChainI] = L.getValue(1); 4402 4403 if (MemVTs[i] != ValueVTs[i]) 4404 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4405 4406 Values[i] = L; 4407 } 4408 4409 if (!ConstantMemory) { 4410 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4411 ArrayRef(Chains.data(), ChainI)); 4412 if (isVolatile) 4413 DAG.setRoot(Chain); 4414 else 4415 PendingLoads.push_back(Chain); 4416 } 4417 4418 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4419 DAG.getVTList(ValueVTs), Values)); 4420 } 4421 4422 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4423 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4424 "call visitStoreToSwiftError when backend supports swifterror"); 4425 4426 SmallVector<EVT, 4> ValueVTs; 4427 SmallVector<uint64_t, 4> Offsets; 4428 const Value *SrcV = I.getOperand(0); 4429 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4430 SrcV->getType(), ValueVTs, &Offsets, 0); 4431 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4432 "expect a single EVT for swifterror"); 4433 4434 SDValue Src = getValue(SrcV); 4435 // Create a virtual register, then update the virtual register. 4436 Register VReg = 4437 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4438 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4439 // Chain can be getRoot or getControlRoot. 4440 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4441 SDValue(Src.getNode(), Src.getResNo())); 4442 DAG.setRoot(CopyNode); 4443 } 4444 4445 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4446 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4447 "call visitLoadFromSwiftError when backend supports swifterror"); 4448 4449 assert(!I.isVolatile() && 4450 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4451 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4452 "Support volatile, non temporal, invariant for load_from_swift_error"); 4453 4454 const Value *SV = I.getOperand(0); 4455 Type *Ty = I.getType(); 4456 assert( 4457 (!AA || 4458 !AA->pointsToConstantMemory(MemoryLocation( 4459 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4460 I.getAAMetadata()))) && 4461 "load_from_swift_error should not be constant memory"); 4462 4463 SmallVector<EVT, 4> ValueVTs; 4464 SmallVector<uint64_t, 4> Offsets; 4465 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4466 ValueVTs, &Offsets, 0); 4467 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4468 "expect a single EVT for swifterror"); 4469 4470 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4471 SDValue L = DAG.getCopyFromReg( 4472 getRoot(), getCurSDLoc(), 4473 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4474 4475 setValue(&I, L); 4476 } 4477 4478 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4479 if (I.isAtomic()) 4480 return visitAtomicStore(I); 4481 4482 const Value *SrcV = I.getOperand(0); 4483 const Value *PtrV = I.getOperand(1); 4484 4485 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4486 if (TLI.supportSwiftError()) { 4487 // Swifterror values can come from either a function parameter with 4488 // swifterror attribute or an alloca with swifterror attribute. 4489 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4490 if (Arg->hasSwiftErrorAttr()) 4491 return visitStoreToSwiftError(I); 4492 } 4493 4494 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4495 if (Alloca->isSwiftError()) 4496 return visitStoreToSwiftError(I); 4497 } 4498 } 4499 4500 SmallVector<EVT, 4> ValueVTs, MemVTs; 4501 SmallVector<TypeSize, 4> Offsets; 4502 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4503 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4504 unsigned NumValues = ValueVTs.size(); 4505 if (NumValues == 0) 4506 return; 4507 4508 // Get the lowered operands. Note that we do this after 4509 // checking if NumResults is zero, because with zero results 4510 // the operands won't have values in the map. 4511 SDValue Src = getValue(SrcV); 4512 SDValue Ptr = getValue(PtrV); 4513 4514 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4515 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4516 SDLoc dl = getCurSDLoc(); 4517 Align Alignment = I.getAlign(); 4518 AAMDNodes AAInfo = I.getAAMetadata(); 4519 4520 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4521 4522 unsigned ChainI = 0; 4523 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4524 // See visitLoad comments. 4525 if (ChainI == MaxParallelChains) { 4526 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4527 ArrayRef(Chains.data(), ChainI)); 4528 Root = Chain; 4529 ChainI = 0; 4530 } 4531 4532 // TODO: MachinePointerInfo only supports a fixed length offset. 4533 MachinePointerInfo PtrInfo = 4534 !Offsets[i].isScalable() || Offsets[i].isZero() 4535 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue()) 4536 : MachinePointerInfo(); 4537 4538 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]); 4539 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4540 if (MemVTs[i] != ValueVTs[i]) 4541 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4542 SDValue St = 4543 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo); 4544 Chains[ChainI] = St; 4545 } 4546 4547 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4548 ArrayRef(Chains.data(), ChainI)); 4549 setValue(&I, StoreNode); 4550 DAG.setRoot(StoreNode); 4551 } 4552 4553 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4554 bool IsCompressing) { 4555 SDLoc sdl = getCurSDLoc(); 4556 4557 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4558 MaybeAlign &Alignment) { 4559 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4560 Src0 = I.getArgOperand(0); 4561 Ptr = I.getArgOperand(1); 4562 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4563 Mask = I.getArgOperand(3); 4564 }; 4565 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4566 MaybeAlign &Alignment) { 4567 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4568 Src0 = I.getArgOperand(0); 4569 Ptr = I.getArgOperand(1); 4570 Mask = I.getArgOperand(2); 4571 Alignment = std::nullopt; 4572 }; 4573 4574 Value *PtrOperand, *MaskOperand, *Src0Operand; 4575 MaybeAlign Alignment; 4576 if (IsCompressing) 4577 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4578 else 4579 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4580 4581 SDValue Ptr = getValue(PtrOperand); 4582 SDValue Src0 = getValue(Src0Operand); 4583 SDValue Mask = getValue(MaskOperand); 4584 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4585 4586 EVT VT = Src0.getValueType(); 4587 if (!Alignment) 4588 Alignment = DAG.getEVTAlign(VT); 4589 4590 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4591 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4592 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4593 SDValue StoreNode = 4594 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4595 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4596 DAG.setRoot(StoreNode); 4597 setValue(&I, StoreNode); 4598 } 4599 4600 // Get a uniform base for the Gather/Scatter intrinsic. 4601 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4602 // We try to represent it as a base pointer + vector of indices. 4603 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4604 // The first operand of the GEP may be a single pointer or a vector of pointers 4605 // Example: 4606 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4607 // or 4608 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4609 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4610 // 4611 // When the first GEP operand is a single pointer - it is the uniform base we 4612 // are looking for. If first operand of the GEP is a splat vector - we 4613 // extract the splat value and use it as a uniform base. 4614 // In all other cases the function returns 'false'. 4615 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4616 ISD::MemIndexType &IndexType, SDValue &Scale, 4617 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4618 uint64_t ElemSize) { 4619 SelectionDAG& DAG = SDB->DAG; 4620 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4621 const DataLayout &DL = DAG.getDataLayout(); 4622 4623 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4624 4625 // Handle splat constant pointer. 4626 if (auto *C = dyn_cast<Constant>(Ptr)) { 4627 C = C->getSplatValue(); 4628 if (!C) 4629 return false; 4630 4631 Base = SDB->getValue(C); 4632 4633 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4634 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4635 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4636 IndexType = ISD::SIGNED_SCALED; 4637 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4638 return true; 4639 } 4640 4641 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4642 if (!GEP || GEP->getParent() != CurBB) 4643 return false; 4644 4645 if (GEP->getNumOperands() != 2) 4646 return false; 4647 4648 const Value *BasePtr = GEP->getPointerOperand(); 4649 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4650 4651 // Make sure the base is scalar and the index is a vector. 4652 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4653 return false; 4654 4655 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4656 if (ScaleVal.isScalable()) 4657 return false; 4658 4659 // Target may not support the required addressing mode. 4660 if (ScaleVal != 1 && 4661 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize)) 4662 return false; 4663 4664 Base = SDB->getValue(BasePtr); 4665 Index = SDB->getValue(IndexVal); 4666 IndexType = ISD::SIGNED_SCALED; 4667 4668 Scale = 4669 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4670 return true; 4671 } 4672 4673 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4674 SDLoc sdl = getCurSDLoc(); 4675 4676 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4677 const Value *Ptr = I.getArgOperand(1); 4678 SDValue Src0 = getValue(I.getArgOperand(0)); 4679 SDValue Mask = getValue(I.getArgOperand(3)); 4680 EVT VT = Src0.getValueType(); 4681 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4682 ->getMaybeAlignValue() 4683 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4684 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4685 4686 SDValue Base; 4687 SDValue Index; 4688 ISD::MemIndexType IndexType; 4689 SDValue Scale; 4690 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4691 I.getParent(), VT.getScalarStoreSize()); 4692 4693 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4694 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4695 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4696 // TODO: Make MachineMemOperands aware of scalable 4697 // vectors. 4698 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4699 if (!UniformBase) { 4700 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4701 Index = getValue(Ptr); 4702 IndexType = ISD::SIGNED_SCALED; 4703 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4704 } 4705 4706 EVT IdxVT = Index.getValueType(); 4707 EVT EltTy = IdxVT.getVectorElementType(); 4708 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4709 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4710 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4711 } 4712 4713 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4714 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4715 Ops, MMO, IndexType, false); 4716 DAG.setRoot(Scatter); 4717 setValue(&I, Scatter); 4718 } 4719 4720 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4721 SDLoc sdl = getCurSDLoc(); 4722 4723 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4724 MaybeAlign &Alignment) { 4725 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4726 Ptr = I.getArgOperand(0); 4727 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4728 Mask = I.getArgOperand(2); 4729 Src0 = I.getArgOperand(3); 4730 }; 4731 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4732 MaybeAlign &Alignment) { 4733 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4734 Ptr = I.getArgOperand(0); 4735 Alignment = std::nullopt; 4736 Mask = I.getArgOperand(1); 4737 Src0 = I.getArgOperand(2); 4738 }; 4739 4740 Value *PtrOperand, *MaskOperand, *Src0Operand; 4741 MaybeAlign Alignment; 4742 if (IsExpanding) 4743 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4744 else 4745 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4746 4747 SDValue Ptr = getValue(PtrOperand); 4748 SDValue Src0 = getValue(Src0Operand); 4749 SDValue Mask = getValue(MaskOperand); 4750 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4751 4752 EVT VT = Src0.getValueType(); 4753 if (!Alignment) 4754 Alignment = DAG.getEVTAlign(VT); 4755 4756 AAMDNodes AAInfo = I.getAAMetadata(); 4757 const MDNode *Ranges = getRangeMetadata(I); 4758 4759 // Do not serialize masked loads of constant memory with anything. 4760 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4761 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4762 4763 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4764 4765 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4766 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4767 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4768 4769 SDValue Load = 4770 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4771 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4772 if (AddToChain) 4773 PendingLoads.push_back(Load.getValue(1)); 4774 setValue(&I, Load); 4775 } 4776 4777 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4778 SDLoc sdl = getCurSDLoc(); 4779 4780 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4781 const Value *Ptr = I.getArgOperand(0); 4782 SDValue Src0 = getValue(I.getArgOperand(3)); 4783 SDValue Mask = getValue(I.getArgOperand(2)); 4784 4785 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4786 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4787 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4788 ->getMaybeAlignValue() 4789 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4790 4791 const MDNode *Ranges = getRangeMetadata(I); 4792 4793 SDValue Root = DAG.getRoot(); 4794 SDValue Base; 4795 SDValue Index; 4796 ISD::MemIndexType IndexType; 4797 SDValue Scale; 4798 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4799 I.getParent(), VT.getScalarStoreSize()); 4800 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4801 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4802 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4803 // TODO: Make MachineMemOperands aware of scalable 4804 // vectors. 4805 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4806 4807 if (!UniformBase) { 4808 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4809 Index = getValue(Ptr); 4810 IndexType = ISD::SIGNED_SCALED; 4811 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4812 } 4813 4814 EVT IdxVT = Index.getValueType(); 4815 EVT EltTy = IdxVT.getVectorElementType(); 4816 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4817 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4818 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4819 } 4820 4821 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4822 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4823 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4824 4825 PendingLoads.push_back(Gather.getValue(1)); 4826 setValue(&I, Gather); 4827 } 4828 4829 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4830 SDLoc dl = getCurSDLoc(); 4831 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4832 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4833 SyncScope::ID SSID = I.getSyncScopeID(); 4834 4835 SDValue InChain = getRoot(); 4836 4837 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4838 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4839 4840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4841 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4842 4843 MachineFunction &MF = DAG.getMachineFunction(); 4844 MachineMemOperand *MMO = MF.getMachineMemOperand( 4845 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4846 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4847 FailureOrdering); 4848 4849 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4850 dl, MemVT, VTs, InChain, 4851 getValue(I.getPointerOperand()), 4852 getValue(I.getCompareOperand()), 4853 getValue(I.getNewValOperand()), MMO); 4854 4855 SDValue OutChain = L.getValue(2); 4856 4857 setValue(&I, L); 4858 DAG.setRoot(OutChain); 4859 } 4860 4861 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4862 SDLoc dl = getCurSDLoc(); 4863 ISD::NodeType NT; 4864 switch (I.getOperation()) { 4865 default: llvm_unreachable("Unknown atomicrmw operation"); 4866 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4867 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4868 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4869 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4870 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4871 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4872 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4873 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4874 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4875 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4876 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4877 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4878 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4879 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4880 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4881 case AtomicRMWInst::UIncWrap: 4882 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4883 break; 4884 case AtomicRMWInst::UDecWrap: 4885 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4886 break; 4887 } 4888 AtomicOrdering Ordering = I.getOrdering(); 4889 SyncScope::ID SSID = I.getSyncScopeID(); 4890 4891 SDValue InChain = getRoot(); 4892 4893 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4894 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4895 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4896 4897 MachineFunction &MF = DAG.getMachineFunction(); 4898 MachineMemOperand *MMO = MF.getMachineMemOperand( 4899 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4900 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4901 4902 SDValue L = 4903 DAG.getAtomic(NT, dl, MemVT, InChain, 4904 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4905 MMO); 4906 4907 SDValue OutChain = L.getValue(1); 4908 4909 setValue(&I, L); 4910 DAG.setRoot(OutChain); 4911 } 4912 4913 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4914 SDLoc dl = getCurSDLoc(); 4915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4916 SDValue Ops[3]; 4917 Ops[0] = getRoot(); 4918 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4919 TLI.getFenceOperandTy(DAG.getDataLayout())); 4920 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4921 TLI.getFenceOperandTy(DAG.getDataLayout())); 4922 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4923 setValue(&I, N); 4924 DAG.setRoot(N); 4925 } 4926 4927 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4928 SDLoc dl = getCurSDLoc(); 4929 AtomicOrdering Order = I.getOrdering(); 4930 SyncScope::ID SSID = I.getSyncScopeID(); 4931 4932 SDValue InChain = getRoot(); 4933 4934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4935 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4936 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4937 4938 if (!TLI.supportsUnalignedAtomics() && 4939 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4940 report_fatal_error("Cannot generate unaligned atomic load"); 4941 4942 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4943 4944 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4945 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4946 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4947 4948 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4949 4950 SDValue Ptr = getValue(I.getPointerOperand()); 4951 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4952 Ptr, MMO); 4953 4954 SDValue OutChain = L.getValue(1); 4955 if (MemVT != VT) 4956 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4957 4958 setValue(&I, L); 4959 DAG.setRoot(OutChain); 4960 } 4961 4962 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4963 SDLoc dl = getCurSDLoc(); 4964 4965 AtomicOrdering Ordering = I.getOrdering(); 4966 SyncScope::ID SSID = I.getSyncScopeID(); 4967 4968 SDValue InChain = getRoot(); 4969 4970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4971 EVT MemVT = 4972 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4973 4974 if (!TLI.supportsUnalignedAtomics() && 4975 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4976 report_fatal_error("Cannot generate unaligned atomic store"); 4977 4978 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4979 4980 MachineFunction &MF = DAG.getMachineFunction(); 4981 MachineMemOperand *MMO = MF.getMachineMemOperand( 4982 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4983 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4984 4985 SDValue Val = getValue(I.getValueOperand()); 4986 if (Val.getValueType() != MemVT) 4987 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4988 SDValue Ptr = getValue(I.getPointerOperand()); 4989 4990 SDValue OutChain = 4991 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO); 4992 4993 setValue(&I, OutChain); 4994 DAG.setRoot(OutChain); 4995 } 4996 4997 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4998 /// node. 4999 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 5000 unsigned Intrinsic) { 5001 // Ignore the callsite's attributes. A specific call site may be marked with 5002 // readnone, but the lowering code will expect the chain based on the 5003 // definition. 5004 const Function *F = I.getCalledFunction(); 5005 bool HasChain = !F->doesNotAccessMemory(); 5006 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 5007 5008 // Build the operand list. 5009 SmallVector<SDValue, 8> Ops; 5010 if (HasChain) { // If this intrinsic has side-effects, chainify it. 5011 if (OnlyLoad) { 5012 // We don't need to serialize loads against other loads. 5013 Ops.push_back(DAG.getRoot()); 5014 } else { 5015 Ops.push_back(getRoot()); 5016 } 5017 } 5018 5019 // Info is set by getTgtMemIntrinsic 5020 TargetLowering::IntrinsicInfo Info; 5021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5022 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 5023 DAG.getMachineFunction(), 5024 Intrinsic); 5025 5026 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 5027 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 5028 Info.opc == ISD::INTRINSIC_W_CHAIN) 5029 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 5030 TLI.getPointerTy(DAG.getDataLayout()))); 5031 5032 // Add all operands of the call to the operand list. 5033 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 5034 const Value *Arg = I.getArgOperand(i); 5035 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 5036 Ops.push_back(getValue(Arg)); 5037 continue; 5038 } 5039 5040 // Use TargetConstant instead of a regular constant for immarg. 5041 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 5042 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 5043 assert(CI->getBitWidth() <= 64 && 5044 "large intrinsic immediates not handled"); 5045 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 5046 } else { 5047 Ops.push_back( 5048 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 5049 } 5050 } 5051 5052 SmallVector<EVT, 4> ValueVTs; 5053 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 5054 5055 if (HasChain) 5056 ValueVTs.push_back(MVT::Other); 5057 5058 SDVTList VTs = DAG.getVTList(ValueVTs); 5059 5060 // Propagate fast-math-flags from IR to node(s). 5061 SDNodeFlags Flags; 5062 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 5063 Flags.copyFMF(*FPMO); 5064 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 5065 5066 // Create the node. 5067 SDValue Result; 5068 5069 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) { 5070 auto *Token = Bundle->Inputs[0].get(); 5071 SDValue ConvControlToken = getValue(Token); 5072 assert(Ops.back().getValueType() != MVT::Glue && 5073 "Did not expected another glue node here."); 5074 ConvControlToken = 5075 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken); 5076 Ops.push_back(ConvControlToken); 5077 } 5078 5079 // In some cases, custom collection of operands from CallInst I may be needed. 5080 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 5081 if (IsTgtIntrinsic) { 5082 // This is target intrinsic that touches memory 5083 // 5084 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 5085 // didn't yield anything useful. 5086 MachinePointerInfo MPI; 5087 if (Info.ptrVal) 5088 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 5089 else if (Info.fallbackAddressSpace) 5090 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 5091 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 5092 Info.memVT, MPI, Info.align, Info.flags, 5093 Info.size, I.getAAMetadata()); 5094 } else if (!HasChain) { 5095 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 5096 } else if (!I.getType()->isVoidTy()) { 5097 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 5098 } else { 5099 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 5100 } 5101 5102 if (HasChain) { 5103 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 5104 if (OnlyLoad) 5105 PendingLoads.push_back(Chain); 5106 else 5107 DAG.setRoot(Chain); 5108 } 5109 5110 if (!I.getType()->isVoidTy()) { 5111 if (!isa<VectorType>(I.getType())) 5112 Result = lowerRangeToAssertZExt(DAG, I, Result); 5113 5114 MaybeAlign Alignment = I.getRetAlign(); 5115 5116 // Insert `assertalign` node if there's an alignment. 5117 if (InsertAssertAlign && Alignment) { 5118 Result = 5119 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 5120 } 5121 5122 setValue(&I, Result); 5123 } 5124 } 5125 5126 /// GetSignificand - Get the significand and build it into a floating-point 5127 /// number with exponent of 1: 5128 /// 5129 /// Op = (Op & 0x007fffff) | 0x3f800000; 5130 /// 5131 /// where Op is the hexadecimal representation of floating point value. 5132 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 5133 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5134 DAG.getConstant(0x007fffff, dl, MVT::i32)); 5135 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 5136 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5137 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5138 } 5139 5140 /// GetExponent - Get the exponent: 5141 /// 5142 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5143 /// 5144 /// where Op is the hexadecimal representation of floating point value. 5145 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5146 const TargetLowering &TLI, const SDLoc &dl) { 5147 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5148 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5149 SDValue t1 = DAG.getNode( 5150 ISD::SRL, dl, MVT::i32, t0, 5151 DAG.getConstant(23, dl, 5152 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5153 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5154 DAG.getConstant(127, dl, MVT::i32)); 5155 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5156 } 5157 5158 /// getF32Constant - Get 32-bit floating point constant. 5159 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5160 const SDLoc &dl) { 5161 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5162 MVT::f32); 5163 } 5164 5165 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5166 SelectionDAG &DAG) { 5167 // TODO: What fast-math-flags should be set on the floating-point nodes? 5168 5169 // IntegerPartOfX = ((int32_t)(t0); 5170 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5171 5172 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5173 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5174 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5175 5176 // IntegerPartOfX <<= 23; 5177 IntegerPartOfX = 5178 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5179 DAG.getConstant(23, dl, 5180 DAG.getTargetLoweringInfo().getShiftAmountTy( 5181 MVT::i32, DAG.getDataLayout()))); 5182 5183 SDValue TwoToFractionalPartOfX; 5184 if (LimitFloatPrecision <= 6) { 5185 // For floating-point precision of 6: 5186 // 5187 // TwoToFractionalPartOfX = 5188 // 0.997535578f + 5189 // (0.735607626f + 0.252464424f * x) * x; 5190 // 5191 // error 0.0144103317, which is 6 bits 5192 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5193 getF32Constant(DAG, 0x3e814304, dl)); 5194 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5195 getF32Constant(DAG, 0x3f3c50c8, dl)); 5196 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5197 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5198 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5199 } else if (LimitFloatPrecision <= 12) { 5200 // For floating-point precision of 12: 5201 // 5202 // TwoToFractionalPartOfX = 5203 // 0.999892986f + 5204 // (0.696457318f + 5205 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5206 // 5207 // error 0.000107046256, which is 13 to 14 bits 5208 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5209 getF32Constant(DAG, 0x3da235e3, dl)); 5210 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5211 getF32Constant(DAG, 0x3e65b8f3, dl)); 5212 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5213 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5214 getF32Constant(DAG, 0x3f324b07, dl)); 5215 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5216 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5217 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5218 } else { // LimitFloatPrecision <= 18 5219 // For floating-point precision of 18: 5220 // 5221 // TwoToFractionalPartOfX = 5222 // 0.999999982f + 5223 // (0.693148872f + 5224 // (0.240227044f + 5225 // (0.554906021e-1f + 5226 // (0.961591928e-2f + 5227 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5228 // error 2.47208000*10^(-7), which is better than 18 bits 5229 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5230 getF32Constant(DAG, 0x3924b03e, dl)); 5231 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5232 getF32Constant(DAG, 0x3ab24b87, dl)); 5233 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5234 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5235 getF32Constant(DAG, 0x3c1d8c17, dl)); 5236 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5237 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5238 getF32Constant(DAG, 0x3d634a1d, dl)); 5239 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5240 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5241 getF32Constant(DAG, 0x3e75fe14, dl)); 5242 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5243 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5244 getF32Constant(DAG, 0x3f317234, dl)); 5245 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5246 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5247 getF32Constant(DAG, 0x3f800000, dl)); 5248 } 5249 5250 // Add the exponent into the result in integer domain. 5251 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5252 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5253 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5254 } 5255 5256 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5257 /// limited-precision mode. 5258 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5259 const TargetLowering &TLI, SDNodeFlags Flags) { 5260 if (Op.getValueType() == MVT::f32 && 5261 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5262 5263 // Put the exponent in the right bit position for later addition to the 5264 // final result: 5265 // 5266 // t0 = Op * log2(e) 5267 5268 // TODO: What fast-math-flags should be set here? 5269 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5270 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5271 return getLimitedPrecisionExp2(t0, dl, DAG); 5272 } 5273 5274 // No special expansion. 5275 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5276 } 5277 5278 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5279 /// limited-precision mode. 5280 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5281 const TargetLowering &TLI, SDNodeFlags Flags) { 5282 // TODO: What fast-math-flags should be set on the floating-point nodes? 5283 5284 if (Op.getValueType() == MVT::f32 && 5285 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5286 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5287 5288 // Scale the exponent by log(2). 5289 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5290 SDValue LogOfExponent = 5291 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5292 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5293 5294 // Get the significand and build it into a floating-point number with 5295 // exponent of 1. 5296 SDValue X = GetSignificand(DAG, Op1, dl); 5297 5298 SDValue LogOfMantissa; 5299 if (LimitFloatPrecision <= 6) { 5300 // For floating-point precision of 6: 5301 // 5302 // LogofMantissa = 5303 // -1.1609546f + 5304 // (1.4034025f - 0.23903021f * x) * x; 5305 // 5306 // error 0.0034276066, which is better than 8 bits 5307 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5308 getF32Constant(DAG, 0xbe74c456, dl)); 5309 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5310 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5311 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5312 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5313 getF32Constant(DAG, 0x3f949a29, dl)); 5314 } else if (LimitFloatPrecision <= 12) { 5315 // For floating-point precision of 12: 5316 // 5317 // LogOfMantissa = 5318 // -1.7417939f + 5319 // (2.8212026f + 5320 // (-1.4699568f + 5321 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5322 // 5323 // error 0.000061011436, which is 14 bits 5324 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5325 getF32Constant(DAG, 0xbd67b6d6, dl)); 5326 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5327 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5328 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5329 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5330 getF32Constant(DAG, 0x3fbc278b, dl)); 5331 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5332 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5333 getF32Constant(DAG, 0x40348e95, dl)); 5334 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5335 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5336 getF32Constant(DAG, 0x3fdef31a, dl)); 5337 } else { // LimitFloatPrecision <= 18 5338 // For floating-point precision of 18: 5339 // 5340 // LogOfMantissa = 5341 // -2.1072184f + 5342 // (4.2372794f + 5343 // (-3.7029485f + 5344 // (2.2781945f + 5345 // (-0.87823314f + 5346 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5347 // 5348 // error 0.0000023660568, which is better than 18 bits 5349 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5350 getF32Constant(DAG, 0xbc91e5ac, dl)); 5351 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5352 getF32Constant(DAG, 0x3e4350aa, dl)); 5353 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5354 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5355 getF32Constant(DAG, 0x3f60d3e3, dl)); 5356 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5357 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5358 getF32Constant(DAG, 0x4011cdf0, dl)); 5359 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5360 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5361 getF32Constant(DAG, 0x406cfd1c, dl)); 5362 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5363 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5364 getF32Constant(DAG, 0x408797cb, dl)); 5365 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5366 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5367 getF32Constant(DAG, 0x4006dcab, dl)); 5368 } 5369 5370 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5371 } 5372 5373 // No special expansion. 5374 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5375 } 5376 5377 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5378 /// limited-precision mode. 5379 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5380 const TargetLowering &TLI, SDNodeFlags Flags) { 5381 // TODO: What fast-math-flags should be set on the floating-point nodes? 5382 5383 if (Op.getValueType() == MVT::f32 && 5384 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5385 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5386 5387 // Get the exponent. 5388 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5389 5390 // Get the significand and build it into a floating-point number with 5391 // exponent of 1. 5392 SDValue X = GetSignificand(DAG, Op1, dl); 5393 5394 // Different possible minimax approximations of significand in 5395 // floating-point for various degrees of accuracy over [1,2]. 5396 SDValue Log2ofMantissa; 5397 if (LimitFloatPrecision <= 6) { 5398 // For floating-point precision of 6: 5399 // 5400 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5401 // 5402 // error 0.0049451742, which is more than 7 bits 5403 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5404 getF32Constant(DAG, 0xbeb08fe0, dl)); 5405 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5406 getF32Constant(DAG, 0x40019463, dl)); 5407 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5408 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5409 getF32Constant(DAG, 0x3fd6633d, dl)); 5410 } else if (LimitFloatPrecision <= 12) { 5411 // For floating-point precision of 12: 5412 // 5413 // Log2ofMantissa = 5414 // -2.51285454f + 5415 // (4.07009056f + 5416 // (-2.12067489f + 5417 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5418 // 5419 // error 0.0000876136000, which is better than 13 bits 5420 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5421 getF32Constant(DAG, 0xbda7262e, dl)); 5422 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5423 getF32Constant(DAG, 0x3f25280b, dl)); 5424 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5425 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5426 getF32Constant(DAG, 0x4007b923, dl)); 5427 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5428 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5429 getF32Constant(DAG, 0x40823e2f, dl)); 5430 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5431 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5432 getF32Constant(DAG, 0x4020d29c, dl)); 5433 } else { // LimitFloatPrecision <= 18 5434 // For floating-point precision of 18: 5435 // 5436 // Log2ofMantissa = 5437 // -3.0400495f + 5438 // (6.1129976f + 5439 // (-5.3420409f + 5440 // (3.2865683f + 5441 // (-1.2669343f + 5442 // (0.27515199f - 5443 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5444 // 5445 // error 0.0000018516, which is better than 18 bits 5446 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5447 getF32Constant(DAG, 0xbcd2769e, dl)); 5448 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5449 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5450 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5451 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5452 getF32Constant(DAG, 0x3fa22ae7, dl)); 5453 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5454 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5455 getF32Constant(DAG, 0x40525723, dl)); 5456 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5457 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5458 getF32Constant(DAG, 0x40aaf200, dl)); 5459 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5460 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5461 getF32Constant(DAG, 0x40c39dad, dl)); 5462 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5463 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5464 getF32Constant(DAG, 0x4042902c, dl)); 5465 } 5466 5467 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5468 } 5469 5470 // No special expansion. 5471 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5472 } 5473 5474 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5475 /// limited-precision mode. 5476 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5477 const TargetLowering &TLI, SDNodeFlags Flags) { 5478 // TODO: What fast-math-flags should be set on the floating-point nodes? 5479 5480 if (Op.getValueType() == MVT::f32 && 5481 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5482 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5483 5484 // Scale the exponent by log10(2) [0.30102999f]. 5485 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5486 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5487 getF32Constant(DAG, 0x3e9a209a, dl)); 5488 5489 // Get the significand and build it into a floating-point number with 5490 // exponent of 1. 5491 SDValue X = GetSignificand(DAG, Op1, dl); 5492 5493 SDValue Log10ofMantissa; 5494 if (LimitFloatPrecision <= 6) { 5495 // For floating-point precision of 6: 5496 // 5497 // Log10ofMantissa = 5498 // -0.50419619f + 5499 // (0.60948995f - 0.10380950f * x) * x; 5500 // 5501 // error 0.0014886165, which is 6 bits 5502 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5503 getF32Constant(DAG, 0xbdd49a13, dl)); 5504 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5505 getF32Constant(DAG, 0x3f1c0789, dl)); 5506 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5507 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5508 getF32Constant(DAG, 0x3f011300, dl)); 5509 } else if (LimitFloatPrecision <= 12) { 5510 // For floating-point precision of 12: 5511 // 5512 // Log10ofMantissa = 5513 // -0.64831180f + 5514 // (0.91751397f + 5515 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5516 // 5517 // error 0.00019228036, which is better than 12 bits 5518 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5519 getF32Constant(DAG, 0x3d431f31, dl)); 5520 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5521 getF32Constant(DAG, 0x3ea21fb2, dl)); 5522 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5523 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5524 getF32Constant(DAG, 0x3f6ae232, dl)); 5525 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5526 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5527 getF32Constant(DAG, 0x3f25f7c3, dl)); 5528 } else { // LimitFloatPrecision <= 18 5529 // For floating-point precision of 18: 5530 // 5531 // Log10ofMantissa = 5532 // -0.84299375f + 5533 // (1.5327582f + 5534 // (-1.0688956f + 5535 // (0.49102474f + 5536 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5537 // 5538 // error 0.0000037995730, which is better than 18 bits 5539 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5540 getF32Constant(DAG, 0x3c5d51ce, dl)); 5541 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5542 getF32Constant(DAG, 0x3e00685a, dl)); 5543 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5544 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5545 getF32Constant(DAG, 0x3efb6798, dl)); 5546 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5547 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5548 getF32Constant(DAG, 0x3f88d192, dl)); 5549 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5550 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5551 getF32Constant(DAG, 0x3fc4316c, dl)); 5552 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5553 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5554 getF32Constant(DAG, 0x3f57ce70, dl)); 5555 } 5556 5557 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5558 } 5559 5560 // No special expansion. 5561 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5562 } 5563 5564 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5565 /// limited-precision mode. 5566 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5567 const TargetLowering &TLI, SDNodeFlags Flags) { 5568 if (Op.getValueType() == MVT::f32 && 5569 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5570 return getLimitedPrecisionExp2(Op, dl, DAG); 5571 5572 // No special expansion. 5573 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5574 } 5575 5576 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5577 /// limited-precision mode with x == 10.0f. 5578 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5579 SelectionDAG &DAG, const TargetLowering &TLI, 5580 SDNodeFlags Flags) { 5581 bool IsExp10 = false; 5582 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5583 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5584 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5585 APFloat Ten(10.0f); 5586 IsExp10 = LHSC->isExactlyValue(Ten); 5587 } 5588 } 5589 5590 // TODO: What fast-math-flags should be set on the FMUL node? 5591 if (IsExp10) { 5592 // Put the exponent in the right bit position for later addition to the 5593 // final result: 5594 // 5595 // #define LOG2OF10 3.3219281f 5596 // t0 = Op * LOG2OF10; 5597 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5598 getF32Constant(DAG, 0x40549a78, dl)); 5599 return getLimitedPrecisionExp2(t0, dl, DAG); 5600 } 5601 5602 // No special expansion. 5603 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5604 } 5605 5606 /// ExpandPowI - Expand a llvm.powi intrinsic. 5607 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5608 SelectionDAG &DAG) { 5609 // If RHS is a constant, we can expand this out to a multiplication tree if 5610 // it's beneficial on the target, otherwise we end up lowering to a call to 5611 // __powidf2 (for example). 5612 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5613 unsigned Val = RHSC->getSExtValue(); 5614 5615 // powi(x, 0) -> 1.0 5616 if (Val == 0) 5617 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5618 5619 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5620 Val, DAG.shouldOptForSize())) { 5621 // Get the exponent as a positive value. 5622 if ((int)Val < 0) 5623 Val = -Val; 5624 // We use the simple binary decomposition method to generate the multiply 5625 // sequence. There are more optimal ways to do this (for example, 5626 // powi(x,15) generates one more multiply than it should), but this has 5627 // the benefit of being both really simple and much better than a libcall. 5628 SDValue Res; // Logically starts equal to 1.0 5629 SDValue CurSquare = LHS; 5630 // TODO: Intrinsics should have fast-math-flags that propagate to these 5631 // nodes. 5632 while (Val) { 5633 if (Val & 1) { 5634 if (Res.getNode()) 5635 Res = 5636 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5637 else 5638 Res = CurSquare; // 1.0*CurSquare. 5639 } 5640 5641 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5642 CurSquare, CurSquare); 5643 Val >>= 1; 5644 } 5645 5646 // If the original was negative, invert the result, producing 1/(x*x*x). 5647 if (RHSC->getSExtValue() < 0) 5648 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5649 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5650 return Res; 5651 } 5652 } 5653 5654 // Otherwise, expand to a libcall. 5655 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5656 } 5657 5658 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5659 SDValue LHS, SDValue RHS, SDValue Scale, 5660 SelectionDAG &DAG, const TargetLowering &TLI) { 5661 EVT VT = LHS.getValueType(); 5662 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5663 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5664 LLVMContext &Ctx = *DAG.getContext(); 5665 5666 // If the type is legal but the operation isn't, this node might survive all 5667 // the way to operation legalization. If we end up there and we do not have 5668 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5669 // node. 5670 5671 // Coax the legalizer into expanding the node during type legalization instead 5672 // by bumping the size by one bit. This will force it to Promote, enabling the 5673 // early expansion and avoiding the need to expand later. 5674 5675 // We don't have to do this if Scale is 0; that can always be expanded, unless 5676 // it's a saturating signed operation. Those can experience true integer 5677 // division overflow, a case which we must avoid. 5678 5679 // FIXME: We wouldn't have to do this (or any of the early 5680 // expansion/promotion) if it was possible to expand a libcall of an 5681 // illegal type during operation legalization. But it's not, so things 5682 // get a bit hacky. 5683 unsigned ScaleInt = Scale->getAsZExtVal(); 5684 if ((ScaleInt > 0 || (Saturating && Signed)) && 5685 (TLI.isTypeLegal(VT) || 5686 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5687 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5688 Opcode, VT, ScaleInt); 5689 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5690 EVT PromVT; 5691 if (VT.isScalarInteger()) 5692 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5693 else if (VT.isVector()) { 5694 PromVT = VT.getVectorElementType(); 5695 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5696 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5697 } else 5698 llvm_unreachable("Wrong VT for DIVFIX?"); 5699 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5700 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5701 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5702 // For saturating operations, we need to shift up the LHS to get the 5703 // proper saturation width, and then shift down again afterwards. 5704 if (Saturating) 5705 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5706 DAG.getConstant(1, DL, ShiftTy)); 5707 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5708 if (Saturating) 5709 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5710 DAG.getConstant(1, DL, ShiftTy)); 5711 return DAG.getZExtOrTrunc(Res, DL, VT); 5712 } 5713 } 5714 5715 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5716 } 5717 5718 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5719 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5720 static void 5721 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5722 const SDValue &N) { 5723 switch (N.getOpcode()) { 5724 case ISD::CopyFromReg: { 5725 SDValue Op = N.getOperand(1); 5726 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5727 Op.getValueType().getSizeInBits()); 5728 return; 5729 } 5730 case ISD::BITCAST: 5731 case ISD::AssertZext: 5732 case ISD::AssertSext: 5733 case ISD::TRUNCATE: 5734 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5735 return; 5736 case ISD::BUILD_PAIR: 5737 case ISD::BUILD_VECTOR: 5738 case ISD::CONCAT_VECTORS: 5739 for (SDValue Op : N->op_values()) 5740 getUnderlyingArgRegs(Regs, Op); 5741 return; 5742 default: 5743 return; 5744 } 5745 } 5746 5747 /// If the DbgValueInst is a dbg_value of a function argument, create the 5748 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5749 /// instruction selection, they will be inserted to the entry BB. 5750 /// We don't currently support this for variadic dbg_values, as they shouldn't 5751 /// appear for function arguments or in the prologue. 5752 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5753 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5754 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5755 const Argument *Arg = dyn_cast<Argument>(V); 5756 if (!Arg) 5757 return false; 5758 5759 MachineFunction &MF = DAG.getMachineFunction(); 5760 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5761 5762 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5763 // we've been asked to pursue. 5764 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5765 bool Indirect) { 5766 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5767 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5768 // pointing at the VReg, which will be patched up later. 5769 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5770 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5771 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5772 /* isKill */ false, /* isDead */ false, 5773 /* isUndef */ false, /* isEarlyClobber */ false, 5774 /* SubReg */ 0, /* isDebug */ true)}); 5775 5776 auto *NewDIExpr = FragExpr; 5777 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5778 // the DIExpression. 5779 if (Indirect) 5780 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5781 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5782 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5783 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5784 } else { 5785 // Create a completely standard DBG_VALUE. 5786 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5787 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5788 } 5789 }; 5790 5791 if (Kind == FuncArgumentDbgValueKind::Value) { 5792 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5793 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5794 // the entry block. 5795 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5796 if (!IsInEntryBlock) 5797 return false; 5798 5799 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5800 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5801 // variable that also is a param. 5802 // 5803 // Although, if we are at the top of the entry block already, we can still 5804 // emit using ArgDbgValue. This might catch some situations when the 5805 // dbg.value refers to an argument that isn't used in the entry block, so 5806 // any CopyToReg node would be optimized out and the only way to express 5807 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5808 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5809 // we should only emit as ArgDbgValue if the Variable is an argument to the 5810 // current function, and the dbg.value intrinsic is found in the entry 5811 // block. 5812 bool VariableIsFunctionInputArg = Variable->isParameter() && 5813 !DL->getInlinedAt(); 5814 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5815 if (!IsInPrologue && !VariableIsFunctionInputArg) 5816 return false; 5817 5818 // Here we assume that a function argument on IR level only can be used to 5819 // describe one input parameter on source level. If we for example have 5820 // source code like this 5821 // 5822 // struct A { long x, y; }; 5823 // void foo(struct A a, long b) { 5824 // ... 5825 // b = a.x; 5826 // ... 5827 // } 5828 // 5829 // and IR like this 5830 // 5831 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5832 // entry: 5833 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5834 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5835 // call void @llvm.dbg.value(metadata i32 %b, "b", 5836 // ... 5837 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5838 // ... 5839 // 5840 // then the last dbg.value is describing a parameter "b" using a value that 5841 // is an argument. But since we already has used %a1 to describe a parameter 5842 // we should not handle that last dbg.value here (that would result in an 5843 // incorrect hoisting of the DBG_VALUE to the function entry). 5844 // Notice that we allow one dbg.value per IR level argument, to accommodate 5845 // for the situation with fragments above. 5846 if (VariableIsFunctionInputArg) { 5847 unsigned ArgNo = Arg->getArgNo(); 5848 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5849 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5850 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5851 return false; 5852 FuncInfo.DescribedArgs.set(ArgNo); 5853 } 5854 } 5855 5856 bool IsIndirect = false; 5857 std::optional<MachineOperand> Op; 5858 // Some arguments' frame index is recorded during argument lowering. 5859 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5860 if (FI != std::numeric_limits<int>::max()) 5861 Op = MachineOperand::CreateFI(FI); 5862 5863 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5864 if (!Op && N.getNode()) { 5865 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5866 Register Reg; 5867 if (ArgRegsAndSizes.size() == 1) 5868 Reg = ArgRegsAndSizes.front().first; 5869 5870 if (Reg && Reg.isVirtual()) { 5871 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5872 Register PR = RegInfo.getLiveInPhysReg(Reg); 5873 if (PR) 5874 Reg = PR; 5875 } 5876 if (Reg) { 5877 Op = MachineOperand::CreateReg(Reg, false); 5878 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5879 } 5880 } 5881 5882 if (!Op && N.getNode()) { 5883 // Check if frame index is available. 5884 SDValue LCandidate = peekThroughBitcasts(N); 5885 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5886 if (FrameIndexSDNode *FINode = 5887 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5888 Op = MachineOperand::CreateFI(FINode->getIndex()); 5889 } 5890 5891 if (!Op) { 5892 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5893 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5894 SplitRegs) { 5895 unsigned Offset = 0; 5896 for (const auto &RegAndSize : SplitRegs) { 5897 // If the expression is already a fragment, the current register 5898 // offset+size might extend beyond the fragment. In this case, only 5899 // the register bits that are inside the fragment are relevant. 5900 int RegFragmentSizeInBits = RegAndSize.second; 5901 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5902 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5903 // The register is entirely outside the expression fragment, 5904 // so is irrelevant for debug info. 5905 if (Offset >= ExprFragmentSizeInBits) 5906 break; 5907 // The register is partially outside the expression fragment, only 5908 // the low bits within the fragment are relevant for debug info. 5909 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5910 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5911 } 5912 } 5913 5914 auto FragmentExpr = DIExpression::createFragmentExpression( 5915 Expr, Offset, RegFragmentSizeInBits); 5916 Offset += RegAndSize.second; 5917 // If a valid fragment expression cannot be created, the variable's 5918 // correct value cannot be determined and so it is set as Undef. 5919 if (!FragmentExpr) { 5920 SDDbgValue *SDV = DAG.getConstantDbgValue( 5921 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5922 DAG.AddDbgValue(SDV, false); 5923 continue; 5924 } 5925 MachineInstr *NewMI = 5926 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5927 Kind != FuncArgumentDbgValueKind::Value); 5928 FuncInfo.ArgDbgValues.push_back(NewMI); 5929 } 5930 }; 5931 5932 // Check if ValueMap has reg number. 5933 DenseMap<const Value *, Register>::const_iterator 5934 VMI = FuncInfo.ValueMap.find(V); 5935 if (VMI != FuncInfo.ValueMap.end()) { 5936 const auto &TLI = DAG.getTargetLoweringInfo(); 5937 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5938 V->getType(), std::nullopt); 5939 if (RFV.occupiesMultipleRegs()) { 5940 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5941 return true; 5942 } 5943 5944 Op = MachineOperand::CreateReg(VMI->second, false); 5945 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5946 } else if (ArgRegsAndSizes.size() > 1) { 5947 // This was split due to the calling convention, and no virtual register 5948 // mapping exists for the value. 5949 splitMultiRegDbgValue(ArgRegsAndSizes); 5950 return true; 5951 } 5952 } 5953 5954 if (!Op) 5955 return false; 5956 5957 assert(Variable->isValidLocationForIntrinsic(DL) && 5958 "Expected inlined-at fields to agree"); 5959 MachineInstr *NewMI = nullptr; 5960 5961 if (Op->isReg()) 5962 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5963 else 5964 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5965 Variable, Expr); 5966 5967 // Otherwise, use ArgDbgValues. 5968 FuncInfo.ArgDbgValues.push_back(NewMI); 5969 return true; 5970 } 5971 5972 /// Return the appropriate SDDbgValue based on N. 5973 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5974 DILocalVariable *Variable, 5975 DIExpression *Expr, 5976 const DebugLoc &dl, 5977 unsigned DbgSDNodeOrder) { 5978 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5979 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5980 // stack slot locations. 5981 // 5982 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5983 // debug values here after optimization: 5984 // 5985 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5986 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5987 // 5988 // Both describe the direct values of their associated variables. 5989 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5990 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5991 } 5992 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5993 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5994 } 5995 5996 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5997 switch (Intrinsic) { 5998 case Intrinsic::smul_fix: 5999 return ISD::SMULFIX; 6000 case Intrinsic::umul_fix: 6001 return ISD::UMULFIX; 6002 case Intrinsic::smul_fix_sat: 6003 return ISD::SMULFIXSAT; 6004 case Intrinsic::umul_fix_sat: 6005 return ISD::UMULFIXSAT; 6006 case Intrinsic::sdiv_fix: 6007 return ISD::SDIVFIX; 6008 case Intrinsic::udiv_fix: 6009 return ISD::UDIVFIX; 6010 case Intrinsic::sdiv_fix_sat: 6011 return ISD::SDIVFIXSAT; 6012 case Intrinsic::udiv_fix_sat: 6013 return ISD::UDIVFIXSAT; 6014 default: 6015 llvm_unreachable("Unhandled fixed point intrinsic"); 6016 } 6017 } 6018 6019 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 6020 const char *FunctionName) { 6021 assert(FunctionName && "FunctionName must not be nullptr"); 6022 SDValue Callee = DAG.getExternalSymbol( 6023 FunctionName, 6024 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6025 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 6026 } 6027 6028 /// Given a @llvm.call.preallocated.setup, return the corresponding 6029 /// preallocated call. 6030 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 6031 assert(cast<CallBase>(PreallocatedSetup) 6032 ->getCalledFunction() 6033 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 6034 "expected call_preallocated_setup Value"); 6035 for (const auto *U : PreallocatedSetup->users()) { 6036 auto *UseCall = cast<CallBase>(U); 6037 const Function *Fn = UseCall->getCalledFunction(); 6038 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 6039 return UseCall; 6040 } 6041 } 6042 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 6043 } 6044 6045 /// If DI is a debug value with an EntryValue expression, lower it using the 6046 /// corresponding physical register of the associated Argument value 6047 /// (guaranteed to exist by the verifier). 6048 bool SelectionDAGBuilder::visitEntryValueDbgValue( 6049 ArrayRef<const Value *> Values, DILocalVariable *Variable, 6050 DIExpression *Expr, DebugLoc DbgLoc) { 6051 if (!Expr->isEntryValue() || !hasSingleElement(Values)) 6052 return false; 6053 6054 // These properties are guaranteed by the verifier. 6055 const Argument *Arg = cast<Argument>(Values[0]); 6056 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 6057 6058 auto ArgIt = FuncInfo.ValueMap.find(Arg); 6059 if (ArgIt == FuncInfo.ValueMap.end()) { 6060 LLVM_DEBUG( 6061 dbgs() << "Dropping dbg.value: expression is entry_value but " 6062 "couldn't find an associated register for the Argument\n"); 6063 return true; 6064 } 6065 Register ArgVReg = ArgIt->getSecond(); 6066 6067 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 6068 if (ArgVReg == VirtReg || ArgVReg == PhysReg) { 6069 SDDbgValue *SDV = DAG.getVRegDbgValue( 6070 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder); 6071 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 6072 return true; 6073 } 6074 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 6075 "couldn't find a physical register\n"); 6076 return true; 6077 } 6078 6079 /// Lower the call to the specified intrinsic function. 6080 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I, 6081 unsigned Intrinsic) { 6082 SDLoc sdl = getCurSDLoc(); 6083 switch (Intrinsic) { 6084 case Intrinsic::experimental_convergence_anchor: 6085 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped)); 6086 break; 6087 case Intrinsic::experimental_convergence_entry: 6088 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped)); 6089 break; 6090 case Intrinsic::experimental_convergence_loop: { 6091 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl); 6092 auto *Token = Bundle->Inputs[0].get(); 6093 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped, 6094 getValue(Token))); 6095 break; 6096 } 6097 } 6098 } 6099 6100 /// Lower the call to the specified intrinsic function. 6101 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 6102 unsigned Intrinsic) { 6103 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6104 SDLoc sdl = getCurSDLoc(); 6105 DebugLoc dl = getCurDebugLoc(); 6106 SDValue Res; 6107 6108 SDNodeFlags Flags; 6109 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 6110 Flags.copyFMF(*FPOp); 6111 6112 switch (Intrinsic) { 6113 default: 6114 // By default, turn this into a target intrinsic node. 6115 visitTargetIntrinsic(I, Intrinsic); 6116 return; 6117 case Intrinsic::vscale: { 6118 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6119 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 6120 return; 6121 } 6122 case Intrinsic::vastart: visitVAStart(I); return; 6123 case Intrinsic::vaend: visitVAEnd(I); return; 6124 case Intrinsic::vacopy: visitVACopy(I); return; 6125 case Intrinsic::returnaddress: 6126 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 6127 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6128 getValue(I.getArgOperand(0)))); 6129 return; 6130 case Intrinsic::addressofreturnaddress: 6131 setValue(&I, 6132 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 6133 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6134 return; 6135 case Intrinsic::sponentry: 6136 setValue(&I, 6137 DAG.getNode(ISD::SPONENTRY, sdl, 6138 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6139 return; 6140 case Intrinsic::frameaddress: 6141 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 6142 TLI.getFrameIndexTy(DAG.getDataLayout()), 6143 getValue(I.getArgOperand(0)))); 6144 return; 6145 case Intrinsic::read_volatile_register: 6146 case Intrinsic::read_register: { 6147 Value *Reg = I.getArgOperand(0); 6148 SDValue Chain = getRoot(); 6149 SDValue RegName = 6150 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6151 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6152 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 6153 DAG.getVTList(VT, MVT::Other), Chain, RegName); 6154 setValue(&I, Res); 6155 DAG.setRoot(Res.getValue(1)); 6156 return; 6157 } 6158 case Intrinsic::write_register: { 6159 Value *Reg = I.getArgOperand(0); 6160 Value *RegValue = I.getArgOperand(1); 6161 SDValue Chain = getRoot(); 6162 SDValue RegName = 6163 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 6164 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 6165 RegName, getValue(RegValue))); 6166 return; 6167 } 6168 case Intrinsic::memcpy: { 6169 const auto &MCI = cast<MemCpyInst>(I); 6170 SDValue Op1 = getValue(I.getArgOperand(0)); 6171 SDValue Op2 = getValue(I.getArgOperand(1)); 6172 SDValue Op3 = getValue(I.getArgOperand(2)); 6173 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6174 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6175 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6176 Align Alignment = std::min(DstAlign, SrcAlign); 6177 bool isVol = MCI.isVolatile(); 6178 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6179 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6180 // node. 6181 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6182 SDValue MC = DAG.getMemcpy( 6183 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6184 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6185 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6186 updateDAGForMaybeTailCall(MC); 6187 return; 6188 } 6189 case Intrinsic::memcpy_inline: { 6190 const auto &MCI = cast<MemCpyInlineInst>(I); 6191 SDValue Dst = getValue(I.getArgOperand(0)); 6192 SDValue Src = getValue(I.getArgOperand(1)); 6193 SDValue Size = getValue(I.getArgOperand(2)); 6194 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6195 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6196 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6197 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6198 Align Alignment = std::min(DstAlign, SrcAlign); 6199 bool isVol = MCI.isVolatile(); 6200 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6201 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6202 // node. 6203 SDValue MC = DAG.getMemcpy( 6204 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6205 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6206 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6207 updateDAGForMaybeTailCall(MC); 6208 return; 6209 } 6210 case Intrinsic::memset: { 6211 const auto &MSI = cast<MemSetInst>(I); 6212 SDValue Op1 = getValue(I.getArgOperand(0)); 6213 SDValue Op2 = getValue(I.getArgOperand(1)); 6214 SDValue Op3 = getValue(I.getArgOperand(2)); 6215 // @llvm.memset defines 0 and 1 to both mean no alignment. 6216 Align Alignment = MSI.getDestAlign().valueOrOne(); 6217 bool isVol = MSI.isVolatile(); 6218 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6219 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6220 SDValue MS = DAG.getMemset( 6221 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6222 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6223 updateDAGForMaybeTailCall(MS); 6224 return; 6225 } 6226 case Intrinsic::memset_inline: { 6227 const auto &MSII = cast<MemSetInlineInst>(I); 6228 SDValue Dst = getValue(I.getArgOperand(0)); 6229 SDValue Value = getValue(I.getArgOperand(1)); 6230 SDValue Size = getValue(I.getArgOperand(2)); 6231 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6232 // @llvm.memset defines 0 and 1 to both mean no alignment. 6233 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6234 bool isVol = MSII.isVolatile(); 6235 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6236 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6237 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6238 /* AlwaysInline */ true, isTC, 6239 MachinePointerInfo(I.getArgOperand(0)), 6240 I.getAAMetadata()); 6241 updateDAGForMaybeTailCall(MC); 6242 return; 6243 } 6244 case Intrinsic::memmove: { 6245 const auto &MMI = cast<MemMoveInst>(I); 6246 SDValue Op1 = getValue(I.getArgOperand(0)); 6247 SDValue Op2 = getValue(I.getArgOperand(1)); 6248 SDValue Op3 = getValue(I.getArgOperand(2)); 6249 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6250 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6251 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6252 Align Alignment = std::min(DstAlign, SrcAlign); 6253 bool isVol = MMI.isVolatile(); 6254 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6255 // FIXME: Support passing different dest/src alignments to the memmove DAG 6256 // node. 6257 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6258 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6259 isTC, MachinePointerInfo(I.getArgOperand(0)), 6260 MachinePointerInfo(I.getArgOperand(1)), 6261 I.getAAMetadata(), AA); 6262 updateDAGForMaybeTailCall(MM); 6263 return; 6264 } 6265 case Intrinsic::memcpy_element_unordered_atomic: { 6266 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6267 SDValue Dst = getValue(MI.getRawDest()); 6268 SDValue Src = getValue(MI.getRawSource()); 6269 SDValue Length = getValue(MI.getLength()); 6270 6271 Type *LengthTy = MI.getLength()->getType(); 6272 unsigned ElemSz = MI.getElementSizeInBytes(); 6273 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6274 SDValue MC = 6275 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6276 isTC, MachinePointerInfo(MI.getRawDest()), 6277 MachinePointerInfo(MI.getRawSource())); 6278 updateDAGForMaybeTailCall(MC); 6279 return; 6280 } 6281 case Intrinsic::memmove_element_unordered_atomic: { 6282 auto &MI = cast<AtomicMemMoveInst>(I); 6283 SDValue Dst = getValue(MI.getRawDest()); 6284 SDValue Src = getValue(MI.getRawSource()); 6285 SDValue Length = getValue(MI.getLength()); 6286 6287 Type *LengthTy = MI.getLength()->getType(); 6288 unsigned ElemSz = MI.getElementSizeInBytes(); 6289 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6290 SDValue MC = 6291 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6292 isTC, MachinePointerInfo(MI.getRawDest()), 6293 MachinePointerInfo(MI.getRawSource())); 6294 updateDAGForMaybeTailCall(MC); 6295 return; 6296 } 6297 case Intrinsic::memset_element_unordered_atomic: { 6298 auto &MI = cast<AtomicMemSetInst>(I); 6299 SDValue Dst = getValue(MI.getRawDest()); 6300 SDValue Val = getValue(MI.getValue()); 6301 SDValue Length = getValue(MI.getLength()); 6302 6303 Type *LengthTy = MI.getLength()->getType(); 6304 unsigned ElemSz = MI.getElementSizeInBytes(); 6305 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6306 SDValue MC = 6307 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6308 isTC, MachinePointerInfo(MI.getRawDest())); 6309 updateDAGForMaybeTailCall(MC); 6310 return; 6311 } 6312 case Intrinsic::call_preallocated_setup: { 6313 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6314 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6315 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6316 getRoot(), SrcValue); 6317 setValue(&I, Res); 6318 DAG.setRoot(Res); 6319 return; 6320 } 6321 case Intrinsic::call_preallocated_arg: { 6322 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6323 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6324 SDValue Ops[3]; 6325 Ops[0] = getRoot(); 6326 Ops[1] = SrcValue; 6327 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6328 MVT::i32); // arg index 6329 SDValue Res = DAG.getNode( 6330 ISD::PREALLOCATED_ARG, sdl, 6331 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6332 setValue(&I, Res); 6333 DAG.setRoot(Res.getValue(1)); 6334 return; 6335 } 6336 case Intrinsic::dbg_declare: { 6337 const auto &DI = cast<DbgDeclareInst>(I); 6338 // Debug intrinsics are handled separately in assignment tracking mode. 6339 // Some intrinsics are handled right after Argument lowering. 6340 if (AssignmentTrackingEnabled || 6341 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6342 return; 6343 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n"); 6344 DILocalVariable *Variable = DI.getVariable(); 6345 DIExpression *Expression = DI.getExpression(); 6346 dropDanglingDebugInfo(Variable, Expression); 6347 // Assume dbg.declare can not currently use DIArgList, i.e. 6348 // it is non-variadic. 6349 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6350 handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression, 6351 DI.getDebugLoc()); 6352 return; 6353 } 6354 case Intrinsic::dbg_label: { 6355 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6356 DILabel *Label = DI.getLabel(); 6357 assert(Label && "Missing label"); 6358 6359 SDDbgLabel *SDV; 6360 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6361 DAG.AddDbgLabel(SDV); 6362 return; 6363 } 6364 case Intrinsic::dbg_assign: { 6365 // Debug intrinsics are handled seperately in assignment tracking mode. 6366 if (AssignmentTrackingEnabled) 6367 return; 6368 // If assignment tracking hasn't been enabled then fall through and treat 6369 // the dbg.assign as a dbg.value. 6370 [[fallthrough]]; 6371 } 6372 case Intrinsic::dbg_value: { 6373 // Debug intrinsics are handled seperately in assignment tracking mode. 6374 if (AssignmentTrackingEnabled) 6375 return; 6376 const DbgValueInst &DI = cast<DbgValueInst>(I); 6377 assert(DI.getVariable() && "Missing variable"); 6378 6379 DILocalVariable *Variable = DI.getVariable(); 6380 DIExpression *Expression = DI.getExpression(); 6381 dropDanglingDebugInfo(Variable, Expression); 6382 6383 if (DI.isKillLocation()) { 6384 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6385 return; 6386 } 6387 6388 SmallVector<Value *, 4> Values(DI.getValues()); 6389 if (Values.empty()) 6390 return; 6391 6392 bool IsVariadic = DI.hasArgList(); 6393 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6394 SDNodeOrder, IsVariadic)) 6395 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic, 6396 DI.getDebugLoc(), SDNodeOrder); 6397 return; 6398 } 6399 6400 case Intrinsic::eh_typeid_for: { 6401 // Find the type id for the given typeinfo. 6402 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6403 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6404 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6405 setValue(&I, Res); 6406 return; 6407 } 6408 6409 case Intrinsic::eh_return_i32: 6410 case Intrinsic::eh_return_i64: 6411 DAG.getMachineFunction().setCallsEHReturn(true); 6412 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6413 MVT::Other, 6414 getControlRoot(), 6415 getValue(I.getArgOperand(0)), 6416 getValue(I.getArgOperand(1)))); 6417 return; 6418 case Intrinsic::eh_unwind_init: 6419 DAG.getMachineFunction().setCallsUnwindInit(true); 6420 return; 6421 case Intrinsic::eh_dwarf_cfa: 6422 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6423 TLI.getPointerTy(DAG.getDataLayout()), 6424 getValue(I.getArgOperand(0)))); 6425 return; 6426 case Intrinsic::eh_sjlj_callsite: { 6427 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6428 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6429 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6430 6431 MMI.setCurrentCallSite(CI->getZExtValue()); 6432 return; 6433 } 6434 case Intrinsic::eh_sjlj_functioncontext: { 6435 // Get and store the index of the function context. 6436 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6437 AllocaInst *FnCtx = 6438 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6439 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6440 MFI.setFunctionContextIndex(FI); 6441 return; 6442 } 6443 case Intrinsic::eh_sjlj_setjmp: { 6444 SDValue Ops[2]; 6445 Ops[0] = getRoot(); 6446 Ops[1] = getValue(I.getArgOperand(0)); 6447 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6448 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6449 setValue(&I, Op.getValue(0)); 6450 DAG.setRoot(Op.getValue(1)); 6451 return; 6452 } 6453 case Intrinsic::eh_sjlj_longjmp: 6454 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6455 getRoot(), getValue(I.getArgOperand(0)))); 6456 return; 6457 case Intrinsic::eh_sjlj_setup_dispatch: 6458 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6459 getRoot())); 6460 return; 6461 case Intrinsic::masked_gather: 6462 visitMaskedGather(I); 6463 return; 6464 case Intrinsic::masked_load: 6465 visitMaskedLoad(I); 6466 return; 6467 case Intrinsic::masked_scatter: 6468 visitMaskedScatter(I); 6469 return; 6470 case Intrinsic::masked_store: 6471 visitMaskedStore(I); 6472 return; 6473 case Intrinsic::masked_expandload: 6474 visitMaskedLoad(I, true /* IsExpanding */); 6475 return; 6476 case Intrinsic::masked_compressstore: 6477 visitMaskedStore(I, true /* IsCompressing */); 6478 return; 6479 case Intrinsic::powi: 6480 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6481 getValue(I.getArgOperand(1)), DAG)); 6482 return; 6483 case Intrinsic::log: 6484 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6485 return; 6486 case Intrinsic::log2: 6487 setValue(&I, 6488 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6489 return; 6490 case Intrinsic::log10: 6491 setValue(&I, 6492 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6493 return; 6494 case Intrinsic::exp: 6495 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6496 return; 6497 case Intrinsic::exp2: 6498 setValue(&I, 6499 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6500 return; 6501 case Intrinsic::pow: 6502 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6503 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6504 return; 6505 case Intrinsic::sqrt: 6506 case Intrinsic::fabs: 6507 case Intrinsic::sin: 6508 case Intrinsic::cos: 6509 case Intrinsic::exp10: 6510 case Intrinsic::floor: 6511 case Intrinsic::ceil: 6512 case Intrinsic::trunc: 6513 case Intrinsic::rint: 6514 case Intrinsic::nearbyint: 6515 case Intrinsic::round: 6516 case Intrinsic::roundeven: 6517 case Intrinsic::canonicalize: { 6518 unsigned Opcode; 6519 switch (Intrinsic) { 6520 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6521 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6522 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6523 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6524 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6525 case Intrinsic::exp10: Opcode = ISD::FEXP10; break; 6526 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6527 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6528 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6529 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6530 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6531 case Intrinsic::round: Opcode = ISD::FROUND; break; 6532 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6533 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6534 } 6535 6536 setValue(&I, DAG.getNode(Opcode, sdl, 6537 getValue(I.getArgOperand(0)).getValueType(), 6538 getValue(I.getArgOperand(0)), Flags)); 6539 return; 6540 } 6541 case Intrinsic::lround: 6542 case Intrinsic::llround: 6543 case Intrinsic::lrint: 6544 case Intrinsic::llrint: { 6545 unsigned Opcode; 6546 switch (Intrinsic) { 6547 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6548 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6549 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6550 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6551 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6552 } 6553 6554 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6555 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6556 getValue(I.getArgOperand(0)))); 6557 return; 6558 } 6559 case Intrinsic::minnum: 6560 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6561 getValue(I.getArgOperand(0)).getValueType(), 6562 getValue(I.getArgOperand(0)), 6563 getValue(I.getArgOperand(1)), Flags)); 6564 return; 6565 case Intrinsic::maxnum: 6566 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6567 getValue(I.getArgOperand(0)).getValueType(), 6568 getValue(I.getArgOperand(0)), 6569 getValue(I.getArgOperand(1)), Flags)); 6570 return; 6571 case Intrinsic::minimum: 6572 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6573 getValue(I.getArgOperand(0)).getValueType(), 6574 getValue(I.getArgOperand(0)), 6575 getValue(I.getArgOperand(1)), Flags)); 6576 return; 6577 case Intrinsic::maximum: 6578 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6579 getValue(I.getArgOperand(0)).getValueType(), 6580 getValue(I.getArgOperand(0)), 6581 getValue(I.getArgOperand(1)), Flags)); 6582 return; 6583 case Intrinsic::copysign: 6584 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6585 getValue(I.getArgOperand(0)).getValueType(), 6586 getValue(I.getArgOperand(0)), 6587 getValue(I.getArgOperand(1)), Flags)); 6588 return; 6589 case Intrinsic::ldexp: 6590 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6591 getValue(I.getArgOperand(0)).getValueType(), 6592 getValue(I.getArgOperand(0)), 6593 getValue(I.getArgOperand(1)), Flags)); 6594 return; 6595 case Intrinsic::frexp: { 6596 SmallVector<EVT, 2> ValueVTs; 6597 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 6598 SDVTList VTs = DAG.getVTList(ValueVTs); 6599 setValue(&I, 6600 DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0)))); 6601 return; 6602 } 6603 case Intrinsic::arithmetic_fence: { 6604 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6605 getValue(I.getArgOperand(0)).getValueType(), 6606 getValue(I.getArgOperand(0)), Flags)); 6607 return; 6608 } 6609 case Intrinsic::fma: 6610 setValue(&I, DAG.getNode( 6611 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6612 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6613 getValue(I.getArgOperand(2)), Flags)); 6614 return; 6615 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6616 case Intrinsic::INTRINSIC: 6617 #include "llvm/IR/ConstrainedOps.def" 6618 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6619 return; 6620 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6621 #include "llvm/IR/VPIntrinsics.def" 6622 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6623 return; 6624 case Intrinsic::fptrunc_round: { 6625 // Get the last argument, the metadata and convert it to an integer in the 6626 // call 6627 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6628 std::optional<RoundingMode> RoundMode = 6629 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6630 6631 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6632 6633 // Propagate fast-math-flags from IR to node(s). 6634 SDNodeFlags Flags; 6635 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6636 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6637 6638 SDValue Result; 6639 Result = DAG.getNode( 6640 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6641 DAG.getTargetConstant((int)*RoundMode, sdl, 6642 TLI.getPointerTy(DAG.getDataLayout()))); 6643 setValue(&I, Result); 6644 6645 return; 6646 } 6647 case Intrinsic::fmuladd: { 6648 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6649 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6650 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6651 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6652 getValue(I.getArgOperand(0)).getValueType(), 6653 getValue(I.getArgOperand(0)), 6654 getValue(I.getArgOperand(1)), 6655 getValue(I.getArgOperand(2)), Flags)); 6656 } else { 6657 // TODO: Intrinsic calls should have fast-math-flags. 6658 SDValue Mul = DAG.getNode( 6659 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6660 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6661 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6662 getValue(I.getArgOperand(0)).getValueType(), 6663 Mul, getValue(I.getArgOperand(2)), Flags); 6664 setValue(&I, Add); 6665 } 6666 return; 6667 } 6668 case Intrinsic::convert_to_fp16: 6669 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6670 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6671 getValue(I.getArgOperand(0)), 6672 DAG.getTargetConstant(0, sdl, 6673 MVT::i32)))); 6674 return; 6675 case Intrinsic::convert_from_fp16: 6676 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6677 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6678 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6679 getValue(I.getArgOperand(0))))); 6680 return; 6681 case Intrinsic::fptosi_sat: { 6682 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6683 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6684 getValue(I.getArgOperand(0)), 6685 DAG.getValueType(VT.getScalarType()))); 6686 return; 6687 } 6688 case Intrinsic::fptoui_sat: { 6689 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6690 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6691 getValue(I.getArgOperand(0)), 6692 DAG.getValueType(VT.getScalarType()))); 6693 return; 6694 } 6695 case Intrinsic::set_rounding: 6696 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6697 {getRoot(), getValue(I.getArgOperand(0))}); 6698 setValue(&I, Res); 6699 DAG.setRoot(Res.getValue(0)); 6700 return; 6701 case Intrinsic::is_fpclass: { 6702 const DataLayout DLayout = DAG.getDataLayout(); 6703 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6704 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6705 FPClassTest Test = static_cast<FPClassTest>( 6706 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6707 MachineFunction &MF = DAG.getMachineFunction(); 6708 const Function &F = MF.getFunction(); 6709 SDValue Op = getValue(I.getArgOperand(0)); 6710 SDNodeFlags Flags; 6711 Flags.setNoFPExcept( 6712 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6713 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6714 // expansion can use illegal types. Making expansion early allows 6715 // legalizing these types prior to selection. 6716 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6717 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6718 setValue(&I, Result); 6719 return; 6720 } 6721 6722 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6723 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6724 setValue(&I, V); 6725 return; 6726 } 6727 case Intrinsic::get_fpenv: { 6728 const DataLayout DLayout = DAG.getDataLayout(); 6729 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6730 Align TempAlign = DAG.getEVTAlign(EnvVT); 6731 SDValue Chain = getRoot(); 6732 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6733 // and temporary storage in stack. 6734 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6735 Res = DAG.getNode( 6736 ISD::GET_FPENV, sdl, 6737 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6738 MVT::Other), 6739 Chain); 6740 } else { 6741 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6742 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6743 auto MPI = 6744 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6745 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6746 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6747 TempAlign); 6748 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6749 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6750 } 6751 setValue(&I, Res); 6752 DAG.setRoot(Res.getValue(1)); 6753 return; 6754 } 6755 case Intrinsic::set_fpenv: { 6756 const DataLayout DLayout = DAG.getDataLayout(); 6757 SDValue Env = getValue(I.getArgOperand(0)); 6758 EVT EnvVT = Env.getValueType(); 6759 Align TempAlign = DAG.getEVTAlign(EnvVT); 6760 SDValue Chain = getRoot(); 6761 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6762 // environment from memory. 6763 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6764 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6765 } else { 6766 // Allocate space in stack, copy environment bits into it and use this 6767 // memory in SET_FPENV_MEM. 6768 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6769 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6770 auto MPI = 6771 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6772 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6773 MachineMemOperand::MOStore); 6774 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6775 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6776 TempAlign); 6777 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6778 } 6779 DAG.setRoot(Chain); 6780 return; 6781 } 6782 case Intrinsic::reset_fpenv: 6783 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6784 return; 6785 case Intrinsic::get_fpmode: 6786 Res = DAG.getNode( 6787 ISD::GET_FPMODE, sdl, 6788 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6789 MVT::Other), 6790 DAG.getRoot()); 6791 setValue(&I, Res); 6792 DAG.setRoot(Res.getValue(1)); 6793 return; 6794 case Intrinsic::set_fpmode: 6795 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()}, 6796 getValue(I.getArgOperand(0))); 6797 DAG.setRoot(Res); 6798 return; 6799 case Intrinsic::reset_fpmode: { 6800 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot()); 6801 DAG.setRoot(Res); 6802 return; 6803 } 6804 case Intrinsic::pcmarker: { 6805 SDValue Tmp = getValue(I.getArgOperand(0)); 6806 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6807 return; 6808 } 6809 case Intrinsic::readcyclecounter: { 6810 SDValue Op = getRoot(); 6811 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6812 DAG.getVTList(MVT::i64, MVT::Other), Op); 6813 setValue(&I, Res); 6814 DAG.setRoot(Res.getValue(1)); 6815 return; 6816 } 6817 case Intrinsic::readsteadycounter: { 6818 SDValue Op = getRoot(); 6819 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl, 6820 DAG.getVTList(MVT::i64, MVT::Other), Op); 6821 setValue(&I, Res); 6822 DAG.setRoot(Res.getValue(1)); 6823 return; 6824 } 6825 case Intrinsic::bitreverse: 6826 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6827 getValue(I.getArgOperand(0)).getValueType(), 6828 getValue(I.getArgOperand(0)))); 6829 return; 6830 case Intrinsic::bswap: 6831 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6832 getValue(I.getArgOperand(0)).getValueType(), 6833 getValue(I.getArgOperand(0)))); 6834 return; 6835 case Intrinsic::cttz: { 6836 SDValue Arg = getValue(I.getArgOperand(0)); 6837 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6838 EVT Ty = Arg.getValueType(); 6839 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6840 sdl, Ty, Arg)); 6841 return; 6842 } 6843 case Intrinsic::ctlz: { 6844 SDValue Arg = getValue(I.getArgOperand(0)); 6845 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6846 EVT Ty = Arg.getValueType(); 6847 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6848 sdl, Ty, Arg)); 6849 return; 6850 } 6851 case Intrinsic::ctpop: { 6852 SDValue Arg = getValue(I.getArgOperand(0)); 6853 EVT Ty = Arg.getValueType(); 6854 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6855 return; 6856 } 6857 case Intrinsic::fshl: 6858 case Intrinsic::fshr: { 6859 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6860 SDValue X = getValue(I.getArgOperand(0)); 6861 SDValue Y = getValue(I.getArgOperand(1)); 6862 SDValue Z = getValue(I.getArgOperand(2)); 6863 EVT VT = X.getValueType(); 6864 6865 if (X == Y) { 6866 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6867 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6868 } else { 6869 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6870 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6871 } 6872 return; 6873 } 6874 case Intrinsic::sadd_sat: { 6875 SDValue Op1 = getValue(I.getArgOperand(0)); 6876 SDValue Op2 = getValue(I.getArgOperand(1)); 6877 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6878 return; 6879 } 6880 case Intrinsic::uadd_sat: { 6881 SDValue Op1 = getValue(I.getArgOperand(0)); 6882 SDValue Op2 = getValue(I.getArgOperand(1)); 6883 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6884 return; 6885 } 6886 case Intrinsic::ssub_sat: { 6887 SDValue Op1 = getValue(I.getArgOperand(0)); 6888 SDValue Op2 = getValue(I.getArgOperand(1)); 6889 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6890 return; 6891 } 6892 case Intrinsic::usub_sat: { 6893 SDValue Op1 = getValue(I.getArgOperand(0)); 6894 SDValue Op2 = getValue(I.getArgOperand(1)); 6895 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6896 return; 6897 } 6898 case Intrinsic::sshl_sat: { 6899 SDValue Op1 = getValue(I.getArgOperand(0)); 6900 SDValue Op2 = getValue(I.getArgOperand(1)); 6901 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6902 return; 6903 } 6904 case Intrinsic::ushl_sat: { 6905 SDValue Op1 = getValue(I.getArgOperand(0)); 6906 SDValue Op2 = getValue(I.getArgOperand(1)); 6907 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6908 return; 6909 } 6910 case Intrinsic::smul_fix: 6911 case Intrinsic::umul_fix: 6912 case Intrinsic::smul_fix_sat: 6913 case Intrinsic::umul_fix_sat: { 6914 SDValue Op1 = getValue(I.getArgOperand(0)); 6915 SDValue Op2 = getValue(I.getArgOperand(1)); 6916 SDValue Op3 = getValue(I.getArgOperand(2)); 6917 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6918 Op1.getValueType(), Op1, Op2, Op3)); 6919 return; 6920 } 6921 case Intrinsic::sdiv_fix: 6922 case Intrinsic::udiv_fix: 6923 case Intrinsic::sdiv_fix_sat: 6924 case Intrinsic::udiv_fix_sat: { 6925 SDValue Op1 = getValue(I.getArgOperand(0)); 6926 SDValue Op2 = getValue(I.getArgOperand(1)); 6927 SDValue Op3 = getValue(I.getArgOperand(2)); 6928 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6929 Op1, Op2, Op3, DAG, TLI)); 6930 return; 6931 } 6932 case Intrinsic::smax: { 6933 SDValue Op1 = getValue(I.getArgOperand(0)); 6934 SDValue Op2 = getValue(I.getArgOperand(1)); 6935 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6936 return; 6937 } 6938 case Intrinsic::smin: { 6939 SDValue Op1 = getValue(I.getArgOperand(0)); 6940 SDValue Op2 = getValue(I.getArgOperand(1)); 6941 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6942 return; 6943 } 6944 case Intrinsic::umax: { 6945 SDValue Op1 = getValue(I.getArgOperand(0)); 6946 SDValue Op2 = getValue(I.getArgOperand(1)); 6947 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6948 return; 6949 } 6950 case Intrinsic::umin: { 6951 SDValue Op1 = getValue(I.getArgOperand(0)); 6952 SDValue Op2 = getValue(I.getArgOperand(1)); 6953 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6954 return; 6955 } 6956 case Intrinsic::abs: { 6957 // TODO: Preserve "int min is poison" arg in SDAG? 6958 SDValue Op1 = getValue(I.getArgOperand(0)); 6959 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6960 return; 6961 } 6962 case Intrinsic::stacksave: { 6963 SDValue Op = getRoot(); 6964 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6965 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6966 setValue(&I, Res); 6967 DAG.setRoot(Res.getValue(1)); 6968 return; 6969 } 6970 case Intrinsic::stackrestore: 6971 Res = getValue(I.getArgOperand(0)); 6972 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6973 return; 6974 case Intrinsic::get_dynamic_area_offset: { 6975 SDValue Op = getRoot(); 6976 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6977 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6978 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6979 // target. 6980 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6981 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6982 " intrinsic!"); 6983 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6984 Op); 6985 DAG.setRoot(Op); 6986 setValue(&I, Res); 6987 return; 6988 } 6989 case Intrinsic::stackguard: { 6990 MachineFunction &MF = DAG.getMachineFunction(); 6991 const Module &M = *MF.getFunction().getParent(); 6992 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6993 SDValue Chain = getRoot(); 6994 if (TLI.useLoadStackGuardNode()) { 6995 Res = getLoadStackGuard(DAG, sdl, Chain); 6996 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy); 6997 } else { 6998 const Value *Global = TLI.getSDagStackGuard(M); 6999 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 7000 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 7001 MachinePointerInfo(Global, 0), Align, 7002 MachineMemOperand::MOVolatile); 7003 } 7004 if (TLI.useStackGuardXorFP()) 7005 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 7006 DAG.setRoot(Chain); 7007 setValue(&I, Res); 7008 return; 7009 } 7010 case Intrinsic::stackprotector: { 7011 // Emit code into the DAG to store the stack guard onto the stack. 7012 MachineFunction &MF = DAG.getMachineFunction(); 7013 MachineFrameInfo &MFI = MF.getFrameInfo(); 7014 SDValue Src, Chain = getRoot(); 7015 7016 if (TLI.useLoadStackGuardNode()) 7017 Src = getLoadStackGuard(DAG, sdl, Chain); 7018 else 7019 Src = getValue(I.getArgOperand(0)); // The guard's value. 7020 7021 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 7022 7023 int FI = FuncInfo.StaticAllocaMap[Slot]; 7024 MFI.setStackProtectorIndex(FI); 7025 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 7026 7027 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 7028 7029 // Store the stack protector onto the stack. 7030 Res = DAG.getStore( 7031 Chain, sdl, Src, FIN, 7032 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 7033 MaybeAlign(), MachineMemOperand::MOVolatile); 7034 setValue(&I, Res); 7035 DAG.setRoot(Res); 7036 return; 7037 } 7038 case Intrinsic::objectsize: 7039 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 7040 7041 case Intrinsic::is_constant: 7042 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 7043 7044 case Intrinsic::annotation: 7045 case Intrinsic::ptr_annotation: 7046 case Intrinsic::launder_invariant_group: 7047 case Intrinsic::strip_invariant_group: 7048 // Drop the intrinsic, but forward the value 7049 setValue(&I, getValue(I.getOperand(0))); 7050 return; 7051 7052 case Intrinsic::assume: 7053 case Intrinsic::experimental_noalias_scope_decl: 7054 case Intrinsic::var_annotation: 7055 case Intrinsic::sideeffect: 7056 // Discard annotate attributes, noalias scope declarations, assumptions, and 7057 // artificial side-effects. 7058 return; 7059 7060 case Intrinsic::codeview_annotation: { 7061 // Emit a label associated with this metadata. 7062 MachineFunction &MF = DAG.getMachineFunction(); 7063 MCSymbol *Label = 7064 MF.getMMI().getContext().createTempSymbol("annotation", true); 7065 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 7066 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 7067 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 7068 DAG.setRoot(Res); 7069 return; 7070 } 7071 7072 case Intrinsic::init_trampoline: { 7073 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 7074 7075 SDValue Ops[6]; 7076 Ops[0] = getRoot(); 7077 Ops[1] = getValue(I.getArgOperand(0)); 7078 Ops[2] = getValue(I.getArgOperand(1)); 7079 Ops[3] = getValue(I.getArgOperand(2)); 7080 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 7081 Ops[5] = DAG.getSrcValue(F); 7082 7083 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 7084 7085 DAG.setRoot(Res); 7086 return; 7087 } 7088 case Intrinsic::adjust_trampoline: 7089 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 7090 TLI.getPointerTy(DAG.getDataLayout()), 7091 getValue(I.getArgOperand(0)))); 7092 return; 7093 case Intrinsic::gcroot: { 7094 assert(DAG.getMachineFunction().getFunction().hasGC() && 7095 "only valid in functions with gc specified, enforced by Verifier"); 7096 assert(GFI && "implied by previous"); 7097 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 7098 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 7099 7100 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 7101 GFI->addStackRoot(FI->getIndex(), TypeMap); 7102 return; 7103 } 7104 case Intrinsic::gcread: 7105 case Intrinsic::gcwrite: 7106 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 7107 case Intrinsic::get_rounding: 7108 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 7109 setValue(&I, Res); 7110 DAG.setRoot(Res.getValue(1)); 7111 return; 7112 7113 case Intrinsic::expect: 7114 // Just replace __builtin_expect(exp, c) with EXP. 7115 setValue(&I, getValue(I.getArgOperand(0))); 7116 return; 7117 7118 case Intrinsic::ubsantrap: 7119 case Intrinsic::debugtrap: 7120 case Intrinsic::trap: { 7121 StringRef TrapFuncName = 7122 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 7123 if (TrapFuncName.empty()) { 7124 switch (Intrinsic) { 7125 case Intrinsic::trap: 7126 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 7127 break; 7128 case Intrinsic::debugtrap: 7129 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 7130 break; 7131 case Intrinsic::ubsantrap: 7132 DAG.setRoot(DAG.getNode( 7133 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 7134 DAG.getTargetConstant( 7135 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 7136 MVT::i32))); 7137 break; 7138 default: llvm_unreachable("unknown trap intrinsic"); 7139 } 7140 return; 7141 } 7142 TargetLowering::ArgListTy Args; 7143 if (Intrinsic == Intrinsic::ubsantrap) { 7144 Args.push_back(TargetLoweringBase::ArgListEntry()); 7145 Args[0].Val = I.getArgOperand(0); 7146 Args[0].Node = getValue(Args[0].Val); 7147 Args[0].Ty = Args[0].Val->getType(); 7148 } 7149 7150 TargetLowering::CallLoweringInfo CLI(DAG); 7151 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 7152 CallingConv::C, I.getType(), 7153 DAG.getExternalSymbol(TrapFuncName.data(), 7154 TLI.getPointerTy(DAG.getDataLayout())), 7155 std::move(Args)); 7156 7157 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7158 DAG.setRoot(Result.second); 7159 return; 7160 } 7161 7162 case Intrinsic::uadd_with_overflow: 7163 case Intrinsic::sadd_with_overflow: 7164 case Intrinsic::usub_with_overflow: 7165 case Intrinsic::ssub_with_overflow: 7166 case Intrinsic::umul_with_overflow: 7167 case Intrinsic::smul_with_overflow: { 7168 ISD::NodeType Op; 7169 switch (Intrinsic) { 7170 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7171 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7172 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7173 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7174 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7175 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7176 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7177 } 7178 SDValue Op1 = getValue(I.getArgOperand(0)); 7179 SDValue Op2 = getValue(I.getArgOperand(1)); 7180 7181 EVT ResultVT = Op1.getValueType(); 7182 EVT OverflowVT = MVT::i1; 7183 if (ResultVT.isVector()) 7184 OverflowVT = EVT::getVectorVT( 7185 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7186 7187 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7188 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7189 return; 7190 } 7191 case Intrinsic::prefetch: { 7192 SDValue Ops[5]; 7193 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7194 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7195 Ops[0] = DAG.getRoot(); 7196 Ops[1] = getValue(I.getArgOperand(0)); 7197 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 7198 MVT::i32); 7199 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl, 7200 MVT::i32); 7201 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl, 7202 MVT::i32); 7203 SDValue Result = DAG.getMemIntrinsicNode( 7204 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7205 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7206 /* align */ std::nullopt, Flags); 7207 7208 // Chain the prefetch in parallel with any pending loads, to stay out of 7209 // the way of later optimizations. 7210 PendingLoads.push_back(Result); 7211 Result = getRoot(); 7212 DAG.setRoot(Result); 7213 return; 7214 } 7215 case Intrinsic::lifetime_start: 7216 case Intrinsic::lifetime_end: { 7217 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7218 // Stack coloring is not enabled in O0, discard region information. 7219 if (TM.getOptLevel() == CodeGenOptLevel::None) 7220 return; 7221 7222 const int64_t ObjectSize = 7223 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7224 Value *const ObjectPtr = I.getArgOperand(1); 7225 SmallVector<const Value *, 4> Allocas; 7226 getUnderlyingObjects(ObjectPtr, Allocas); 7227 7228 for (const Value *Alloca : Allocas) { 7229 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7230 7231 // Could not find an Alloca. 7232 if (!LifetimeObject) 7233 continue; 7234 7235 // First check that the Alloca is static, otherwise it won't have a 7236 // valid frame index. 7237 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7238 if (SI == FuncInfo.StaticAllocaMap.end()) 7239 return; 7240 7241 const int FrameIndex = SI->second; 7242 int64_t Offset; 7243 if (GetPointerBaseWithConstantOffset( 7244 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7245 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7246 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7247 Offset); 7248 DAG.setRoot(Res); 7249 } 7250 return; 7251 } 7252 case Intrinsic::pseudoprobe: { 7253 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7254 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7255 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7256 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7257 DAG.setRoot(Res); 7258 return; 7259 } 7260 case Intrinsic::invariant_start: 7261 // Discard region information. 7262 setValue(&I, 7263 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7264 return; 7265 case Intrinsic::invariant_end: 7266 // Discard region information. 7267 return; 7268 case Intrinsic::clear_cache: 7269 /// FunctionName may be null. 7270 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7271 lowerCallToExternalSymbol(I, FunctionName); 7272 return; 7273 case Intrinsic::donothing: 7274 case Intrinsic::seh_try_begin: 7275 case Intrinsic::seh_scope_begin: 7276 case Intrinsic::seh_try_end: 7277 case Intrinsic::seh_scope_end: 7278 // ignore 7279 return; 7280 case Intrinsic::experimental_stackmap: 7281 visitStackmap(I); 7282 return; 7283 case Intrinsic::experimental_patchpoint_void: 7284 case Intrinsic::experimental_patchpoint_i64: 7285 visitPatchpoint(I); 7286 return; 7287 case Intrinsic::experimental_gc_statepoint: 7288 LowerStatepoint(cast<GCStatepointInst>(I)); 7289 return; 7290 case Intrinsic::experimental_gc_result: 7291 visitGCResult(cast<GCResultInst>(I)); 7292 return; 7293 case Intrinsic::experimental_gc_relocate: 7294 visitGCRelocate(cast<GCRelocateInst>(I)); 7295 return; 7296 case Intrinsic::instrprof_cover: 7297 llvm_unreachable("instrprof failed to lower a cover"); 7298 case Intrinsic::instrprof_increment: 7299 llvm_unreachable("instrprof failed to lower an increment"); 7300 case Intrinsic::instrprof_timestamp: 7301 llvm_unreachable("instrprof failed to lower a timestamp"); 7302 case Intrinsic::instrprof_value_profile: 7303 llvm_unreachable("instrprof failed to lower a value profiling call"); 7304 case Intrinsic::instrprof_mcdc_parameters: 7305 llvm_unreachable("instrprof failed to lower mcdc parameters"); 7306 case Intrinsic::instrprof_mcdc_tvbitmap_update: 7307 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update"); 7308 case Intrinsic::instrprof_mcdc_condbitmap_update: 7309 llvm_unreachable("instrprof failed to lower an mcdc condbitmap update"); 7310 case Intrinsic::localescape: { 7311 MachineFunction &MF = DAG.getMachineFunction(); 7312 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7313 7314 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7315 // is the same on all targets. 7316 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7317 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7318 if (isa<ConstantPointerNull>(Arg)) 7319 continue; // Skip null pointers. They represent a hole in index space. 7320 AllocaInst *Slot = cast<AllocaInst>(Arg); 7321 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7322 "can only escape static allocas"); 7323 int FI = FuncInfo.StaticAllocaMap[Slot]; 7324 MCSymbol *FrameAllocSym = 7325 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7326 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7328 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7329 .addSym(FrameAllocSym) 7330 .addFrameIndex(FI); 7331 } 7332 7333 return; 7334 } 7335 7336 case Intrinsic::localrecover: { 7337 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7338 MachineFunction &MF = DAG.getMachineFunction(); 7339 7340 // Get the symbol that defines the frame offset. 7341 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7342 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7343 unsigned IdxVal = 7344 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7345 MCSymbol *FrameAllocSym = 7346 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7347 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7348 7349 Value *FP = I.getArgOperand(1); 7350 SDValue FPVal = getValue(FP); 7351 EVT PtrVT = FPVal.getValueType(); 7352 7353 // Create a MCSymbol for the label to avoid any target lowering 7354 // that would make this PC relative. 7355 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7356 SDValue OffsetVal = 7357 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7358 7359 // Add the offset to the FP. 7360 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7361 setValue(&I, Add); 7362 7363 return; 7364 } 7365 7366 case Intrinsic::eh_exceptionpointer: 7367 case Intrinsic::eh_exceptioncode: { 7368 // Get the exception pointer vreg, copy from it, and resize it to fit. 7369 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7370 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7371 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7372 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7373 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7374 if (Intrinsic == Intrinsic::eh_exceptioncode) 7375 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7376 setValue(&I, N); 7377 return; 7378 } 7379 case Intrinsic::xray_customevent: { 7380 // Here we want to make sure that the intrinsic behaves as if it has a 7381 // specific calling convention. 7382 const auto &Triple = DAG.getTarget().getTargetTriple(); 7383 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7384 return; 7385 7386 SmallVector<SDValue, 8> Ops; 7387 7388 // We want to say that we always want the arguments in registers. 7389 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7390 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7391 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7392 SDValue Chain = getRoot(); 7393 Ops.push_back(LogEntryVal); 7394 Ops.push_back(StrSizeVal); 7395 Ops.push_back(Chain); 7396 7397 // We need to enforce the calling convention for the callsite, so that 7398 // argument ordering is enforced correctly, and that register allocation can 7399 // see that some registers may be assumed clobbered and have to preserve 7400 // them across calls to the intrinsic. 7401 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7402 sdl, NodeTys, Ops); 7403 SDValue patchableNode = SDValue(MN, 0); 7404 DAG.setRoot(patchableNode); 7405 setValue(&I, patchableNode); 7406 return; 7407 } 7408 case Intrinsic::xray_typedevent: { 7409 // Here we want to make sure that the intrinsic behaves as if it has a 7410 // specific calling convention. 7411 const auto &Triple = DAG.getTarget().getTargetTriple(); 7412 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7413 return; 7414 7415 SmallVector<SDValue, 8> Ops; 7416 7417 // We want to say that we always want the arguments in registers. 7418 // It's unclear to me how manipulating the selection DAG here forces callers 7419 // to provide arguments in registers instead of on the stack. 7420 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7421 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7422 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7423 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7424 SDValue Chain = getRoot(); 7425 Ops.push_back(LogTypeId); 7426 Ops.push_back(LogEntryVal); 7427 Ops.push_back(StrSizeVal); 7428 Ops.push_back(Chain); 7429 7430 // We need to enforce the calling convention for the callsite, so that 7431 // argument ordering is enforced correctly, and that register allocation can 7432 // see that some registers may be assumed clobbered and have to preserve 7433 // them across calls to the intrinsic. 7434 MachineSDNode *MN = DAG.getMachineNode( 7435 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7436 SDValue patchableNode = SDValue(MN, 0); 7437 DAG.setRoot(patchableNode); 7438 setValue(&I, patchableNode); 7439 return; 7440 } 7441 case Intrinsic::experimental_deoptimize: 7442 LowerDeoptimizeCall(&I); 7443 return; 7444 case Intrinsic::experimental_stepvector: 7445 visitStepVector(I); 7446 return; 7447 case Intrinsic::vector_reduce_fadd: 7448 case Intrinsic::vector_reduce_fmul: 7449 case Intrinsic::vector_reduce_add: 7450 case Intrinsic::vector_reduce_mul: 7451 case Intrinsic::vector_reduce_and: 7452 case Intrinsic::vector_reduce_or: 7453 case Intrinsic::vector_reduce_xor: 7454 case Intrinsic::vector_reduce_smax: 7455 case Intrinsic::vector_reduce_smin: 7456 case Intrinsic::vector_reduce_umax: 7457 case Intrinsic::vector_reduce_umin: 7458 case Intrinsic::vector_reduce_fmax: 7459 case Intrinsic::vector_reduce_fmin: 7460 case Intrinsic::vector_reduce_fmaximum: 7461 case Intrinsic::vector_reduce_fminimum: 7462 visitVectorReduce(I, Intrinsic); 7463 return; 7464 7465 case Intrinsic::icall_branch_funnel: { 7466 SmallVector<SDValue, 16> Ops; 7467 Ops.push_back(getValue(I.getArgOperand(0))); 7468 7469 int64_t Offset; 7470 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7471 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7472 if (!Base) 7473 report_fatal_error( 7474 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7475 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7476 7477 struct BranchFunnelTarget { 7478 int64_t Offset; 7479 SDValue Target; 7480 }; 7481 SmallVector<BranchFunnelTarget, 8> Targets; 7482 7483 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7484 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7485 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7486 if (ElemBase != Base) 7487 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7488 "to the same GlobalValue"); 7489 7490 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7491 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7492 if (!GA) 7493 report_fatal_error( 7494 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7495 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7496 GA->getGlobal(), sdl, Val.getValueType(), 7497 GA->getOffset())}); 7498 } 7499 llvm::sort(Targets, 7500 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7501 return T1.Offset < T2.Offset; 7502 }); 7503 7504 for (auto &T : Targets) { 7505 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7506 Ops.push_back(T.Target); 7507 } 7508 7509 Ops.push_back(DAG.getRoot()); // Chain 7510 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7511 MVT::Other, Ops), 7512 0); 7513 DAG.setRoot(N); 7514 setValue(&I, N); 7515 HasTailCall = true; 7516 return; 7517 } 7518 7519 case Intrinsic::wasm_landingpad_index: 7520 // Information this intrinsic contained has been transferred to 7521 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7522 // delete it now. 7523 return; 7524 7525 case Intrinsic::aarch64_settag: 7526 case Intrinsic::aarch64_settag_zero: { 7527 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7528 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7529 SDValue Val = TSI.EmitTargetCodeForSetTag( 7530 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7531 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7532 ZeroMemory); 7533 DAG.setRoot(Val); 7534 setValue(&I, Val); 7535 return; 7536 } 7537 case Intrinsic::amdgcn_cs_chain: { 7538 assert(I.arg_size() == 5 && "Additional args not supported yet"); 7539 assert(cast<ConstantInt>(I.getOperand(4))->isZero() && 7540 "Non-zero flags not supported yet"); 7541 7542 // At this point we don't care if it's amdgpu_cs_chain or 7543 // amdgpu_cs_chain_preserve. 7544 CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain; 7545 7546 Type *RetTy = I.getType(); 7547 assert(RetTy->isVoidTy() && "Should not return"); 7548 7549 SDValue Callee = getValue(I.getOperand(0)); 7550 7551 // We only have 2 actual args: one for the SGPRs and one for the VGPRs. 7552 // We'll also tack the value of the EXEC mask at the end. 7553 TargetLowering::ArgListTy Args; 7554 Args.reserve(3); 7555 7556 for (unsigned Idx : {2, 3, 1}) { 7557 TargetLowering::ArgListEntry Arg; 7558 Arg.Node = getValue(I.getOperand(Idx)); 7559 Arg.Ty = I.getOperand(Idx)->getType(); 7560 Arg.setAttributes(&I, Idx); 7561 Args.push_back(Arg); 7562 } 7563 7564 assert(Args[0].IsInReg && "SGPR args should be marked inreg"); 7565 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg"); 7566 Args[2].IsInReg = true; // EXEC should be inreg 7567 7568 TargetLowering::CallLoweringInfo CLI(DAG); 7569 CLI.setDebugLoc(getCurSDLoc()) 7570 .setChain(getRoot()) 7571 .setCallee(CC, RetTy, Callee, std::move(Args)) 7572 .setNoReturn(true) 7573 .setTailCall(true) 7574 .setConvergent(I.isConvergent()); 7575 CLI.CB = &I; 7576 std::pair<SDValue, SDValue> Result = 7577 lowerInvokable(CLI, /*EHPadBB*/ nullptr); 7578 (void)Result; 7579 assert(!Result.first.getNode() && !Result.second.getNode() && 7580 "Should've lowered as tail call"); 7581 7582 HasTailCall = true; 7583 return; 7584 } 7585 case Intrinsic::ptrmask: { 7586 SDValue Ptr = getValue(I.getOperand(0)); 7587 SDValue Mask = getValue(I.getOperand(1)); 7588 7589 EVT PtrVT = Ptr.getValueType(); 7590 assert(PtrVT == Mask.getValueType() && 7591 "Pointers with different index type are not supported by SDAG"); 7592 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask)); 7593 return; 7594 } 7595 case Intrinsic::threadlocal_address: { 7596 setValue(&I, getValue(I.getOperand(0))); 7597 return; 7598 } 7599 case Intrinsic::get_active_lane_mask: { 7600 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7601 SDValue Index = getValue(I.getOperand(0)); 7602 EVT ElementVT = Index.getValueType(); 7603 7604 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7605 visitTargetIntrinsic(I, Intrinsic); 7606 return; 7607 } 7608 7609 SDValue TripCount = getValue(I.getOperand(1)); 7610 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT, 7611 CCVT.getVectorElementCount()); 7612 7613 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7614 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7615 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7616 SDValue VectorInduction = DAG.getNode( 7617 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7618 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7619 VectorTripCount, ISD::CondCode::SETULT); 7620 setValue(&I, SetCC); 7621 return; 7622 } 7623 case Intrinsic::experimental_get_vector_length: { 7624 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7625 "Expected positive VF"); 7626 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7627 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7628 7629 SDValue Count = getValue(I.getOperand(0)); 7630 EVT CountVT = Count.getValueType(); 7631 7632 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7633 visitTargetIntrinsic(I, Intrinsic); 7634 return; 7635 } 7636 7637 // Expand to a umin between the trip count and the maximum elements the type 7638 // can hold. 7639 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7640 7641 // Extend the trip count to at least the result VT. 7642 if (CountVT.bitsLT(VT)) { 7643 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7644 CountVT = VT; 7645 } 7646 7647 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7648 ElementCount::get(VF, IsScalable)); 7649 7650 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7651 // Clip to the result type if needed. 7652 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7653 7654 setValue(&I, Trunc); 7655 return; 7656 } 7657 case Intrinsic::experimental_cttz_elts: { 7658 auto DL = getCurSDLoc(); 7659 SDValue Op = getValue(I.getOperand(0)); 7660 EVT OpVT = Op.getValueType(); 7661 7662 if (!TLI.shouldExpandCttzElements(OpVT)) { 7663 visitTargetIntrinsic(I, Intrinsic); 7664 return; 7665 } 7666 7667 if (OpVT.getScalarType() != MVT::i1) { 7668 // Compare the input vector elements to zero & use to count trailing zeros 7669 SDValue AllZero = DAG.getConstant(0, DL, OpVT); 7670 OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 7671 OpVT.getVectorElementCount()); 7672 Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE); 7673 } 7674 7675 // Find the smallest "sensible" element type to use for the expansion. 7676 ConstantRange CR( 7677 APInt(64, OpVT.getVectorElementCount().getKnownMinValue())); 7678 if (OpVT.isScalableVT()) 7679 CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64)); 7680 7681 // If the zero-is-poison flag is set, we can assume the upper limit 7682 // of the result is VF-1. 7683 if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero()) 7684 CR = CR.subtract(APInt(64, 1)); 7685 7686 unsigned EltWidth = I.getType()->getScalarSizeInBits(); 7687 EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits()); 7688 EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8); 7689 7690 MVT NewEltTy = MVT::getIntegerVT(EltWidth); 7691 7692 // Create the new vector type & get the vector length 7693 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy, 7694 OpVT.getVectorElementCount()); 7695 7696 SDValue VL = 7697 DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount()); 7698 7699 SDValue StepVec = DAG.getStepVector(DL, NewVT); 7700 SDValue SplatVL = DAG.getSplat(NewVT, DL, VL); 7701 SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec); 7702 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op); 7703 SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext); 7704 SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And); 7705 SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max); 7706 7707 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7708 SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy); 7709 7710 setValue(&I, Ret); 7711 return; 7712 } 7713 case Intrinsic::vector_insert: { 7714 SDValue Vec = getValue(I.getOperand(0)); 7715 SDValue SubVec = getValue(I.getOperand(1)); 7716 SDValue Index = getValue(I.getOperand(2)); 7717 7718 // The intrinsic's index type is i64, but the SDNode requires an index type 7719 // suitable for the target. Convert the index as required. 7720 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7721 if (Index.getValueType() != VectorIdxTy) 7722 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7723 7724 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7725 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7726 Index)); 7727 return; 7728 } 7729 case Intrinsic::vector_extract: { 7730 SDValue Vec = getValue(I.getOperand(0)); 7731 SDValue Index = getValue(I.getOperand(1)); 7732 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7733 7734 // The intrinsic's index type is i64, but the SDNode requires an index type 7735 // suitable for the target. Convert the index as required. 7736 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7737 if (Index.getValueType() != VectorIdxTy) 7738 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl); 7739 7740 setValue(&I, 7741 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7742 return; 7743 } 7744 case Intrinsic::experimental_vector_reverse: 7745 visitVectorReverse(I); 7746 return; 7747 case Intrinsic::experimental_vector_splice: 7748 visitVectorSplice(I); 7749 return; 7750 case Intrinsic::callbr_landingpad: 7751 visitCallBrLandingPad(I); 7752 return; 7753 case Intrinsic::experimental_vector_interleave2: 7754 visitVectorInterleave(I); 7755 return; 7756 case Intrinsic::experimental_vector_deinterleave2: 7757 visitVectorDeinterleave(I); 7758 return; 7759 case Intrinsic::experimental_convergence_anchor: 7760 case Intrinsic::experimental_convergence_entry: 7761 case Intrinsic::experimental_convergence_loop: 7762 visitConvergenceControl(I, Intrinsic); 7763 } 7764 } 7765 7766 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7767 const ConstrainedFPIntrinsic &FPI) { 7768 SDLoc sdl = getCurSDLoc(); 7769 7770 // We do not need to serialize constrained FP intrinsics against 7771 // each other or against (nonvolatile) loads, so they can be 7772 // chained like loads. 7773 SDValue Chain = DAG.getRoot(); 7774 SmallVector<SDValue, 4> Opers; 7775 Opers.push_back(Chain); 7776 if (FPI.isUnaryOp()) { 7777 Opers.push_back(getValue(FPI.getArgOperand(0))); 7778 } else if (FPI.isTernaryOp()) { 7779 Opers.push_back(getValue(FPI.getArgOperand(0))); 7780 Opers.push_back(getValue(FPI.getArgOperand(1))); 7781 Opers.push_back(getValue(FPI.getArgOperand(2))); 7782 } else { 7783 Opers.push_back(getValue(FPI.getArgOperand(0))); 7784 Opers.push_back(getValue(FPI.getArgOperand(1))); 7785 } 7786 7787 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7788 assert(Result.getNode()->getNumValues() == 2); 7789 7790 // Push node to the appropriate list so that future instructions can be 7791 // chained up correctly. 7792 SDValue OutChain = Result.getValue(1); 7793 switch (EB) { 7794 case fp::ExceptionBehavior::ebIgnore: 7795 // The only reason why ebIgnore nodes still need to be chained is that 7796 // they might depend on the current rounding mode, and therefore must 7797 // not be moved across instruction that may change that mode. 7798 [[fallthrough]]; 7799 case fp::ExceptionBehavior::ebMayTrap: 7800 // These must not be moved across calls or instructions that may change 7801 // floating-point exception masks. 7802 PendingConstrainedFP.push_back(OutChain); 7803 break; 7804 case fp::ExceptionBehavior::ebStrict: 7805 // These must not be moved across calls or instructions that may change 7806 // floating-point exception masks or read floating-point exception flags. 7807 // In addition, they cannot be optimized out even if unused. 7808 PendingConstrainedFPStrict.push_back(OutChain); 7809 break; 7810 } 7811 }; 7812 7813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7814 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7815 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7816 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7817 7818 SDNodeFlags Flags; 7819 if (EB == fp::ExceptionBehavior::ebIgnore) 7820 Flags.setNoFPExcept(true); 7821 7822 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7823 Flags.copyFMF(*FPOp); 7824 7825 unsigned Opcode; 7826 switch (FPI.getIntrinsicID()) { 7827 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7828 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7829 case Intrinsic::INTRINSIC: \ 7830 Opcode = ISD::STRICT_##DAGN; \ 7831 break; 7832 #include "llvm/IR/ConstrainedOps.def" 7833 case Intrinsic::experimental_constrained_fmuladd: { 7834 Opcode = ISD::STRICT_FMA; 7835 // Break fmuladd into fmul and fadd. 7836 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7837 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7838 Opers.pop_back(); 7839 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7840 pushOutChain(Mul, EB); 7841 Opcode = ISD::STRICT_FADD; 7842 Opers.clear(); 7843 Opers.push_back(Mul.getValue(1)); 7844 Opers.push_back(Mul.getValue(0)); 7845 Opers.push_back(getValue(FPI.getArgOperand(2))); 7846 } 7847 break; 7848 } 7849 } 7850 7851 // A few strict DAG nodes carry additional operands that are not 7852 // set up by the default code above. 7853 switch (Opcode) { 7854 default: break; 7855 case ISD::STRICT_FP_ROUND: 7856 Opers.push_back( 7857 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7858 break; 7859 case ISD::STRICT_FSETCC: 7860 case ISD::STRICT_FSETCCS: { 7861 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7862 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7863 if (TM.Options.NoNaNsFPMath) 7864 Condition = getFCmpCodeWithoutNaN(Condition); 7865 Opers.push_back(DAG.getCondCode(Condition)); 7866 break; 7867 } 7868 } 7869 7870 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7871 pushOutChain(Result, EB); 7872 7873 SDValue FPResult = Result.getValue(0); 7874 setValue(&FPI, FPResult); 7875 } 7876 7877 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7878 std::optional<unsigned> ResOPC; 7879 switch (VPIntrin.getIntrinsicID()) { 7880 case Intrinsic::vp_ctlz: { 7881 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7882 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7883 break; 7884 } 7885 case Intrinsic::vp_cttz: { 7886 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7887 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7888 break; 7889 } 7890 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7891 case Intrinsic::VPID: \ 7892 ResOPC = ISD::VPSD; \ 7893 break; 7894 #include "llvm/IR/VPIntrinsics.def" 7895 } 7896 7897 if (!ResOPC) 7898 llvm_unreachable( 7899 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7900 7901 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7902 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7903 if (VPIntrin.getFastMathFlags().allowReassoc()) 7904 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7905 : ISD::VP_REDUCE_FMUL; 7906 } 7907 7908 return *ResOPC; 7909 } 7910 7911 void SelectionDAGBuilder::visitVPLoad( 7912 const VPIntrinsic &VPIntrin, EVT VT, 7913 const SmallVectorImpl<SDValue> &OpValues) { 7914 SDLoc DL = getCurSDLoc(); 7915 Value *PtrOperand = VPIntrin.getArgOperand(0); 7916 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7917 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7918 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7919 SDValue LD; 7920 // Do not serialize variable-length loads of constant memory with 7921 // anything. 7922 if (!Alignment) 7923 Alignment = DAG.getEVTAlign(VT); 7924 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7925 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7926 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7927 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7928 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7929 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7930 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7931 MMO, false /*IsExpanding */); 7932 if (AddToChain) 7933 PendingLoads.push_back(LD.getValue(1)); 7934 setValue(&VPIntrin, LD); 7935 } 7936 7937 void SelectionDAGBuilder::visitVPGather( 7938 const VPIntrinsic &VPIntrin, EVT VT, 7939 const SmallVectorImpl<SDValue> &OpValues) { 7940 SDLoc DL = getCurSDLoc(); 7941 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7942 Value *PtrOperand = VPIntrin.getArgOperand(0); 7943 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7944 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7945 const MDNode *Ranges = getRangeMetadata(VPIntrin); 7946 SDValue LD; 7947 if (!Alignment) 7948 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7949 unsigned AS = 7950 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7951 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7952 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7953 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7954 SDValue Base, Index, Scale; 7955 ISD::MemIndexType IndexType; 7956 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7957 this, VPIntrin.getParent(), 7958 VT.getScalarStoreSize()); 7959 if (!UniformBase) { 7960 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7961 Index = getValue(PtrOperand); 7962 IndexType = ISD::SIGNED_SCALED; 7963 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7964 } 7965 EVT IdxVT = Index.getValueType(); 7966 EVT EltTy = IdxVT.getVectorElementType(); 7967 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7968 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7969 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7970 } 7971 LD = DAG.getGatherVP( 7972 DAG.getVTList(VT, MVT::Other), VT, DL, 7973 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7974 IndexType); 7975 PendingLoads.push_back(LD.getValue(1)); 7976 setValue(&VPIntrin, LD); 7977 } 7978 7979 void SelectionDAGBuilder::visitVPStore( 7980 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7981 SDLoc DL = getCurSDLoc(); 7982 Value *PtrOperand = VPIntrin.getArgOperand(1); 7983 EVT VT = OpValues[0].getValueType(); 7984 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7985 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7986 SDValue ST; 7987 if (!Alignment) 7988 Alignment = DAG.getEVTAlign(VT); 7989 SDValue Ptr = OpValues[1]; 7990 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7991 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7992 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7993 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7994 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7995 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7996 /* IsTruncating */ false, /*IsCompressing*/ false); 7997 DAG.setRoot(ST); 7998 setValue(&VPIntrin, ST); 7999 } 8000 8001 void SelectionDAGBuilder::visitVPScatter( 8002 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8003 SDLoc DL = getCurSDLoc(); 8004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8005 Value *PtrOperand = VPIntrin.getArgOperand(1); 8006 EVT VT = OpValues[0].getValueType(); 8007 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8008 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8009 SDValue ST; 8010 if (!Alignment) 8011 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8012 unsigned AS = 8013 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 8014 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8015 MachinePointerInfo(AS), MachineMemOperand::MOStore, 8016 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8017 SDValue Base, Index, Scale; 8018 ISD::MemIndexType IndexType; 8019 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 8020 this, VPIntrin.getParent(), 8021 VT.getScalarStoreSize()); 8022 if (!UniformBase) { 8023 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 8024 Index = getValue(PtrOperand); 8025 IndexType = ISD::SIGNED_SCALED; 8026 Scale = 8027 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 8028 } 8029 EVT IdxVT = Index.getValueType(); 8030 EVT EltTy = IdxVT.getVectorElementType(); 8031 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 8032 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 8033 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 8034 } 8035 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 8036 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 8037 OpValues[2], OpValues[3]}, 8038 MMO, IndexType); 8039 DAG.setRoot(ST); 8040 setValue(&VPIntrin, ST); 8041 } 8042 8043 void SelectionDAGBuilder::visitVPStridedLoad( 8044 const VPIntrinsic &VPIntrin, EVT VT, 8045 const SmallVectorImpl<SDValue> &OpValues) { 8046 SDLoc DL = getCurSDLoc(); 8047 Value *PtrOperand = VPIntrin.getArgOperand(0); 8048 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8049 if (!Alignment) 8050 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8051 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8052 const MDNode *Ranges = getRangeMetadata(VPIntrin); 8053 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 8054 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 8055 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 8056 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8057 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 8058 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 8059 8060 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 8061 OpValues[2], OpValues[3], MMO, 8062 false /*IsExpanding*/); 8063 8064 if (AddToChain) 8065 PendingLoads.push_back(LD.getValue(1)); 8066 setValue(&VPIntrin, LD); 8067 } 8068 8069 void SelectionDAGBuilder::visitVPStridedStore( 8070 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 8071 SDLoc DL = getCurSDLoc(); 8072 Value *PtrOperand = VPIntrin.getArgOperand(1); 8073 EVT VT = OpValues[0].getValueType(); 8074 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 8075 if (!Alignment) 8076 Alignment = DAG.getEVTAlign(VT.getScalarType()); 8077 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 8078 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 8079 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 8080 MemoryLocation::UnknownSize, *Alignment, AAInfo); 8081 8082 SDValue ST = DAG.getStridedStoreVP( 8083 getMemoryRoot(), DL, OpValues[0], OpValues[1], 8084 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 8085 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 8086 /*IsCompressing*/ false); 8087 8088 DAG.setRoot(ST); 8089 setValue(&VPIntrin, ST); 8090 } 8091 8092 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 8093 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8094 SDLoc DL = getCurSDLoc(); 8095 8096 ISD::CondCode Condition; 8097 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 8098 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 8099 if (IsFP) { 8100 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 8101 // flags, but calls that don't return floating-point types can't be 8102 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 8103 Condition = getFCmpCondCode(CondCode); 8104 if (TM.Options.NoNaNsFPMath) 8105 Condition = getFCmpCodeWithoutNaN(Condition); 8106 } else { 8107 Condition = getICmpCondCode(CondCode); 8108 } 8109 8110 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 8111 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 8112 // #2 is the condition code 8113 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 8114 SDValue EVL = getValue(VPIntrin.getOperand(4)); 8115 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8116 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8117 "Unexpected target EVL type"); 8118 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 8119 8120 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8121 VPIntrin.getType()); 8122 setValue(&VPIntrin, 8123 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 8124 } 8125 8126 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 8127 const VPIntrinsic &VPIntrin) { 8128 SDLoc DL = getCurSDLoc(); 8129 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 8130 8131 auto IID = VPIntrin.getIntrinsicID(); 8132 8133 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 8134 return visitVPCmp(*CmpI); 8135 8136 SmallVector<EVT, 4> ValueVTs; 8137 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8138 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 8139 SDVTList VTs = DAG.getVTList(ValueVTs); 8140 8141 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 8142 8143 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 8144 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 8145 "Unexpected target EVL type"); 8146 8147 // Request operands. 8148 SmallVector<SDValue, 7> OpValues; 8149 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 8150 auto Op = getValue(VPIntrin.getArgOperand(I)); 8151 if (I == EVLParamPos) 8152 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 8153 OpValues.push_back(Op); 8154 } 8155 8156 switch (Opcode) { 8157 default: { 8158 SDNodeFlags SDFlags; 8159 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8160 SDFlags.copyFMF(*FPMO); 8161 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 8162 setValue(&VPIntrin, Result); 8163 break; 8164 } 8165 case ISD::VP_LOAD: 8166 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 8167 break; 8168 case ISD::VP_GATHER: 8169 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 8170 break; 8171 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 8172 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 8173 break; 8174 case ISD::VP_STORE: 8175 visitVPStore(VPIntrin, OpValues); 8176 break; 8177 case ISD::VP_SCATTER: 8178 visitVPScatter(VPIntrin, OpValues); 8179 break; 8180 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 8181 visitVPStridedStore(VPIntrin, OpValues); 8182 break; 8183 case ISD::VP_FMULADD: { 8184 assert(OpValues.size() == 5 && "Unexpected number of operands"); 8185 SDNodeFlags SDFlags; 8186 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 8187 SDFlags.copyFMF(*FPMO); 8188 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 8189 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 8190 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 8191 } else { 8192 SDValue Mul = DAG.getNode( 8193 ISD::VP_FMUL, DL, VTs, 8194 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 8195 SDValue Add = 8196 DAG.getNode(ISD::VP_FADD, DL, VTs, 8197 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 8198 setValue(&VPIntrin, Add); 8199 } 8200 break; 8201 } 8202 case ISD::VP_IS_FPCLASS: { 8203 const DataLayout DLayout = DAG.getDataLayout(); 8204 EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType()); 8205 auto Constant = OpValues[1]->getAsZExtVal(); 8206 SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32); 8207 SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT, 8208 {OpValues[0], Check, OpValues[2], OpValues[3]}); 8209 setValue(&VPIntrin, V); 8210 return; 8211 } 8212 case ISD::VP_INTTOPTR: { 8213 SDValue N = OpValues[0]; 8214 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 8215 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 8216 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8217 OpValues[2]); 8218 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8219 OpValues[2]); 8220 setValue(&VPIntrin, N); 8221 break; 8222 } 8223 case ISD::VP_PTRTOINT: { 8224 SDValue N = OpValues[0]; 8225 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8226 VPIntrin.getType()); 8227 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 8228 VPIntrin.getOperand(0)->getType()); 8229 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 8230 OpValues[2]); 8231 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 8232 OpValues[2]); 8233 setValue(&VPIntrin, N); 8234 break; 8235 } 8236 case ISD::VP_ABS: 8237 case ISD::VP_CTLZ: 8238 case ISD::VP_CTLZ_ZERO_UNDEF: 8239 case ISD::VP_CTTZ: 8240 case ISD::VP_CTTZ_ZERO_UNDEF: { 8241 SDValue Result = 8242 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 8243 setValue(&VPIntrin, Result); 8244 break; 8245 } 8246 } 8247 } 8248 8249 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 8250 const BasicBlock *EHPadBB, 8251 MCSymbol *&BeginLabel) { 8252 MachineFunction &MF = DAG.getMachineFunction(); 8253 MachineModuleInfo &MMI = MF.getMMI(); 8254 8255 // Insert a label before the invoke call to mark the try range. This can be 8256 // used to detect deletion of the invoke via the MachineModuleInfo. 8257 BeginLabel = MMI.getContext().createTempSymbol(); 8258 8259 // For SjLj, keep track of which landing pads go with which invokes 8260 // so as to maintain the ordering of pads in the LSDA. 8261 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 8262 if (CallSiteIndex) { 8263 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 8264 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 8265 8266 // Now that the call site is handled, stop tracking it. 8267 MMI.setCurrentCallSite(0); 8268 } 8269 8270 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 8271 } 8272 8273 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 8274 const BasicBlock *EHPadBB, 8275 MCSymbol *BeginLabel) { 8276 assert(BeginLabel && "BeginLabel should've been set"); 8277 8278 MachineFunction &MF = DAG.getMachineFunction(); 8279 MachineModuleInfo &MMI = MF.getMMI(); 8280 8281 // Insert a label at the end of the invoke call to mark the try range. This 8282 // can be used to detect deletion of the invoke via the MachineModuleInfo. 8283 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 8284 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 8285 8286 // Inform MachineModuleInfo of range. 8287 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 8288 // There is a platform (e.g. wasm) that uses funclet style IR but does not 8289 // actually use outlined funclets and their LSDA info style. 8290 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 8291 assert(II && "II should've been set"); 8292 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8293 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8294 } else if (!isScopedEHPersonality(Pers)) { 8295 assert(EHPadBB); 8296 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8297 } 8298 8299 return Chain; 8300 } 8301 8302 std::pair<SDValue, SDValue> 8303 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8304 const BasicBlock *EHPadBB) { 8305 MCSymbol *BeginLabel = nullptr; 8306 8307 if (EHPadBB) { 8308 // Both PendingLoads and PendingExports must be flushed here; 8309 // this call might not return. 8310 (void)getRoot(); 8311 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8312 CLI.setChain(getRoot()); 8313 } 8314 8315 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8316 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8317 8318 assert((CLI.IsTailCall || Result.second.getNode()) && 8319 "Non-null chain expected with non-tail call!"); 8320 assert((Result.second.getNode() || !Result.first.getNode()) && 8321 "Null value expected with tail call!"); 8322 8323 if (!Result.second.getNode()) { 8324 // As a special case, a null chain means that a tail call has been emitted 8325 // and the DAG root is already updated. 8326 HasTailCall = true; 8327 8328 // Since there's no actual continuation from this block, nothing can be 8329 // relying on us setting vregs for them. 8330 PendingExports.clear(); 8331 } else { 8332 DAG.setRoot(Result.second); 8333 } 8334 8335 if (EHPadBB) { 8336 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8337 BeginLabel)); 8338 } 8339 8340 return Result; 8341 } 8342 8343 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8344 bool isTailCall, 8345 bool isMustTailCall, 8346 const BasicBlock *EHPadBB) { 8347 auto &DL = DAG.getDataLayout(); 8348 FunctionType *FTy = CB.getFunctionType(); 8349 Type *RetTy = CB.getType(); 8350 8351 TargetLowering::ArgListTy Args; 8352 Args.reserve(CB.arg_size()); 8353 8354 const Value *SwiftErrorVal = nullptr; 8355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8356 8357 if (isTailCall) { 8358 // Avoid emitting tail calls in functions with the disable-tail-calls 8359 // attribute. 8360 auto *Caller = CB.getParent()->getParent(); 8361 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8362 "true" && !isMustTailCall) 8363 isTailCall = false; 8364 8365 // We can't tail call inside a function with a swifterror argument. Lowering 8366 // does not support this yet. It would have to move into the swifterror 8367 // register before the call. 8368 if (TLI.supportSwiftError() && 8369 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8370 isTailCall = false; 8371 } 8372 8373 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8374 TargetLowering::ArgListEntry Entry; 8375 const Value *V = *I; 8376 8377 // Skip empty types 8378 if (V->getType()->isEmptyTy()) 8379 continue; 8380 8381 SDValue ArgNode = getValue(V); 8382 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8383 8384 Entry.setAttributes(&CB, I - CB.arg_begin()); 8385 8386 // Use swifterror virtual register as input to the call. 8387 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8388 SwiftErrorVal = V; 8389 // We find the virtual register for the actual swifterror argument. 8390 // Instead of using the Value, we use the virtual register instead. 8391 Entry.Node = 8392 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8393 EVT(TLI.getPointerTy(DL))); 8394 } 8395 8396 Args.push_back(Entry); 8397 8398 // If we have an explicit sret argument that is an Instruction, (i.e., it 8399 // might point to function-local memory), we can't meaningfully tail-call. 8400 if (Entry.IsSRet && isa<Instruction>(V)) 8401 isTailCall = false; 8402 } 8403 8404 // If call site has a cfguardtarget operand bundle, create and add an 8405 // additional ArgListEntry. 8406 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8407 TargetLowering::ArgListEntry Entry; 8408 Value *V = Bundle->Inputs[0]; 8409 SDValue ArgNode = getValue(V); 8410 Entry.Node = ArgNode; 8411 Entry.Ty = V->getType(); 8412 Entry.IsCFGuardTarget = true; 8413 Args.push_back(Entry); 8414 } 8415 8416 // Check if target-independent constraints permit a tail call here. 8417 // Target-dependent constraints are checked within TLI->LowerCallTo. 8418 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8419 isTailCall = false; 8420 8421 // Disable tail calls if there is an swifterror argument. Targets have not 8422 // been updated to support tail calls. 8423 if (TLI.supportSwiftError() && SwiftErrorVal) 8424 isTailCall = false; 8425 8426 ConstantInt *CFIType = nullptr; 8427 if (CB.isIndirectCall()) { 8428 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8429 if (!TLI.supportKCFIBundles()) 8430 report_fatal_error( 8431 "Target doesn't support calls with kcfi operand bundles."); 8432 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8433 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8434 } 8435 } 8436 8437 SDValue ConvControlToken; 8438 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) { 8439 auto *Token = Bundle->Inputs[0].get(); 8440 ConvControlToken = getValue(Token); 8441 } else { 8442 ConvControlToken = DAG.getUNDEF(MVT::Untyped); 8443 } 8444 8445 TargetLowering::CallLoweringInfo CLI(DAG); 8446 CLI.setDebugLoc(getCurSDLoc()) 8447 .setChain(getRoot()) 8448 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8449 .setTailCall(isTailCall) 8450 .setConvergent(CB.isConvergent()) 8451 .setIsPreallocated( 8452 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8453 .setCFIType(CFIType) 8454 .setConvergenceControlToken(ConvControlToken); 8455 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8456 8457 if (Result.first.getNode()) { 8458 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8459 setValue(&CB, Result.first); 8460 } 8461 8462 // The last element of CLI.InVals has the SDValue for swifterror return. 8463 // Here we copy it to a virtual register and update SwiftErrorMap for 8464 // book-keeping. 8465 if (SwiftErrorVal && TLI.supportSwiftError()) { 8466 // Get the last element of InVals. 8467 SDValue Src = CLI.InVals.back(); 8468 Register VReg = 8469 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8470 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8471 DAG.setRoot(CopyNode); 8472 } 8473 } 8474 8475 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8476 SelectionDAGBuilder &Builder) { 8477 // Check to see if this load can be trivially constant folded, e.g. if the 8478 // input is from a string literal. 8479 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8480 // Cast pointer to the type we really want to load. 8481 Type *LoadTy = 8482 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8483 if (LoadVT.isVector()) 8484 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8485 8486 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8487 PointerType::getUnqual(LoadTy)); 8488 8489 if (const Constant *LoadCst = 8490 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8491 LoadTy, Builder.DAG.getDataLayout())) 8492 return Builder.getValue(LoadCst); 8493 } 8494 8495 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8496 // still constant memory, the input chain can be the entry node. 8497 SDValue Root; 8498 bool ConstantMemory = false; 8499 8500 // Do not serialize (non-volatile) loads of constant memory with anything. 8501 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8502 Root = Builder.DAG.getEntryNode(); 8503 ConstantMemory = true; 8504 } else { 8505 // Do not serialize non-volatile loads against each other. 8506 Root = Builder.DAG.getRoot(); 8507 } 8508 8509 SDValue Ptr = Builder.getValue(PtrVal); 8510 SDValue LoadVal = 8511 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8512 MachinePointerInfo(PtrVal), Align(1)); 8513 8514 if (!ConstantMemory) 8515 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8516 return LoadVal; 8517 } 8518 8519 /// Record the value for an instruction that produces an integer result, 8520 /// converting the type where necessary. 8521 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8522 SDValue Value, 8523 bool IsSigned) { 8524 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8525 I.getType(), true); 8526 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8527 setValue(&I, Value); 8528 } 8529 8530 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8531 /// true and lower it. Otherwise return false, and it will be lowered like a 8532 /// normal call. 8533 /// The caller already checked that \p I calls the appropriate LibFunc with a 8534 /// correct prototype. 8535 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8536 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8537 const Value *Size = I.getArgOperand(2); 8538 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8539 if (CSize && CSize->getZExtValue() == 0) { 8540 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8541 I.getType(), true); 8542 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8543 return true; 8544 } 8545 8546 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8547 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8548 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8549 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8550 if (Res.first.getNode()) { 8551 processIntegerCallValue(I, Res.first, true); 8552 PendingLoads.push_back(Res.second); 8553 return true; 8554 } 8555 8556 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8557 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8558 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8559 return false; 8560 8561 // If the target has a fast compare for the given size, it will return a 8562 // preferred load type for that size. Require that the load VT is legal and 8563 // that the target supports unaligned loads of that type. Otherwise, return 8564 // INVALID. 8565 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8567 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8568 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8569 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8570 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8571 // TODO: Check alignment of src and dest ptrs. 8572 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8573 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8574 if (!TLI.isTypeLegal(LVT) || 8575 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8576 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8577 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8578 } 8579 8580 return LVT; 8581 }; 8582 8583 // This turns into unaligned loads. We only do this if the target natively 8584 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8585 // we'll only produce a small number of byte loads. 8586 MVT LoadVT; 8587 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8588 switch (NumBitsToCompare) { 8589 default: 8590 return false; 8591 case 16: 8592 LoadVT = MVT::i16; 8593 break; 8594 case 32: 8595 LoadVT = MVT::i32; 8596 break; 8597 case 64: 8598 case 128: 8599 case 256: 8600 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8601 break; 8602 } 8603 8604 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8605 return false; 8606 8607 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8608 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8609 8610 // Bitcast to a wide integer type if the loads are vectors. 8611 if (LoadVT.isVector()) { 8612 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8613 LoadL = DAG.getBitcast(CmpVT, LoadL); 8614 LoadR = DAG.getBitcast(CmpVT, LoadR); 8615 } 8616 8617 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8618 processIntegerCallValue(I, Cmp, false); 8619 return true; 8620 } 8621 8622 /// See if we can lower a memchr call into an optimized form. If so, return 8623 /// true and lower it. Otherwise return false, and it will be lowered like a 8624 /// normal call. 8625 /// The caller already checked that \p I calls the appropriate LibFunc with a 8626 /// correct prototype. 8627 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8628 const Value *Src = I.getArgOperand(0); 8629 const Value *Char = I.getArgOperand(1); 8630 const Value *Length = I.getArgOperand(2); 8631 8632 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8633 std::pair<SDValue, SDValue> Res = 8634 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8635 getValue(Src), getValue(Char), getValue(Length), 8636 MachinePointerInfo(Src)); 8637 if (Res.first.getNode()) { 8638 setValue(&I, Res.first); 8639 PendingLoads.push_back(Res.second); 8640 return true; 8641 } 8642 8643 return false; 8644 } 8645 8646 /// See if we can lower a mempcpy call into an optimized form. If so, return 8647 /// true and lower it. Otherwise return false, and it will be lowered like a 8648 /// normal call. 8649 /// The caller already checked that \p I calls the appropriate LibFunc with a 8650 /// correct prototype. 8651 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8652 SDValue Dst = getValue(I.getArgOperand(0)); 8653 SDValue Src = getValue(I.getArgOperand(1)); 8654 SDValue Size = getValue(I.getArgOperand(2)); 8655 8656 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8657 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8658 // DAG::getMemcpy needs Alignment to be defined. 8659 Align Alignment = std::min(DstAlign, SrcAlign); 8660 8661 SDLoc sdl = getCurSDLoc(); 8662 8663 // In the mempcpy context we need to pass in a false value for isTailCall 8664 // because the return pointer needs to be adjusted by the size of 8665 // the copied memory. 8666 SDValue Root = getMemoryRoot(); 8667 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8668 /*isTailCall=*/false, 8669 MachinePointerInfo(I.getArgOperand(0)), 8670 MachinePointerInfo(I.getArgOperand(1)), 8671 I.getAAMetadata()); 8672 assert(MC.getNode() != nullptr && 8673 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8674 DAG.setRoot(MC); 8675 8676 // Check if Size needs to be truncated or extended. 8677 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8678 8679 // Adjust return pointer to point just past the last dst byte. 8680 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8681 Dst, Size); 8682 setValue(&I, DstPlusSize); 8683 return true; 8684 } 8685 8686 /// See if we can lower a strcpy call into an optimized form. If so, return 8687 /// true and lower it, otherwise return false and it will be lowered like a 8688 /// normal call. 8689 /// The caller already checked that \p I calls the appropriate LibFunc with a 8690 /// correct prototype. 8691 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8692 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8693 8694 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8695 std::pair<SDValue, SDValue> Res = 8696 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8697 getValue(Arg0), getValue(Arg1), 8698 MachinePointerInfo(Arg0), 8699 MachinePointerInfo(Arg1), isStpcpy); 8700 if (Res.first.getNode()) { 8701 setValue(&I, Res.first); 8702 DAG.setRoot(Res.second); 8703 return true; 8704 } 8705 8706 return false; 8707 } 8708 8709 /// See if we can lower a strcmp call into an optimized form. If so, return 8710 /// true and lower it, otherwise return false and it will be lowered like a 8711 /// normal call. 8712 /// The caller already checked that \p I calls the appropriate LibFunc with a 8713 /// correct prototype. 8714 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8715 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8716 8717 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8718 std::pair<SDValue, SDValue> Res = 8719 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8720 getValue(Arg0), getValue(Arg1), 8721 MachinePointerInfo(Arg0), 8722 MachinePointerInfo(Arg1)); 8723 if (Res.first.getNode()) { 8724 processIntegerCallValue(I, Res.first, true); 8725 PendingLoads.push_back(Res.second); 8726 return true; 8727 } 8728 8729 return false; 8730 } 8731 8732 /// See if we can lower a strlen call into an optimized form. If so, return 8733 /// true and lower it, otherwise return false and it will be lowered like a 8734 /// normal call. 8735 /// The caller already checked that \p I calls the appropriate LibFunc with a 8736 /// correct prototype. 8737 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8738 const Value *Arg0 = I.getArgOperand(0); 8739 8740 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8741 std::pair<SDValue, SDValue> Res = 8742 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8743 getValue(Arg0), MachinePointerInfo(Arg0)); 8744 if (Res.first.getNode()) { 8745 processIntegerCallValue(I, Res.first, false); 8746 PendingLoads.push_back(Res.second); 8747 return true; 8748 } 8749 8750 return false; 8751 } 8752 8753 /// See if we can lower a strnlen call into an optimized form. If so, return 8754 /// true and lower it, otherwise return false and it will be lowered like a 8755 /// normal call. 8756 /// The caller already checked that \p I calls the appropriate LibFunc with a 8757 /// correct prototype. 8758 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8759 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8760 8761 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8762 std::pair<SDValue, SDValue> Res = 8763 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8764 getValue(Arg0), getValue(Arg1), 8765 MachinePointerInfo(Arg0)); 8766 if (Res.first.getNode()) { 8767 processIntegerCallValue(I, Res.first, false); 8768 PendingLoads.push_back(Res.second); 8769 return true; 8770 } 8771 8772 return false; 8773 } 8774 8775 /// See if we can lower a unary floating-point operation into an SDNode with 8776 /// the specified Opcode. If so, return true and lower it, otherwise return 8777 /// false and it will be lowered like a normal call. 8778 /// The caller already checked that \p I calls the appropriate LibFunc with a 8779 /// correct prototype. 8780 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8781 unsigned Opcode) { 8782 // We already checked this call's prototype; verify it doesn't modify errno. 8783 if (!I.onlyReadsMemory()) 8784 return false; 8785 8786 SDNodeFlags Flags; 8787 Flags.copyFMF(cast<FPMathOperator>(I)); 8788 8789 SDValue Tmp = getValue(I.getArgOperand(0)); 8790 setValue(&I, 8791 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8792 return true; 8793 } 8794 8795 /// See if we can lower a binary floating-point operation into an SDNode with 8796 /// the specified Opcode. If so, return true and lower it. Otherwise return 8797 /// false, and it will be lowered like a normal call. 8798 /// The caller already checked that \p I calls the appropriate LibFunc with a 8799 /// correct prototype. 8800 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8801 unsigned Opcode) { 8802 // We already checked this call's prototype; verify it doesn't modify errno. 8803 if (!I.onlyReadsMemory()) 8804 return false; 8805 8806 SDNodeFlags Flags; 8807 Flags.copyFMF(cast<FPMathOperator>(I)); 8808 8809 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8810 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8811 EVT VT = Tmp0.getValueType(); 8812 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8813 return true; 8814 } 8815 8816 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8817 // Handle inline assembly differently. 8818 if (I.isInlineAsm()) { 8819 visitInlineAsm(I); 8820 return; 8821 } 8822 8823 diagnoseDontCall(I); 8824 8825 if (Function *F = I.getCalledFunction()) { 8826 if (F->isDeclaration()) { 8827 // Is this an LLVM intrinsic or a target-specific intrinsic? 8828 unsigned IID = F->getIntrinsicID(); 8829 if (!IID) 8830 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8831 IID = II->getIntrinsicID(F); 8832 8833 if (IID) { 8834 visitIntrinsicCall(I, IID); 8835 return; 8836 } 8837 } 8838 8839 // Check for well-known libc/libm calls. If the function is internal, it 8840 // can't be a library call. Don't do the check if marked as nobuiltin for 8841 // some reason or the call site requires strict floating point semantics. 8842 LibFunc Func; 8843 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8844 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8845 LibInfo->hasOptimizedCodeGen(Func)) { 8846 switch (Func) { 8847 default: break; 8848 case LibFunc_bcmp: 8849 if (visitMemCmpBCmpCall(I)) 8850 return; 8851 break; 8852 case LibFunc_copysign: 8853 case LibFunc_copysignf: 8854 case LibFunc_copysignl: 8855 // We already checked this call's prototype; verify it doesn't modify 8856 // errno. 8857 if (I.onlyReadsMemory()) { 8858 SDValue LHS = getValue(I.getArgOperand(0)); 8859 SDValue RHS = getValue(I.getArgOperand(1)); 8860 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8861 LHS.getValueType(), LHS, RHS)); 8862 return; 8863 } 8864 break; 8865 case LibFunc_fabs: 8866 case LibFunc_fabsf: 8867 case LibFunc_fabsl: 8868 if (visitUnaryFloatCall(I, ISD::FABS)) 8869 return; 8870 break; 8871 case LibFunc_fmin: 8872 case LibFunc_fminf: 8873 case LibFunc_fminl: 8874 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8875 return; 8876 break; 8877 case LibFunc_fmax: 8878 case LibFunc_fmaxf: 8879 case LibFunc_fmaxl: 8880 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8881 return; 8882 break; 8883 case LibFunc_sin: 8884 case LibFunc_sinf: 8885 case LibFunc_sinl: 8886 if (visitUnaryFloatCall(I, ISD::FSIN)) 8887 return; 8888 break; 8889 case LibFunc_cos: 8890 case LibFunc_cosf: 8891 case LibFunc_cosl: 8892 if (visitUnaryFloatCall(I, ISD::FCOS)) 8893 return; 8894 break; 8895 case LibFunc_sqrt: 8896 case LibFunc_sqrtf: 8897 case LibFunc_sqrtl: 8898 case LibFunc_sqrt_finite: 8899 case LibFunc_sqrtf_finite: 8900 case LibFunc_sqrtl_finite: 8901 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8902 return; 8903 break; 8904 case LibFunc_floor: 8905 case LibFunc_floorf: 8906 case LibFunc_floorl: 8907 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8908 return; 8909 break; 8910 case LibFunc_nearbyint: 8911 case LibFunc_nearbyintf: 8912 case LibFunc_nearbyintl: 8913 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8914 return; 8915 break; 8916 case LibFunc_ceil: 8917 case LibFunc_ceilf: 8918 case LibFunc_ceill: 8919 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8920 return; 8921 break; 8922 case LibFunc_rint: 8923 case LibFunc_rintf: 8924 case LibFunc_rintl: 8925 if (visitUnaryFloatCall(I, ISD::FRINT)) 8926 return; 8927 break; 8928 case LibFunc_round: 8929 case LibFunc_roundf: 8930 case LibFunc_roundl: 8931 if (visitUnaryFloatCall(I, ISD::FROUND)) 8932 return; 8933 break; 8934 case LibFunc_trunc: 8935 case LibFunc_truncf: 8936 case LibFunc_truncl: 8937 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8938 return; 8939 break; 8940 case LibFunc_log2: 8941 case LibFunc_log2f: 8942 case LibFunc_log2l: 8943 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8944 return; 8945 break; 8946 case LibFunc_exp2: 8947 case LibFunc_exp2f: 8948 case LibFunc_exp2l: 8949 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8950 return; 8951 break; 8952 case LibFunc_exp10: 8953 case LibFunc_exp10f: 8954 case LibFunc_exp10l: 8955 if (visitUnaryFloatCall(I, ISD::FEXP10)) 8956 return; 8957 break; 8958 case LibFunc_ldexp: 8959 case LibFunc_ldexpf: 8960 case LibFunc_ldexpl: 8961 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8962 return; 8963 break; 8964 case LibFunc_memcmp: 8965 if (visitMemCmpBCmpCall(I)) 8966 return; 8967 break; 8968 case LibFunc_mempcpy: 8969 if (visitMemPCpyCall(I)) 8970 return; 8971 break; 8972 case LibFunc_memchr: 8973 if (visitMemChrCall(I)) 8974 return; 8975 break; 8976 case LibFunc_strcpy: 8977 if (visitStrCpyCall(I, false)) 8978 return; 8979 break; 8980 case LibFunc_stpcpy: 8981 if (visitStrCpyCall(I, true)) 8982 return; 8983 break; 8984 case LibFunc_strcmp: 8985 if (visitStrCmpCall(I)) 8986 return; 8987 break; 8988 case LibFunc_strlen: 8989 if (visitStrLenCall(I)) 8990 return; 8991 break; 8992 case LibFunc_strnlen: 8993 if (visitStrNLenCall(I)) 8994 return; 8995 break; 8996 } 8997 } 8998 } 8999 9000 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 9001 // have to do anything here to lower funclet bundles. 9002 // CFGuardTarget bundles are lowered in LowerCallTo. 9003 assert(!I.hasOperandBundlesOtherThan( 9004 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 9005 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 9006 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi, 9007 LLVMContext::OB_convergencectrl}) && 9008 "Cannot lower calls with arbitrary operand bundles!"); 9009 9010 SDValue Callee = getValue(I.getCalledOperand()); 9011 9012 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 9013 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 9014 else 9015 // Check if we can potentially perform a tail call. More detailed checking 9016 // is be done within LowerCallTo, after more information about the call is 9017 // known. 9018 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 9019 } 9020 9021 namespace { 9022 9023 /// AsmOperandInfo - This contains information for each constraint that we are 9024 /// lowering. 9025 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 9026 public: 9027 /// CallOperand - If this is the result output operand or a clobber 9028 /// this is null, otherwise it is the incoming operand to the CallInst. 9029 /// This gets modified as the asm is processed. 9030 SDValue CallOperand; 9031 9032 /// AssignedRegs - If this is a register or register class operand, this 9033 /// contains the set of register corresponding to the operand. 9034 RegsForValue AssignedRegs; 9035 9036 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 9037 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 9038 } 9039 9040 /// Whether or not this operand accesses memory 9041 bool hasMemory(const TargetLowering &TLI) const { 9042 // Indirect operand accesses access memory. 9043 if (isIndirect) 9044 return true; 9045 9046 for (const auto &Code : Codes) 9047 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 9048 return true; 9049 9050 return false; 9051 } 9052 }; 9053 9054 9055 } // end anonymous namespace 9056 9057 /// Make sure that the output operand \p OpInfo and its corresponding input 9058 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 9059 /// out). 9060 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 9061 SDISelAsmOperandInfo &MatchingOpInfo, 9062 SelectionDAG &DAG) { 9063 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 9064 return; 9065 9066 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 9067 const auto &TLI = DAG.getTargetLoweringInfo(); 9068 9069 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 9070 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 9071 OpInfo.ConstraintVT); 9072 std::pair<unsigned, const TargetRegisterClass *> InputRC = 9073 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 9074 MatchingOpInfo.ConstraintVT); 9075 if ((OpInfo.ConstraintVT.isInteger() != 9076 MatchingOpInfo.ConstraintVT.isInteger()) || 9077 (MatchRC.second != InputRC.second)) { 9078 // FIXME: error out in a more elegant fashion 9079 report_fatal_error("Unsupported asm: input constraint" 9080 " with a matching output constraint of" 9081 " incompatible type!"); 9082 } 9083 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 9084 } 9085 9086 /// Get a direct memory input to behave well as an indirect operand. 9087 /// This may introduce stores, hence the need for a \p Chain. 9088 /// \return The (possibly updated) chain. 9089 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 9090 SDISelAsmOperandInfo &OpInfo, 9091 SelectionDAG &DAG) { 9092 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9093 9094 // If we don't have an indirect input, put it in the constpool if we can, 9095 // otherwise spill it to a stack slot. 9096 // TODO: This isn't quite right. We need to handle these according to 9097 // the addressing mode that the constraint wants. Also, this may take 9098 // an additional register for the computation and we don't want that 9099 // either. 9100 9101 // If the operand is a float, integer, or vector constant, spill to a 9102 // constant pool entry to get its address. 9103 const Value *OpVal = OpInfo.CallOperandVal; 9104 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 9105 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 9106 OpInfo.CallOperand = DAG.getConstantPool( 9107 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 9108 return Chain; 9109 } 9110 9111 // Otherwise, create a stack slot and emit a store to it before the asm. 9112 Type *Ty = OpVal->getType(); 9113 auto &DL = DAG.getDataLayout(); 9114 uint64_t TySize = DL.getTypeAllocSize(Ty); 9115 MachineFunction &MF = DAG.getMachineFunction(); 9116 int SSFI = MF.getFrameInfo().CreateStackObject( 9117 TySize, DL.getPrefTypeAlign(Ty), false); 9118 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 9119 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 9120 MachinePointerInfo::getFixedStack(MF, SSFI), 9121 TLI.getMemValueType(DL, Ty)); 9122 OpInfo.CallOperand = StackSlot; 9123 9124 return Chain; 9125 } 9126 9127 /// GetRegistersForValue - Assign registers (virtual or physical) for the 9128 /// specified operand. We prefer to assign virtual registers, to allow the 9129 /// register allocator to handle the assignment process. However, if the asm 9130 /// uses features that we can't model on machineinstrs, we have SDISel do the 9131 /// allocation. This produces generally horrible, but correct, code. 9132 /// 9133 /// OpInfo describes the operand 9134 /// RefOpInfo describes the matching operand if any, the operand otherwise 9135 static std::optional<unsigned> 9136 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 9137 SDISelAsmOperandInfo &OpInfo, 9138 SDISelAsmOperandInfo &RefOpInfo) { 9139 LLVMContext &Context = *DAG.getContext(); 9140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9141 9142 MachineFunction &MF = DAG.getMachineFunction(); 9143 SmallVector<unsigned, 4> Regs; 9144 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9145 9146 // No work to do for memory/address operands. 9147 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9148 OpInfo.ConstraintType == TargetLowering::C_Address) 9149 return std::nullopt; 9150 9151 // If this is a constraint for a single physreg, or a constraint for a 9152 // register class, find it. 9153 unsigned AssignedReg; 9154 const TargetRegisterClass *RC; 9155 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 9156 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 9157 // RC is unset only on failure. Return immediately. 9158 if (!RC) 9159 return std::nullopt; 9160 9161 // Get the actual register value type. This is important, because the user 9162 // may have asked for (e.g.) the AX register in i32 type. We need to 9163 // remember that AX is actually i16 to get the right extension. 9164 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 9165 9166 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 9167 // If this is an FP operand in an integer register (or visa versa), or more 9168 // generally if the operand value disagrees with the register class we plan 9169 // to stick it in, fix the operand type. 9170 // 9171 // If this is an input value, the bitcast to the new type is done now. 9172 // Bitcast for output value is done at the end of visitInlineAsm(). 9173 if ((OpInfo.Type == InlineAsm::isOutput || 9174 OpInfo.Type == InlineAsm::isInput) && 9175 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 9176 // Try to convert to the first EVT that the reg class contains. If the 9177 // types are identical size, use a bitcast to convert (e.g. two differing 9178 // vector types). Note: output bitcast is done at the end of 9179 // visitInlineAsm(). 9180 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 9181 // Exclude indirect inputs while they are unsupported because the code 9182 // to perform the load is missing and thus OpInfo.CallOperand still 9183 // refers to the input address rather than the pointed-to value. 9184 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 9185 OpInfo.CallOperand = 9186 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 9187 OpInfo.ConstraintVT = RegVT; 9188 // If the operand is an FP value and we want it in integer registers, 9189 // use the corresponding integer type. This turns an f64 value into 9190 // i64, which can be passed with two i32 values on a 32-bit machine. 9191 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 9192 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 9193 if (OpInfo.Type == InlineAsm::isInput) 9194 OpInfo.CallOperand = 9195 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 9196 OpInfo.ConstraintVT = VT; 9197 } 9198 } 9199 } 9200 9201 // No need to allocate a matching input constraint since the constraint it's 9202 // matching to has already been allocated. 9203 if (OpInfo.isMatchingInputConstraint()) 9204 return std::nullopt; 9205 9206 EVT ValueVT = OpInfo.ConstraintVT; 9207 if (OpInfo.ConstraintVT == MVT::Other) 9208 ValueVT = RegVT; 9209 9210 // Initialize NumRegs. 9211 unsigned NumRegs = 1; 9212 if (OpInfo.ConstraintVT != MVT::Other) 9213 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 9214 9215 // If this is a constraint for a specific physical register, like {r17}, 9216 // assign it now. 9217 9218 // If this associated to a specific register, initialize iterator to correct 9219 // place. If virtual, make sure we have enough registers 9220 9221 // Initialize iterator if necessary 9222 TargetRegisterClass::iterator I = RC->begin(); 9223 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9224 9225 // Do not check for single registers. 9226 if (AssignedReg) { 9227 I = std::find(I, RC->end(), AssignedReg); 9228 if (I == RC->end()) { 9229 // RC does not contain the selected register, which indicates a 9230 // mismatch between the register and the required type/bitwidth. 9231 return {AssignedReg}; 9232 } 9233 } 9234 9235 for (; NumRegs; --NumRegs, ++I) { 9236 assert(I != RC->end() && "Ran out of registers to allocate!"); 9237 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 9238 Regs.push_back(R); 9239 } 9240 9241 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 9242 return std::nullopt; 9243 } 9244 9245 static unsigned 9246 findMatchingInlineAsmOperand(unsigned OperandNo, 9247 const std::vector<SDValue> &AsmNodeOperands) { 9248 // Scan until we find the definition we already emitted of this operand. 9249 unsigned CurOp = InlineAsm::Op_FirstOperand; 9250 for (; OperandNo; --OperandNo) { 9251 // Advance to the next operand. 9252 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal(); 9253 const InlineAsm::Flag F(OpFlag); 9254 assert( 9255 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) && 9256 "Skipped past definitions?"); 9257 CurOp += F.getNumOperandRegisters() + 1; 9258 } 9259 return CurOp; 9260 } 9261 9262 namespace { 9263 9264 class ExtraFlags { 9265 unsigned Flags = 0; 9266 9267 public: 9268 explicit ExtraFlags(const CallBase &Call) { 9269 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9270 if (IA->hasSideEffects()) 9271 Flags |= InlineAsm::Extra_HasSideEffects; 9272 if (IA->isAlignStack()) 9273 Flags |= InlineAsm::Extra_IsAlignStack; 9274 if (Call.isConvergent()) 9275 Flags |= InlineAsm::Extra_IsConvergent; 9276 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 9277 } 9278 9279 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 9280 // Ideally, we would only check against memory constraints. However, the 9281 // meaning of an Other constraint can be target-specific and we can't easily 9282 // reason about it. Therefore, be conservative and set MayLoad/MayStore 9283 // for Other constraints as well. 9284 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 9285 OpInfo.ConstraintType == TargetLowering::C_Other) { 9286 if (OpInfo.Type == InlineAsm::isInput) 9287 Flags |= InlineAsm::Extra_MayLoad; 9288 else if (OpInfo.Type == InlineAsm::isOutput) 9289 Flags |= InlineAsm::Extra_MayStore; 9290 else if (OpInfo.Type == InlineAsm::isClobber) 9291 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 9292 } 9293 } 9294 9295 unsigned get() const { return Flags; } 9296 }; 9297 9298 } // end anonymous namespace 9299 9300 static bool isFunction(SDValue Op) { 9301 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 9302 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 9303 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 9304 9305 // In normal "call dllimport func" instruction (non-inlineasm) it force 9306 // indirect access by specifing call opcode. And usually specially print 9307 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9308 // not do in this way now. (In fact, this is similar with "Data Access" 9309 // action). So here we ignore dllimport function. 9310 if (Fn && !Fn->hasDLLImportStorageClass()) 9311 return true; 9312 } 9313 } 9314 return false; 9315 } 9316 9317 /// visitInlineAsm - Handle a call to an InlineAsm object. 9318 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9319 const BasicBlock *EHPadBB) { 9320 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9321 9322 /// ConstraintOperands - Information about all of the constraints. 9323 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9324 9325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9326 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9327 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9328 9329 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9330 // AsmDialect, MayLoad, MayStore). 9331 bool HasSideEffect = IA->hasSideEffects(); 9332 ExtraFlags ExtraInfo(Call); 9333 9334 for (auto &T : TargetConstraints) { 9335 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9336 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9337 9338 if (OpInfo.CallOperandVal) 9339 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9340 9341 if (!HasSideEffect) 9342 HasSideEffect = OpInfo.hasMemory(TLI); 9343 9344 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9345 // FIXME: Could we compute this on OpInfo rather than T? 9346 9347 // Compute the constraint code and ConstraintType to use. 9348 TLI.ComputeConstraintToUse(T, SDValue()); 9349 9350 if (T.ConstraintType == TargetLowering::C_Immediate && 9351 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9352 // We've delayed emitting a diagnostic like the "n" constraint because 9353 // inlining could cause an integer showing up. 9354 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9355 "' expects an integer constant " 9356 "expression"); 9357 9358 ExtraInfo.update(T); 9359 } 9360 9361 // We won't need to flush pending loads if this asm doesn't touch 9362 // memory and is nonvolatile. 9363 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9364 9365 bool EmitEHLabels = isa<InvokeInst>(Call); 9366 if (EmitEHLabels) { 9367 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9368 } 9369 bool IsCallBr = isa<CallBrInst>(Call); 9370 9371 if (IsCallBr || EmitEHLabels) { 9372 // If this is a callbr or invoke we need to flush pending exports since 9373 // inlineasm_br and invoke are terminators. 9374 // We need to do this before nodes are glued to the inlineasm_br node. 9375 Chain = getControlRoot(); 9376 } 9377 9378 MCSymbol *BeginLabel = nullptr; 9379 if (EmitEHLabels) { 9380 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9381 } 9382 9383 int OpNo = -1; 9384 SmallVector<StringRef> AsmStrs; 9385 IA->collectAsmStrs(AsmStrs); 9386 9387 // Second pass over the constraints: compute which constraint option to use. 9388 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9389 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9390 OpNo++; 9391 9392 // If this is an output operand with a matching input operand, look up the 9393 // matching input. If their types mismatch, e.g. one is an integer, the 9394 // other is floating point, or their sizes are different, flag it as an 9395 // error. 9396 if (OpInfo.hasMatchingInput()) { 9397 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9398 patchMatchingInput(OpInfo, Input, DAG); 9399 } 9400 9401 // Compute the constraint code and ConstraintType to use. 9402 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9403 9404 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9405 OpInfo.Type == InlineAsm::isClobber) || 9406 OpInfo.ConstraintType == TargetLowering::C_Address) 9407 continue; 9408 9409 // In Linux PIC model, there are 4 cases about value/label addressing: 9410 // 9411 // 1: Function call or Label jmp inside the module. 9412 // 2: Data access (such as global variable, static variable) inside module. 9413 // 3: Function call or Label jmp outside the module. 9414 // 4: Data access (such as global variable) outside the module. 9415 // 9416 // Due to current llvm inline asm architecture designed to not "recognize" 9417 // the asm code, there are quite troubles for us to treat mem addressing 9418 // differently for same value/adress used in different instuctions. 9419 // For example, in pic model, call a func may in plt way or direclty 9420 // pc-related, but lea/mov a function adress may use got. 9421 // 9422 // Here we try to "recognize" function call for the case 1 and case 3 in 9423 // inline asm. And try to adjust the constraint for them. 9424 // 9425 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9426 // label, so here we don't handle jmp function label now, but we need to 9427 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9428 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9429 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9430 TM.getCodeModel() != CodeModel::Large) { 9431 OpInfo.isIndirect = false; 9432 OpInfo.ConstraintType = TargetLowering::C_Address; 9433 } 9434 9435 // If this is a memory input, and if the operand is not indirect, do what we 9436 // need to provide an address for the memory input. 9437 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9438 !OpInfo.isIndirect) { 9439 assert((OpInfo.isMultipleAlternative || 9440 (OpInfo.Type == InlineAsm::isInput)) && 9441 "Can only indirectify direct input operands!"); 9442 9443 // Memory operands really want the address of the value. 9444 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9445 9446 // There is no longer a Value* corresponding to this operand. 9447 OpInfo.CallOperandVal = nullptr; 9448 9449 // It is now an indirect operand. 9450 OpInfo.isIndirect = true; 9451 } 9452 9453 } 9454 9455 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9456 std::vector<SDValue> AsmNodeOperands; 9457 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9458 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9459 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9460 9461 // If we have a !srcloc metadata node associated with it, we want to attach 9462 // this to the ultimately generated inline asm machineinstr. To do this, we 9463 // pass in the third operand as this (potentially null) inline asm MDNode. 9464 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9465 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9466 9467 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9468 // bits as operand 3. 9469 AsmNodeOperands.push_back(DAG.getTargetConstant( 9470 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9471 9472 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9473 // this, assign virtual and physical registers for inputs and otput. 9474 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9475 // Assign Registers. 9476 SDISelAsmOperandInfo &RefOpInfo = 9477 OpInfo.isMatchingInputConstraint() 9478 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9479 : OpInfo; 9480 const auto RegError = 9481 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9482 if (RegError) { 9483 const MachineFunction &MF = DAG.getMachineFunction(); 9484 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9485 const char *RegName = TRI.getName(*RegError); 9486 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9487 "' allocated for constraint '" + 9488 Twine(OpInfo.ConstraintCode) + 9489 "' does not match required type"); 9490 return; 9491 } 9492 9493 auto DetectWriteToReservedRegister = [&]() { 9494 const MachineFunction &MF = DAG.getMachineFunction(); 9495 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9496 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9497 if (Register::isPhysicalRegister(Reg) && 9498 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9499 const char *RegName = TRI.getName(Reg); 9500 emitInlineAsmError(Call, "write to reserved register '" + 9501 Twine(RegName) + "'"); 9502 return true; 9503 } 9504 } 9505 return false; 9506 }; 9507 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9508 (OpInfo.Type == InlineAsm::isInput && 9509 !OpInfo.isMatchingInputConstraint())) && 9510 "Only address as input operand is allowed."); 9511 9512 switch (OpInfo.Type) { 9513 case InlineAsm::isOutput: 9514 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9515 const InlineAsm::ConstraintCode ConstraintID = 9516 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9517 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9518 "Failed to convert memory constraint code to constraint id."); 9519 9520 // Add information to the INLINEASM node to know about this output. 9521 InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1); 9522 OpFlags.setMemConstraint(ConstraintID); 9523 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9524 MVT::i32)); 9525 AsmNodeOperands.push_back(OpInfo.CallOperand); 9526 } else { 9527 // Otherwise, this outputs to a register (directly for C_Register / 9528 // C_RegisterClass, and a target-defined fashion for 9529 // C_Immediate/C_Other). Find a register that we can use. 9530 if (OpInfo.AssignedRegs.Regs.empty()) { 9531 emitInlineAsmError( 9532 Call, "couldn't allocate output register for constraint '" + 9533 Twine(OpInfo.ConstraintCode) + "'"); 9534 return; 9535 } 9536 9537 if (DetectWriteToReservedRegister()) 9538 return; 9539 9540 // Add information to the INLINEASM node to know that this register is 9541 // set. 9542 OpInfo.AssignedRegs.AddInlineAsmOperands( 9543 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber 9544 : InlineAsm::Kind::RegDef, 9545 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9546 } 9547 break; 9548 9549 case InlineAsm::isInput: 9550 case InlineAsm::isLabel: { 9551 SDValue InOperandVal = OpInfo.CallOperand; 9552 9553 if (OpInfo.isMatchingInputConstraint()) { 9554 // If this is required to match an output register we have already set, 9555 // just use its register. 9556 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9557 AsmNodeOperands); 9558 InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal()); 9559 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) { 9560 if (OpInfo.isIndirect) { 9561 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9562 emitInlineAsmError(Call, "inline asm not supported yet: " 9563 "don't know how to handle tied " 9564 "indirect register inputs"); 9565 return; 9566 } 9567 9568 SmallVector<unsigned, 4> Regs; 9569 MachineFunction &MF = DAG.getMachineFunction(); 9570 MachineRegisterInfo &MRI = MF.getRegInfo(); 9571 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9572 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9573 Register TiedReg = R->getReg(); 9574 MVT RegVT = R->getSimpleValueType(0); 9575 const TargetRegisterClass *RC = 9576 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9577 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9578 : TRI.getMinimalPhysRegClass(TiedReg); 9579 for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i) 9580 Regs.push_back(MRI.createVirtualRegister(RC)); 9581 9582 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9583 9584 SDLoc dl = getCurSDLoc(); 9585 // Use the produced MatchedRegs object to 9586 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9587 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true, 9588 OpInfo.getMatchedOperand(), dl, DAG, 9589 AsmNodeOperands); 9590 break; 9591 } 9592 9593 assert(Flag.isMemKind() && "Unknown matching constraint!"); 9594 assert(Flag.getNumOperandRegisters() == 1 && 9595 "Unexpected number of operands"); 9596 // Add information to the INLINEASM node to know about this input. 9597 // See InlineAsm.h isUseOperandTiedToDef. 9598 Flag.clearMemConstraint(); 9599 Flag.setMatchingOp(OpInfo.getMatchedOperand()); 9600 AsmNodeOperands.push_back(DAG.getTargetConstant( 9601 Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9602 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9603 break; 9604 } 9605 9606 // Treat indirect 'X' constraint as memory. 9607 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9608 OpInfo.isIndirect) 9609 OpInfo.ConstraintType = TargetLowering::C_Memory; 9610 9611 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9612 OpInfo.ConstraintType == TargetLowering::C_Other) { 9613 std::vector<SDValue> Ops; 9614 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9615 Ops, DAG); 9616 if (Ops.empty()) { 9617 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9618 if (isa<ConstantSDNode>(InOperandVal)) { 9619 emitInlineAsmError(Call, "value out of range for constraint '" + 9620 Twine(OpInfo.ConstraintCode) + "'"); 9621 return; 9622 } 9623 9624 emitInlineAsmError(Call, 9625 "invalid operand for inline asm constraint '" + 9626 Twine(OpInfo.ConstraintCode) + "'"); 9627 return; 9628 } 9629 9630 // Add information to the INLINEASM node to know about this input. 9631 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size()); 9632 AsmNodeOperands.push_back(DAG.getTargetConstant( 9633 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9634 llvm::append_range(AsmNodeOperands, Ops); 9635 break; 9636 } 9637 9638 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9639 assert((OpInfo.isIndirect || 9640 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9641 "Operand must be indirect to be a mem!"); 9642 assert(InOperandVal.getValueType() == 9643 TLI.getPointerTy(DAG.getDataLayout()) && 9644 "Memory operands expect pointer values"); 9645 9646 const InlineAsm::ConstraintCode ConstraintID = 9647 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9648 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9649 "Failed to convert memory constraint code to constraint id."); 9650 9651 // Add information to the INLINEASM node to know about this input. 9652 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9653 ResOpType.setMemConstraint(ConstraintID); 9654 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9655 getCurSDLoc(), 9656 MVT::i32)); 9657 AsmNodeOperands.push_back(InOperandVal); 9658 break; 9659 } 9660 9661 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9662 const InlineAsm::ConstraintCode ConstraintID = 9663 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9664 assert(ConstraintID != InlineAsm::ConstraintCode::Unknown && 9665 "Failed to convert memory constraint code to constraint id."); 9666 9667 InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1); 9668 9669 SDValue AsmOp = InOperandVal; 9670 if (isFunction(InOperandVal)) { 9671 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9672 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1); 9673 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9674 InOperandVal.getValueType(), 9675 GA->getOffset()); 9676 } 9677 9678 // Add information to the INLINEASM node to know about this input. 9679 ResOpType.setMemConstraint(ConstraintID); 9680 9681 AsmNodeOperands.push_back( 9682 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9683 9684 AsmNodeOperands.push_back(AsmOp); 9685 break; 9686 } 9687 9688 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9689 OpInfo.ConstraintType == TargetLowering::C_Register) && 9690 "Unknown constraint type!"); 9691 9692 // TODO: Support this. 9693 if (OpInfo.isIndirect) { 9694 emitInlineAsmError( 9695 Call, "Don't know how to handle indirect register inputs yet " 9696 "for constraint '" + 9697 Twine(OpInfo.ConstraintCode) + "'"); 9698 return; 9699 } 9700 9701 // Copy the input into the appropriate registers. 9702 if (OpInfo.AssignedRegs.Regs.empty()) { 9703 emitInlineAsmError(Call, 9704 "couldn't allocate input reg for constraint '" + 9705 Twine(OpInfo.ConstraintCode) + "'"); 9706 return; 9707 } 9708 9709 if (DetectWriteToReservedRegister()) 9710 return; 9711 9712 SDLoc dl = getCurSDLoc(); 9713 9714 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9715 &Call); 9716 9717 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false, 9718 0, dl, DAG, AsmNodeOperands); 9719 break; 9720 } 9721 case InlineAsm::isClobber: 9722 // Add the clobbered value to the operand list, so that the register 9723 // allocator is aware that the physreg got clobbered. 9724 if (!OpInfo.AssignedRegs.Regs.empty()) 9725 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber, 9726 false, 0, getCurSDLoc(), DAG, 9727 AsmNodeOperands); 9728 break; 9729 } 9730 } 9731 9732 // Finish up input operands. Set the input chain and add the flag last. 9733 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9734 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9735 9736 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9737 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9738 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9739 Glue = Chain.getValue(1); 9740 9741 // Do additional work to generate outputs. 9742 9743 SmallVector<EVT, 1> ResultVTs; 9744 SmallVector<SDValue, 1> ResultValues; 9745 SmallVector<SDValue, 8> OutChains; 9746 9747 llvm::Type *CallResultType = Call.getType(); 9748 ArrayRef<Type *> ResultTypes; 9749 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9750 ResultTypes = StructResult->elements(); 9751 else if (!CallResultType->isVoidTy()) 9752 ResultTypes = ArrayRef(CallResultType); 9753 9754 auto CurResultType = ResultTypes.begin(); 9755 auto handleRegAssign = [&](SDValue V) { 9756 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9757 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9758 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9759 ++CurResultType; 9760 // If the type of the inline asm call site return value is different but has 9761 // same size as the type of the asm output bitcast it. One example of this 9762 // is for vectors with different width / number of elements. This can 9763 // happen for register classes that can contain multiple different value 9764 // types. The preg or vreg allocated may not have the same VT as was 9765 // expected. 9766 // 9767 // This can also happen for a return value that disagrees with the register 9768 // class it is put in, eg. a double in a general-purpose register on a 9769 // 32-bit machine. 9770 if (ResultVT != V.getValueType() && 9771 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9772 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9773 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9774 V.getValueType().isInteger()) { 9775 // If a result value was tied to an input value, the computed result 9776 // may have a wider width than the expected result. Extract the 9777 // relevant portion. 9778 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9779 } 9780 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9781 ResultVTs.push_back(ResultVT); 9782 ResultValues.push_back(V); 9783 }; 9784 9785 // Deal with output operands. 9786 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9787 if (OpInfo.Type == InlineAsm::isOutput) { 9788 SDValue Val; 9789 // Skip trivial output operands. 9790 if (OpInfo.AssignedRegs.Regs.empty()) 9791 continue; 9792 9793 switch (OpInfo.ConstraintType) { 9794 case TargetLowering::C_Register: 9795 case TargetLowering::C_RegisterClass: 9796 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9797 Chain, &Glue, &Call); 9798 break; 9799 case TargetLowering::C_Immediate: 9800 case TargetLowering::C_Other: 9801 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9802 OpInfo, DAG); 9803 break; 9804 case TargetLowering::C_Memory: 9805 break; // Already handled. 9806 case TargetLowering::C_Address: 9807 break; // Silence warning. 9808 case TargetLowering::C_Unknown: 9809 assert(false && "Unexpected unknown constraint"); 9810 } 9811 9812 // Indirect output manifest as stores. Record output chains. 9813 if (OpInfo.isIndirect) { 9814 const Value *Ptr = OpInfo.CallOperandVal; 9815 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9816 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9817 MachinePointerInfo(Ptr)); 9818 OutChains.push_back(Store); 9819 } else { 9820 // generate CopyFromRegs to associated registers. 9821 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9822 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9823 for (const SDValue &V : Val->op_values()) 9824 handleRegAssign(V); 9825 } else 9826 handleRegAssign(Val); 9827 } 9828 } 9829 } 9830 9831 // Set results. 9832 if (!ResultValues.empty()) { 9833 assert(CurResultType == ResultTypes.end() && 9834 "Mismatch in number of ResultTypes"); 9835 assert(ResultValues.size() == ResultTypes.size() && 9836 "Mismatch in number of output operands in asm result"); 9837 9838 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9839 DAG.getVTList(ResultVTs), ResultValues); 9840 setValue(&Call, V); 9841 } 9842 9843 // Collect store chains. 9844 if (!OutChains.empty()) 9845 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9846 9847 if (EmitEHLabels) { 9848 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9849 } 9850 9851 // Only Update Root if inline assembly has a memory effect. 9852 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9853 EmitEHLabels) 9854 DAG.setRoot(Chain); 9855 } 9856 9857 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9858 const Twine &Message) { 9859 LLVMContext &Ctx = *DAG.getContext(); 9860 Ctx.emitError(&Call, Message); 9861 9862 // Make sure we leave the DAG in a valid state 9863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9864 SmallVector<EVT, 1> ValueVTs; 9865 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9866 9867 if (ValueVTs.empty()) 9868 return; 9869 9870 SmallVector<SDValue, 1> Ops; 9871 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9872 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9873 9874 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9875 } 9876 9877 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9878 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9879 MVT::Other, getRoot(), 9880 getValue(I.getArgOperand(0)), 9881 DAG.getSrcValue(I.getArgOperand(0)))); 9882 } 9883 9884 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9885 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9886 const DataLayout &DL = DAG.getDataLayout(); 9887 SDValue V = DAG.getVAArg( 9888 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9889 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9890 DL.getABITypeAlign(I.getType()).value()); 9891 DAG.setRoot(V.getValue(1)); 9892 9893 if (I.getType()->isPointerTy()) 9894 V = DAG.getPtrExtOrTrunc( 9895 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9896 setValue(&I, V); 9897 } 9898 9899 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9900 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9901 MVT::Other, getRoot(), 9902 getValue(I.getArgOperand(0)), 9903 DAG.getSrcValue(I.getArgOperand(0)))); 9904 } 9905 9906 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9907 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9908 MVT::Other, getRoot(), 9909 getValue(I.getArgOperand(0)), 9910 getValue(I.getArgOperand(1)), 9911 DAG.getSrcValue(I.getArgOperand(0)), 9912 DAG.getSrcValue(I.getArgOperand(1)))); 9913 } 9914 9915 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9916 const Instruction &I, 9917 SDValue Op) { 9918 const MDNode *Range = getRangeMetadata(I); 9919 if (!Range) 9920 return Op; 9921 9922 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9923 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9924 return Op; 9925 9926 APInt Lo = CR.getUnsignedMin(); 9927 if (!Lo.isMinValue()) 9928 return Op; 9929 9930 APInt Hi = CR.getUnsignedMax(); 9931 unsigned Bits = std::max(Hi.getActiveBits(), 9932 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9933 9934 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9935 9936 SDLoc SL = getCurSDLoc(); 9937 9938 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9939 DAG.getValueType(SmallVT)); 9940 unsigned NumVals = Op.getNode()->getNumValues(); 9941 if (NumVals == 1) 9942 return ZExt; 9943 9944 SmallVector<SDValue, 4> Ops; 9945 9946 Ops.push_back(ZExt); 9947 for (unsigned I = 1; I != NumVals; ++I) 9948 Ops.push_back(Op.getValue(I)); 9949 9950 return DAG.getMergeValues(Ops, SL); 9951 } 9952 9953 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9954 /// the call being lowered. 9955 /// 9956 /// This is a helper for lowering intrinsics that follow a target calling 9957 /// convention or require stack pointer adjustment. Only a subset of the 9958 /// intrinsic's operands need to participate in the calling convention. 9959 void SelectionDAGBuilder::populateCallLoweringInfo( 9960 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9961 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9962 AttributeSet RetAttrs, bool IsPatchPoint) { 9963 TargetLowering::ArgListTy Args; 9964 Args.reserve(NumArgs); 9965 9966 // Populate the argument list. 9967 // Attributes for args start at offset 1, after the return attribute. 9968 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9969 ArgI != ArgE; ++ArgI) { 9970 const Value *V = Call->getOperand(ArgI); 9971 9972 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9973 9974 TargetLowering::ArgListEntry Entry; 9975 Entry.Node = getValue(V); 9976 Entry.Ty = V->getType(); 9977 Entry.setAttributes(Call, ArgI); 9978 Args.push_back(Entry); 9979 } 9980 9981 CLI.setDebugLoc(getCurSDLoc()) 9982 .setChain(getRoot()) 9983 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args), 9984 RetAttrs) 9985 .setDiscardResult(Call->use_empty()) 9986 .setIsPatchPoint(IsPatchPoint) 9987 .setIsPreallocated( 9988 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9989 } 9990 9991 /// Add a stack map intrinsic call's live variable operands to a stackmap 9992 /// or patchpoint target node's operand list. 9993 /// 9994 /// Constants are converted to TargetConstants purely as an optimization to 9995 /// avoid constant materialization and register allocation. 9996 /// 9997 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9998 /// generate addess computation nodes, and so FinalizeISel can convert the 9999 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 10000 /// address materialization and register allocation, but may also be required 10001 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 10002 /// alloca in the entry block, then the runtime may assume that the alloca's 10003 /// StackMap location can be read immediately after compilation and that the 10004 /// location is valid at any point during execution (this is similar to the 10005 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 10006 /// only available in a register, then the runtime would need to trap when 10007 /// execution reaches the StackMap in order to read the alloca's location. 10008 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 10009 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 10010 SelectionDAGBuilder &Builder) { 10011 SelectionDAG &DAG = Builder.DAG; 10012 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 10013 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 10014 10015 // Things on the stack are pointer-typed, meaning that they are already 10016 // legal and can be emitted directly to target nodes. 10017 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 10018 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 10019 } else { 10020 // Otherwise emit a target independent node to be legalised. 10021 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 10022 } 10023 } 10024 } 10025 10026 /// Lower llvm.experimental.stackmap. 10027 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 10028 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 10029 // [live variables...]) 10030 10031 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 10032 10033 SDValue Chain, InGlue, Callee; 10034 SmallVector<SDValue, 32> Ops; 10035 10036 SDLoc DL = getCurSDLoc(); 10037 Callee = getValue(CI.getCalledOperand()); 10038 10039 // The stackmap intrinsic only records the live variables (the arguments 10040 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 10041 // intrinsic, this won't be lowered to a function call. This means we don't 10042 // have to worry about calling conventions and target specific lowering code. 10043 // Instead we perform the call lowering right here. 10044 // 10045 // chain, flag = CALLSEQ_START(chain, 0, 0) 10046 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 10047 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 10048 // 10049 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 10050 InGlue = Chain.getValue(1); 10051 10052 // Add the STACKMAP operands, starting with DAG house-keeping. 10053 Ops.push_back(Chain); 10054 Ops.push_back(InGlue); 10055 10056 // Add the <id>, <numShadowBytes> operands. 10057 // 10058 // These do not require legalisation, and can be emitted directly to target 10059 // constant nodes. 10060 SDValue ID = getValue(CI.getArgOperand(0)); 10061 assert(ID.getValueType() == MVT::i64); 10062 SDValue IDConst = 10063 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType()); 10064 Ops.push_back(IDConst); 10065 10066 SDValue Shad = getValue(CI.getArgOperand(1)); 10067 assert(Shad.getValueType() == MVT::i32); 10068 SDValue ShadConst = 10069 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType()); 10070 Ops.push_back(ShadConst); 10071 10072 // Add the live variables. 10073 addStackMapLiveVars(CI, 2, DL, Ops, *this); 10074 10075 // Create the STACKMAP node. 10076 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10077 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 10078 InGlue = Chain.getValue(1); 10079 10080 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 10081 10082 // Stackmaps don't generate values, so nothing goes into the NodeMap. 10083 10084 // Set the root to the target-lowered call chain. 10085 DAG.setRoot(Chain); 10086 10087 // Inform the Frame Information that we have a stackmap in this function. 10088 FuncInfo.MF->getFrameInfo().setHasStackMap(); 10089 } 10090 10091 /// Lower llvm.experimental.patchpoint directly to its target opcode. 10092 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 10093 const BasicBlock *EHPadBB) { 10094 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 10095 // i32 <numBytes>, 10096 // i8* <target>, 10097 // i32 <numArgs>, 10098 // [Args...], 10099 // [live variables...]) 10100 10101 CallingConv::ID CC = CB.getCallingConv(); 10102 bool IsAnyRegCC = CC == CallingConv::AnyReg; 10103 bool HasDef = !CB.getType()->isVoidTy(); 10104 SDLoc dl = getCurSDLoc(); 10105 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 10106 10107 // Handle immediate and symbolic callees. 10108 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 10109 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 10110 /*isTarget=*/true); 10111 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 10112 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 10113 SDLoc(SymbolicCallee), 10114 SymbolicCallee->getValueType(0)); 10115 10116 // Get the real number of arguments participating in the call <numArgs> 10117 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 10118 unsigned NumArgs = NArgVal->getAsZExtVal(); 10119 10120 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 10121 // Intrinsics include all meta-operands up to but not including CC. 10122 unsigned NumMetaOpers = PatchPointOpers::CCPos; 10123 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 10124 "Not enough arguments provided to the patchpoint intrinsic"); 10125 10126 // For AnyRegCC the arguments are lowered later on manually. 10127 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 10128 Type *ReturnTy = 10129 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 10130 10131 TargetLowering::CallLoweringInfo CLI(DAG); 10132 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 10133 ReturnTy, CB.getAttributes().getRetAttrs(), true); 10134 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 10135 10136 SDNode *CallEnd = Result.second.getNode(); 10137 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 10138 CallEnd = CallEnd->getOperand(0).getNode(); 10139 10140 /// Get a call instruction from the call sequence chain. 10141 /// Tail calls are not allowed. 10142 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 10143 "Expected a callseq node."); 10144 SDNode *Call = CallEnd->getOperand(0).getNode(); 10145 bool HasGlue = Call->getGluedNode(); 10146 10147 // Replace the target specific call node with the patchable intrinsic. 10148 SmallVector<SDValue, 8> Ops; 10149 10150 // Push the chain. 10151 Ops.push_back(*(Call->op_begin())); 10152 10153 // Optionally, push the glue (if any). 10154 if (HasGlue) 10155 Ops.push_back(*(Call->op_end() - 1)); 10156 10157 // Push the register mask info. 10158 if (HasGlue) 10159 Ops.push_back(*(Call->op_end() - 2)); 10160 else 10161 Ops.push_back(*(Call->op_end() - 1)); 10162 10163 // Add the <id> and <numBytes> constants. 10164 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 10165 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64)); 10166 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 10167 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32)); 10168 10169 // Add the callee. 10170 Ops.push_back(Callee); 10171 10172 // Adjust <numArgs> to account for any arguments that have been passed on the 10173 // stack instead. 10174 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 10175 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 10176 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 10177 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 10178 10179 // Add the calling convention 10180 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 10181 10182 // Add the arguments we omitted previously. The register allocator should 10183 // place these in any free register. 10184 if (IsAnyRegCC) 10185 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 10186 Ops.push_back(getValue(CB.getArgOperand(i))); 10187 10188 // Push the arguments from the call instruction. 10189 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 10190 Ops.append(Call->op_begin() + 2, e); 10191 10192 // Push live variables for the stack map. 10193 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 10194 10195 SDVTList NodeTys; 10196 if (IsAnyRegCC && HasDef) { 10197 // Create the return types based on the intrinsic definition 10198 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10199 SmallVector<EVT, 3> ValueVTs; 10200 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 10201 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 10202 10203 // There is always a chain and a glue type at the end 10204 ValueVTs.push_back(MVT::Other); 10205 ValueVTs.push_back(MVT::Glue); 10206 NodeTys = DAG.getVTList(ValueVTs); 10207 } else 10208 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10209 10210 // Replace the target specific call node with a PATCHPOINT node. 10211 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 10212 10213 // Update the NodeMap. 10214 if (HasDef) { 10215 if (IsAnyRegCC) 10216 setValue(&CB, SDValue(PPV.getNode(), 0)); 10217 else 10218 setValue(&CB, Result.first); 10219 } 10220 10221 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 10222 // call sequence. Furthermore the location of the chain and glue can change 10223 // when the AnyReg calling convention is used and the intrinsic returns a 10224 // value. 10225 if (IsAnyRegCC && HasDef) { 10226 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 10227 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 10228 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10229 } else 10230 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 10231 DAG.DeleteNode(Call); 10232 10233 // Inform the Frame Information that we have a patchpoint in this function. 10234 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 10235 } 10236 10237 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 10238 unsigned Intrinsic) { 10239 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10240 SDValue Op1 = getValue(I.getArgOperand(0)); 10241 SDValue Op2; 10242 if (I.arg_size() > 1) 10243 Op2 = getValue(I.getArgOperand(1)); 10244 SDLoc dl = getCurSDLoc(); 10245 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 10246 SDValue Res; 10247 SDNodeFlags SDFlags; 10248 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 10249 SDFlags.copyFMF(*FPMO); 10250 10251 switch (Intrinsic) { 10252 case Intrinsic::vector_reduce_fadd: 10253 if (SDFlags.hasAllowReassociation()) 10254 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 10255 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 10256 SDFlags); 10257 else 10258 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 10259 break; 10260 case Intrinsic::vector_reduce_fmul: 10261 if (SDFlags.hasAllowReassociation()) 10262 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 10263 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 10264 SDFlags); 10265 else 10266 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 10267 break; 10268 case Intrinsic::vector_reduce_add: 10269 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 10270 break; 10271 case Intrinsic::vector_reduce_mul: 10272 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 10273 break; 10274 case Intrinsic::vector_reduce_and: 10275 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 10276 break; 10277 case Intrinsic::vector_reduce_or: 10278 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 10279 break; 10280 case Intrinsic::vector_reduce_xor: 10281 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 10282 break; 10283 case Intrinsic::vector_reduce_smax: 10284 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 10285 break; 10286 case Intrinsic::vector_reduce_smin: 10287 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 10288 break; 10289 case Intrinsic::vector_reduce_umax: 10290 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 10291 break; 10292 case Intrinsic::vector_reduce_umin: 10293 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 10294 break; 10295 case Intrinsic::vector_reduce_fmax: 10296 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10297 break; 10298 case Intrinsic::vector_reduce_fmin: 10299 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10300 break; 10301 case Intrinsic::vector_reduce_fmaximum: 10302 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10303 break; 10304 case Intrinsic::vector_reduce_fminimum: 10305 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10306 break; 10307 default: 10308 llvm_unreachable("Unhandled vector reduce intrinsic"); 10309 } 10310 setValue(&I, Res); 10311 } 10312 10313 /// Returns an AttributeList representing the attributes applied to the return 10314 /// value of the given call. 10315 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10316 SmallVector<Attribute::AttrKind, 2> Attrs; 10317 if (CLI.RetSExt) 10318 Attrs.push_back(Attribute::SExt); 10319 if (CLI.RetZExt) 10320 Attrs.push_back(Attribute::ZExt); 10321 if (CLI.IsInReg) 10322 Attrs.push_back(Attribute::InReg); 10323 10324 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10325 Attrs); 10326 } 10327 10328 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10329 /// implementation, which just calls LowerCall. 10330 /// FIXME: When all targets are 10331 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10332 std::pair<SDValue, SDValue> 10333 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10334 // Handle the incoming return values from the call. 10335 CLI.Ins.clear(); 10336 Type *OrigRetTy = CLI.RetTy; 10337 SmallVector<EVT, 4> RetTys; 10338 SmallVector<uint64_t, 4> Offsets; 10339 auto &DL = CLI.DAG.getDataLayout(); 10340 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10341 10342 if (CLI.IsPostTypeLegalization) { 10343 // If we are lowering a libcall after legalization, split the return type. 10344 SmallVector<EVT, 4> OldRetTys; 10345 SmallVector<uint64_t, 4> OldOffsets; 10346 RetTys.swap(OldRetTys); 10347 Offsets.swap(OldOffsets); 10348 10349 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10350 EVT RetVT = OldRetTys[i]; 10351 uint64_t Offset = OldOffsets[i]; 10352 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10353 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10354 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10355 RetTys.append(NumRegs, RegisterVT); 10356 for (unsigned j = 0; j != NumRegs; ++j) 10357 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10358 } 10359 } 10360 10361 SmallVector<ISD::OutputArg, 4> Outs; 10362 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10363 10364 bool CanLowerReturn = 10365 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10366 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10367 10368 SDValue DemoteStackSlot; 10369 int DemoteStackIdx = -100; 10370 if (!CanLowerReturn) { 10371 // FIXME: equivalent assert? 10372 // assert(!CS.hasInAllocaArgument() && 10373 // "sret demotion is incompatible with inalloca"); 10374 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10375 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10376 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10377 DemoteStackIdx = 10378 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10379 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10380 DL.getAllocaAddrSpace()); 10381 10382 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10383 ArgListEntry Entry; 10384 Entry.Node = DemoteStackSlot; 10385 Entry.Ty = StackSlotPtrType; 10386 Entry.IsSExt = false; 10387 Entry.IsZExt = false; 10388 Entry.IsInReg = false; 10389 Entry.IsSRet = true; 10390 Entry.IsNest = false; 10391 Entry.IsByVal = false; 10392 Entry.IsByRef = false; 10393 Entry.IsReturned = false; 10394 Entry.IsSwiftSelf = false; 10395 Entry.IsSwiftAsync = false; 10396 Entry.IsSwiftError = false; 10397 Entry.IsCFGuardTarget = false; 10398 Entry.Alignment = Alignment; 10399 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10400 CLI.NumFixedArgs += 1; 10401 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10402 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10403 10404 // sret demotion isn't compatible with tail-calls, since the sret argument 10405 // points into the callers stack frame. 10406 CLI.IsTailCall = false; 10407 } else { 10408 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10409 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10410 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10411 ISD::ArgFlagsTy Flags; 10412 if (NeedsRegBlock) { 10413 Flags.setInConsecutiveRegs(); 10414 if (I == RetTys.size() - 1) 10415 Flags.setInConsecutiveRegsLast(); 10416 } 10417 EVT VT = RetTys[I]; 10418 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10419 CLI.CallConv, VT); 10420 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10421 CLI.CallConv, VT); 10422 for (unsigned i = 0; i != NumRegs; ++i) { 10423 ISD::InputArg MyFlags; 10424 MyFlags.Flags = Flags; 10425 MyFlags.VT = RegisterVT; 10426 MyFlags.ArgVT = VT; 10427 MyFlags.Used = CLI.IsReturnValueUsed; 10428 if (CLI.RetTy->isPointerTy()) { 10429 MyFlags.Flags.setPointer(); 10430 MyFlags.Flags.setPointerAddrSpace( 10431 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10432 } 10433 if (CLI.RetSExt) 10434 MyFlags.Flags.setSExt(); 10435 if (CLI.RetZExt) 10436 MyFlags.Flags.setZExt(); 10437 if (CLI.IsInReg) 10438 MyFlags.Flags.setInReg(); 10439 CLI.Ins.push_back(MyFlags); 10440 } 10441 } 10442 } 10443 10444 // We push in swifterror return as the last element of CLI.Ins. 10445 ArgListTy &Args = CLI.getArgs(); 10446 if (supportSwiftError()) { 10447 for (const ArgListEntry &Arg : Args) { 10448 if (Arg.IsSwiftError) { 10449 ISD::InputArg MyFlags; 10450 MyFlags.VT = getPointerTy(DL); 10451 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10452 MyFlags.Flags.setSwiftError(); 10453 CLI.Ins.push_back(MyFlags); 10454 } 10455 } 10456 } 10457 10458 // Handle all of the outgoing arguments. 10459 CLI.Outs.clear(); 10460 CLI.OutVals.clear(); 10461 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10462 SmallVector<EVT, 4> ValueVTs; 10463 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10464 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10465 Type *FinalType = Args[i].Ty; 10466 if (Args[i].IsByVal) 10467 FinalType = Args[i].IndirectType; 10468 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10469 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10470 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10471 ++Value) { 10472 EVT VT = ValueVTs[Value]; 10473 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10474 SDValue Op = SDValue(Args[i].Node.getNode(), 10475 Args[i].Node.getResNo() + Value); 10476 ISD::ArgFlagsTy Flags; 10477 10478 // Certain targets (such as MIPS), may have a different ABI alignment 10479 // for a type depending on the context. Give the target a chance to 10480 // specify the alignment it wants. 10481 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10482 Flags.setOrigAlign(OriginalAlignment); 10483 10484 if (Args[i].Ty->isPointerTy()) { 10485 Flags.setPointer(); 10486 Flags.setPointerAddrSpace( 10487 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10488 } 10489 if (Args[i].IsZExt) 10490 Flags.setZExt(); 10491 if (Args[i].IsSExt) 10492 Flags.setSExt(); 10493 if (Args[i].IsInReg) { 10494 // If we are using vectorcall calling convention, a structure that is 10495 // passed InReg - is surely an HVA 10496 if (CLI.CallConv == CallingConv::X86_VectorCall && 10497 isa<StructType>(FinalType)) { 10498 // The first value of a structure is marked 10499 if (0 == Value) 10500 Flags.setHvaStart(); 10501 Flags.setHva(); 10502 } 10503 // Set InReg Flag 10504 Flags.setInReg(); 10505 } 10506 if (Args[i].IsSRet) 10507 Flags.setSRet(); 10508 if (Args[i].IsSwiftSelf) 10509 Flags.setSwiftSelf(); 10510 if (Args[i].IsSwiftAsync) 10511 Flags.setSwiftAsync(); 10512 if (Args[i].IsSwiftError) 10513 Flags.setSwiftError(); 10514 if (Args[i].IsCFGuardTarget) 10515 Flags.setCFGuardTarget(); 10516 if (Args[i].IsByVal) 10517 Flags.setByVal(); 10518 if (Args[i].IsByRef) 10519 Flags.setByRef(); 10520 if (Args[i].IsPreallocated) { 10521 Flags.setPreallocated(); 10522 // Set the byval flag for CCAssignFn callbacks that don't know about 10523 // preallocated. This way we can know how many bytes we should've 10524 // allocated and how many bytes a callee cleanup function will pop. If 10525 // we port preallocated to more targets, we'll have to add custom 10526 // preallocated handling in the various CC lowering callbacks. 10527 Flags.setByVal(); 10528 } 10529 if (Args[i].IsInAlloca) { 10530 Flags.setInAlloca(); 10531 // Set the byval flag for CCAssignFn callbacks that don't know about 10532 // inalloca. This way we can know how many bytes we should've allocated 10533 // and how many bytes a callee cleanup function will pop. If we port 10534 // inalloca to more targets, we'll have to add custom inalloca handling 10535 // in the various CC lowering callbacks. 10536 Flags.setByVal(); 10537 } 10538 Align MemAlign; 10539 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10540 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10541 Flags.setByValSize(FrameSize); 10542 10543 // info is not there but there are cases it cannot get right. 10544 if (auto MA = Args[i].Alignment) 10545 MemAlign = *MA; 10546 else 10547 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10548 } else if (auto MA = Args[i].Alignment) { 10549 MemAlign = *MA; 10550 } else { 10551 MemAlign = OriginalAlignment; 10552 } 10553 Flags.setMemAlign(MemAlign); 10554 if (Args[i].IsNest) 10555 Flags.setNest(); 10556 if (NeedsRegBlock) 10557 Flags.setInConsecutiveRegs(); 10558 10559 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10560 CLI.CallConv, VT); 10561 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10562 CLI.CallConv, VT); 10563 SmallVector<SDValue, 4> Parts(NumParts); 10564 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10565 10566 if (Args[i].IsSExt) 10567 ExtendKind = ISD::SIGN_EXTEND; 10568 else if (Args[i].IsZExt) 10569 ExtendKind = ISD::ZERO_EXTEND; 10570 10571 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10572 // for now. 10573 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10574 CanLowerReturn) { 10575 assert((CLI.RetTy == Args[i].Ty || 10576 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10577 CLI.RetTy->getPointerAddressSpace() == 10578 Args[i].Ty->getPointerAddressSpace())) && 10579 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10580 // Before passing 'returned' to the target lowering code, ensure that 10581 // either the register MVT and the actual EVT are the same size or that 10582 // the return value and argument are extended in the same way; in these 10583 // cases it's safe to pass the argument register value unchanged as the 10584 // return register value (although it's at the target's option whether 10585 // to do so) 10586 // TODO: allow code generation to take advantage of partially preserved 10587 // registers rather than clobbering the entire register when the 10588 // parameter extension method is not compatible with the return 10589 // extension method 10590 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10591 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10592 CLI.RetZExt == Args[i].IsZExt)) 10593 Flags.setReturned(); 10594 } 10595 10596 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10597 CLI.CallConv, ExtendKind); 10598 10599 for (unsigned j = 0; j != NumParts; ++j) { 10600 // if it isn't first piece, alignment must be 1 10601 // For scalable vectors the scalable part is currently handled 10602 // by individual targets, so we just use the known minimum size here. 10603 ISD::OutputArg MyFlags( 10604 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10605 i < CLI.NumFixedArgs, i, 10606 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10607 if (NumParts > 1 && j == 0) 10608 MyFlags.Flags.setSplit(); 10609 else if (j != 0) { 10610 MyFlags.Flags.setOrigAlign(Align(1)); 10611 if (j == NumParts - 1) 10612 MyFlags.Flags.setSplitEnd(); 10613 } 10614 10615 CLI.Outs.push_back(MyFlags); 10616 CLI.OutVals.push_back(Parts[j]); 10617 } 10618 10619 if (NeedsRegBlock && Value == NumValues - 1) 10620 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10621 } 10622 } 10623 10624 SmallVector<SDValue, 4> InVals; 10625 CLI.Chain = LowerCall(CLI, InVals); 10626 10627 // Update CLI.InVals to use outside of this function. 10628 CLI.InVals = InVals; 10629 10630 // Verify that the target's LowerCall behaved as expected. 10631 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10632 "LowerCall didn't return a valid chain!"); 10633 assert((!CLI.IsTailCall || InVals.empty()) && 10634 "LowerCall emitted a return value for a tail call!"); 10635 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10636 "LowerCall didn't emit the correct number of values!"); 10637 10638 // For a tail call, the return value is merely live-out and there aren't 10639 // any nodes in the DAG representing it. Return a special value to 10640 // indicate that a tail call has been emitted and no more Instructions 10641 // should be processed in the current block. 10642 if (CLI.IsTailCall) { 10643 CLI.DAG.setRoot(CLI.Chain); 10644 return std::make_pair(SDValue(), SDValue()); 10645 } 10646 10647 #ifndef NDEBUG 10648 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10649 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10650 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10651 "LowerCall emitted a value with the wrong type!"); 10652 } 10653 #endif 10654 10655 SmallVector<SDValue, 4> ReturnValues; 10656 if (!CanLowerReturn) { 10657 // The instruction result is the result of loading from the 10658 // hidden sret parameter. 10659 SmallVector<EVT, 1> PVTs; 10660 Type *PtrRetTy = 10661 PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace()); 10662 10663 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10664 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10665 EVT PtrVT = PVTs[0]; 10666 10667 unsigned NumValues = RetTys.size(); 10668 ReturnValues.resize(NumValues); 10669 SmallVector<SDValue, 4> Chains(NumValues); 10670 10671 // An aggregate return value cannot wrap around the address space, so 10672 // offsets to its parts don't wrap either. 10673 SDNodeFlags Flags; 10674 Flags.setNoUnsignedWrap(true); 10675 10676 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10677 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10678 for (unsigned i = 0; i < NumValues; ++i) { 10679 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10680 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10681 PtrVT), Flags); 10682 SDValue L = CLI.DAG.getLoad( 10683 RetTys[i], CLI.DL, CLI.Chain, Add, 10684 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10685 DemoteStackIdx, Offsets[i]), 10686 HiddenSRetAlign); 10687 ReturnValues[i] = L; 10688 Chains[i] = L.getValue(1); 10689 } 10690 10691 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10692 } else { 10693 // Collect the legal value parts into potentially illegal values 10694 // that correspond to the original function's return values. 10695 std::optional<ISD::NodeType> AssertOp; 10696 if (CLI.RetSExt) 10697 AssertOp = ISD::AssertSext; 10698 else if (CLI.RetZExt) 10699 AssertOp = ISD::AssertZext; 10700 unsigned CurReg = 0; 10701 for (EVT VT : RetTys) { 10702 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10703 CLI.CallConv, VT); 10704 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10705 CLI.CallConv, VT); 10706 10707 ReturnValues.push_back(getCopyFromParts( 10708 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr, 10709 CLI.Chain, CLI.CallConv, AssertOp)); 10710 CurReg += NumRegs; 10711 } 10712 10713 // For a function returning void, there is no return value. We can't create 10714 // such a node, so we just return a null return value in that case. In 10715 // that case, nothing will actually look at the value. 10716 if (ReturnValues.empty()) 10717 return std::make_pair(SDValue(), CLI.Chain); 10718 } 10719 10720 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10721 CLI.DAG.getVTList(RetTys), ReturnValues); 10722 return std::make_pair(Res, CLI.Chain); 10723 } 10724 10725 /// Places new result values for the node in Results (their number 10726 /// and types must exactly match those of the original return values of 10727 /// the node), or leaves Results empty, which indicates that the node is not 10728 /// to be custom lowered after all. 10729 void TargetLowering::LowerOperationWrapper(SDNode *N, 10730 SmallVectorImpl<SDValue> &Results, 10731 SelectionDAG &DAG) const { 10732 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10733 10734 if (!Res.getNode()) 10735 return; 10736 10737 // If the original node has one result, take the return value from 10738 // LowerOperation as is. It might not be result number 0. 10739 if (N->getNumValues() == 1) { 10740 Results.push_back(Res); 10741 return; 10742 } 10743 10744 // If the original node has multiple results, then the return node should 10745 // have the same number of results. 10746 assert((N->getNumValues() == Res->getNumValues()) && 10747 "Lowering returned the wrong number of results!"); 10748 10749 // Places new result values base on N result number. 10750 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10751 Results.push_back(Res.getValue(I)); 10752 } 10753 10754 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10755 llvm_unreachable("LowerOperation not implemented for this target!"); 10756 } 10757 10758 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10759 unsigned Reg, 10760 ISD::NodeType ExtendType) { 10761 SDValue Op = getNonRegisterValue(V); 10762 assert((Op.getOpcode() != ISD::CopyFromReg || 10763 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10764 "Copy from a reg to the same reg!"); 10765 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10766 10767 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10768 // If this is an InlineAsm we have to match the registers required, not the 10769 // notional registers required by the type. 10770 10771 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10772 std::nullopt); // This is not an ABI copy. 10773 SDValue Chain = DAG.getEntryNode(); 10774 10775 if (ExtendType == ISD::ANY_EXTEND) { 10776 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10777 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10778 ExtendType = PreferredExtendIt->second; 10779 } 10780 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10781 PendingExports.push_back(Chain); 10782 } 10783 10784 #include "llvm/CodeGen/SelectionDAGISel.h" 10785 10786 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10787 /// entry block, return true. This includes arguments used by switches, since 10788 /// the switch may expand into multiple basic blocks. 10789 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10790 // With FastISel active, we may be splitting blocks, so force creation 10791 // of virtual registers for all non-dead arguments. 10792 if (FastISel) 10793 return A->use_empty(); 10794 10795 const BasicBlock &Entry = A->getParent()->front(); 10796 for (const User *U : A->users()) 10797 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10798 return false; // Use not in entry block. 10799 10800 return true; 10801 } 10802 10803 using ArgCopyElisionMapTy = 10804 DenseMap<const Argument *, 10805 std::pair<const AllocaInst *, const StoreInst *>>; 10806 10807 /// Scan the entry block of the function in FuncInfo for arguments that look 10808 /// like copies into a local alloca. Record any copied arguments in 10809 /// ArgCopyElisionCandidates. 10810 static void 10811 findArgumentCopyElisionCandidates(const DataLayout &DL, 10812 FunctionLoweringInfo *FuncInfo, 10813 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10814 // Record the state of every static alloca used in the entry block. Argument 10815 // allocas are all used in the entry block, so we need approximately as many 10816 // entries as we have arguments. 10817 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10818 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10819 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10820 StaticAllocas.reserve(NumArgs * 2); 10821 10822 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10823 if (!V) 10824 return nullptr; 10825 V = V->stripPointerCasts(); 10826 const auto *AI = dyn_cast<AllocaInst>(V); 10827 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10828 return nullptr; 10829 auto Iter = StaticAllocas.insert({AI, Unknown}); 10830 return &Iter.first->second; 10831 }; 10832 10833 // Look for stores of arguments to static allocas. Look through bitcasts and 10834 // GEPs to handle type coercions, as long as the alloca is fully initialized 10835 // by the store. Any non-store use of an alloca escapes it and any subsequent 10836 // unanalyzed store might write it. 10837 // FIXME: Handle structs initialized with multiple stores. 10838 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10839 // Look for stores, and handle non-store uses conservatively. 10840 const auto *SI = dyn_cast<StoreInst>(&I); 10841 if (!SI) { 10842 // We will look through cast uses, so ignore them completely. 10843 if (I.isCast()) 10844 continue; 10845 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10846 // to allocas. 10847 if (I.isDebugOrPseudoInst()) 10848 continue; 10849 // This is an unknown instruction. Assume it escapes or writes to all 10850 // static alloca operands. 10851 for (const Use &U : I.operands()) { 10852 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10853 *Info = StaticAllocaInfo::Clobbered; 10854 } 10855 continue; 10856 } 10857 10858 // If the stored value is a static alloca, mark it as escaped. 10859 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10860 *Info = StaticAllocaInfo::Clobbered; 10861 10862 // Check if the destination is a static alloca. 10863 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10864 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10865 if (!Info) 10866 continue; 10867 const AllocaInst *AI = cast<AllocaInst>(Dst); 10868 10869 // Skip allocas that have been initialized or clobbered. 10870 if (*Info != StaticAllocaInfo::Unknown) 10871 continue; 10872 10873 // Check if the stored value is an argument, and that this store fully 10874 // initializes the alloca. 10875 // If the argument type has padding bits we can't directly forward a pointer 10876 // as the upper bits may contain garbage. 10877 // Don't elide copies from the same argument twice. 10878 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10879 const auto *Arg = dyn_cast<Argument>(Val); 10880 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10881 Arg->getType()->isEmptyTy() || 10882 DL.getTypeStoreSize(Arg->getType()) != 10883 DL.getTypeAllocSize(AI->getAllocatedType()) || 10884 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10885 ArgCopyElisionCandidates.count(Arg)) { 10886 *Info = StaticAllocaInfo::Clobbered; 10887 continue; 10888 } 10889 10890 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10891 << '\n'); 10892 10893 // Mark this alloca and store for argument copy elision. 10894 *Info = StaticAllocaInfo::Elidable; 10895 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10896 10897 // Stop scanning if we've seen all arguments. This will happen early in -O0 10898 // builds, which is useful, because -O0 builds have large entry blocks and 10899 // many allocas. 10900 if (ArgCopyElisionCandidates.size() == NumArgs) 10901 break; 10902 } 10903 } 10904 10905 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10906 /// ArgVal is a load from a suitable fixed stack object. 10907 static void tryToElideArgumentCopy( 10908 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10909 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10910 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10911 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10912 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10913 // Check if this is a load from a fixed stack object. 10914 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10915 if (!LNode) 10916 return; 10917 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10918 if (!FINode) 10919 return; 10920 10921 // Check that the fixed stack object is the right size and alignment. 10922 // Look at the alignment that the user wrote on the alloca instead of looking 10923 // at the stack object. 10924 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10925 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10926 const AllocaInst *AI = ArgCopyIter->second.first; 10927 int FixedIndex = FINode->getIndex(); 10928 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10929 int OldIndex = AllocaIndex; 10930 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10931 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10932 LLVM_DEBUG( 10933 dbgs() << " argument copy elision failed due to bad fixed stack " 10934 "object size\n"); 10935 return; 10936 } 10937 Align RequiredAlignment = AI->getAlign(); 10938 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10939 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10940 "greater than stack argument alignment (" 10941 << DebugStr(RequiredAlignment) << " vs " 10942 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10943 return; 10944 } 10945 10946 // Perform the elision. Delete the old stack object and replace its only use 10947 // in the variable info map. Mark the stack object as mutable. 10948 LLVM_DEBUG({ 10949 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10950 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10951 << '\n'; 10952 }); 10953 MFI.RemoveStackObject(OldIndex); 10954 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10955 AllocaIndex = FixedIndex; 10956 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10957 for (SDValue ArgVal : ArgVals) 10958 Chains.push_back(ArgVal.getValue(1)); 10959 10960 // Avoid emitting code for the store implementing the copy. 10961 const StoreInst *SI = ArgCopyIter->second.second; 10962 ElidedArgCopyInstrs.insert(SI); 10963 10964 // Check for uses of the argument again so that we can avoid exporting ArgVal 10965 // if it is't used by anything other than the store. 10966 for (const Value *U : Arg.users()) { 10967 if (U != SI) { 10968 ArgHasUses = true; 10969 break; 10970 } 10971 } 10972 } 10973 10974 void SelectionDAGISel::LowerArguments(const Function &F) { 10975 SelectionDAG &DAG = SDB->DAG; 10976 SDLoc dl = SDB->getCurSDLoc(); 10977 const DataLayout &DL = DAG.getDataLayout(); 10978 SmallVector<ISD::InputArg, 16> Ins; 10979 10980 // In Naked functions we aren't going to save any registers. 10981 if (F.hasFnAttribute(Attribute::Naked)) 10982 return; 10983 10984 if (!FuncInfo->CanLowerReturn) { 10985 // Put in an sret pointer parameter before all the other parameters. 10986 SmallVector<EVT, 1> ValueVTs; 10987 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10988 PointerType::get(F.getContext(), 10989 DAG.getDataLayout().getAllocaAddrSpace()), 10990 ValueVTs); 10991 10992 // NOTE: Assuming that a pointer will never break down to more than one VT 10993 // or one register. 10994 ISD::ArgFlagsTy Flags; 10995 Flags.setSRet(); 10996 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10997 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10998 ISD::InputArg::NoArgIndex, 0); 10999 Ins.push_back(RetArg); 11000 } 11001 11002 // Look for stores of arguments to static allocas. Mark such arguments with a 11003 // flag to ask the target to give us the memory location of that argument if 11004 // available. 11005 ArgCopyElisionMapTy ArgCopyElisionCandidates; 11006 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 11007 ArgCopyElisionCandidates); 11008 11009 // Set up the incoming argument description vector. 11010 for (const Argument &Arg : F.args()) { 11011 unsigned ArgNo = Arg.getArgNo(); 11012 SmallVector<EVT, 4> ValueVTs; 11013 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11014 bool isArgValueUsed = !Arg.use_empty(); 11015 unsigned PartBase = 0; 11016 Type *FinalType = Arg.getType(); 11017 if (Arg.hasAttribute(Attribute::ByVal)) 11018 FinalType = Arg.getParamByValType(); 11019 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 11020 FinalType, F.getCallingConv(), F.isVarArg(), DL); 11021 for (unsigned Value = 0, NumValues = ValueVTs.size(); 11022 Value != NumValues; ++Value) { 11023 EVT VT = ValueVTs[Value]; 11024 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 11025 ISD::ArgFlagsTy Flags; 11026 11027 11028 if (Arg.getType()->isPointerTy()) { 11029 Flags.setPointer(); 11030 Flags.setPointerAddrSpace( 11031 cast<PointerType>(Arg.getType())->getAddressSpace()); 11032 } 11033 if (Arg.hasAttribute(Attribute::ZExt)) 11034 Flags.setZExt(); 11035 if (Arg.hasAttribute(Attribute::SExt)) 11036 Flags.setSExt(); 11037 if (Arg.hasAttribute(Attribute::InReg)) { 11038 // If we are using vectorcall calling convention, a structure that is 11039 // passed InReg - is surely an HVA 11040 if (F.getCallingConv() == CallingConv::X86_VectorCall && 11041 isa<StructType>(Arg.getType())) { 11042 // The first value of a structure is marked 11043 if (0 == Value) 11044 Flags.setHvaStart(); 11045 Flags.setHva(); 11046 } 11047 // Set InReg Flag 11048 Flags.setInReg(); 11049 } 11050 if (Arg.hasAttribute(Attribute::StructRet)) 11051 Flags.setSRet(); 11052 if (Arg.hasAttribute(Attribute::SwiftSelf)) 11053 Flags.setSwiftSelf(); 11054 if (Arg.hasAttribute(Attribute::SwiftAsync)) 11055 Flags.setSwiftAsync(); 11056 if (Arg.hasAttribute(Attribute::SwiftError)) 11057 Flags.setSwiftError(); 11058 if (Arg.hasAttribute(Attribute::ByVal)) 11059 Flags.setByVal(); 11060 if (Arg.hasAttribute(Attribute::ByRef)) 11061 Flags.setByRef(); 11062 if (Arg.hasAttribute(Attribute::InAlloca)) { 11063 Flags.setInAlloca(); 11064 // Set the byval flag for CCAssignFn callbacks that don't know about 11065 // inalloca. This way we can know how many bytes we should've allocated 11066 // and how many bytes a callee cleanup function will pop. If we port 11067 // inalloca to more targets, we'll have to add custom inalloca handling 11068 // in the various CC lowering callbacks. 11069 Flags.setByVal(); 11070 } 11071 if (Arg.hasAttribute(Attribute::Preallocated)) { 11072 Flags.setPreallocated(); 11073 // Set the byval flag for CCAssignFn callbacks that don't know about 11074 // preallocated. This way we can know how many bytes we should've 11075 // allocated and how many bytes a callee cleanup function will pop. If 11076 // we port preallocated to more targets, we'll have to add custom 11077 // preallocated handling in the various CC lowering callbacks. 11078 Flags.setByVal(); 11079 } 11080 11081 // Certain targets (such as MIPS), may have a different ABI alignment 11082 // for a type depending on the context. Give the target a chance to 11083 // specify the alignment it wants. 11084 const Align OriginalAlignment( 11085 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 11086 Flags.setOrigAlign(OriginalAlignment); 11087 11088 Align MemAlign; 11089 Type *ArgMemTy = nullptr; 11090 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 11091 Flags.isByRef()) { 11092 if (!ArgMemTy) 11093 ArgMemTy = Arg.getPointeeInMemoryValueType(); 11094 11095 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 11096 11097 // For in-memory arguments, size and alignment should be passed from FE. 11098 // BE will guess if this info is not there but there are cases it cannot 11099 // get right. 11100 if (auto ParamAlign = Arg.getParamStackAlign()) 11101 MemAlign = *ParamAlign; 11102 else if ((ParamAlign = Arg.getParamAlign())) 11103 MemAlign = *ParamAlign; 11104 else 11105 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 11106 if (Flags.isByRef()) 11107 Flags.setByRefSize(MemSize); 11108 else 11109 Flags.setByValSize(MemSize); 11110 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 11111 MemAlign = *ParamAlign; 11112 } else { 11113 MemAlign = OriginalAlignment; 11114 } 11115 Flags.setMemAlign(MemAlign); 11116 11117 if (Arg.hasAttribute(Attribute::Nest)) 11118 Flags.setNest(); 11119 if (NeedsRegBlock) 11120 Flags.setInConsecutiveRegs(); 11121 if (ArgCopyElisionCandidates.count(&Arg)) 11122 Flags.setCopyElisionCandidate(); 11123 if (Arg.hasAttribute(Attribute::Returned)) 11124 Flags.setReturned(); 11125 11126 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 11127 *CurDAG->getContext(), F.getCallingConv(), VT); 11128 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 11129 *CurDAG->getContext(), F.getCallingConv(), VT); 11130 for (unsigned i = 0; i != NumRegs; ++i) { 11131 // For scalable vectors, use the minimum size; individual targets 11132 // are responsible for handling scalable vector arguments and 11133 // return values. 11134 ISD::InputArg MyFlags( 11135 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 11136 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 11137 if (NumRegs > 1 && i == 0) 11138 MyFlags.Flags.setSplit(); 11139 // if it isn't first piece, alignment must be 1 11140 else if (i > 0) { 11141 MyFlags.Flags.setOrigAlign(Align(1)); 11142 if (i == NumRegs - 1) 11143 MyFlags.Flags.setSplitEnd(); 11144 } 11145 Ins.push_back(MyFlags); 11146 } 11147 if (NeedsRegBlock && Value == NumValues - 1) 11148 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 11149 PartBase += VT.getStoreSize().getKnownMinValue(); 11150 } 11151 } 11152 11153 // Call the target to set up the argument values. 11154 SmallVector<SDValue, 8> InVals; 11155 SDValue NewRoot = TLI->LowerFormalArguments( 11156 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 11157 11158 // Verify that the target's LowerFormalArguments behaved as expected. 11159 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 11160 "LowerFormalArguments didn't return a valid chain!"); 11161 assert(InVals.size() == Ins.size() && 11162 "LowerFormalArguments didn't emit the correct number of values!"); 11163 LLVM_DEBUG({ 11164 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 11165 assert(InVals[i].getNode() && 11166 "LowerFormalArguments emitted a null value!"); 11167 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 11168 "LowerFormalArguments emitted a value with the wrong type!"); 11169 } 11170 }); 11171 11172 // Update the DAG with the new chain value resulting from argument lowering. 11173 DAG.setRoot(NewRoot); 11174 11175 // Set up the argument values. 11176 unsigned i = 0; 11177 if (!FuncInfo->CanLowerReturn) { 11178 // Create a virtual register for the sret pointer, and put in a copy 11179 // from the sret argument into it. 11180 SmallVector<EVT, 1> ValueVTs; 11181 ComputeValueVTs(*TLI, DAG.getDataLayout(), 11182 PointerType::get(F.getContext(), 11183 DAG.getDataLayout().getAllocaAddrSpace()), 11184 ValueVTs); 11185 MVT VT = ValueVTs[0].getSimpleVT(); 11186 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 11187 std::optional<ISD::NodeType> AssertOp; 11188 SDValue ArgValue = 11189 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot, 11190 F.getCallingConv(), AssertOp); 11191 11192 MachineFunction& MF = SDB->DAG.getMachineFunction(); 11193 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 11194 Register SRetReg = 11195 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 11196 FuncInfo->DemoteRegister = SRetReg; 11197 NewRoot = 11198 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 11199 DAG.setRoot(NewRoot); 11200 11201 // i indexes lowered arguments. Bump it past the hidden sret argument. 11202 ++i; 11203 } 11204 11205 SmallVector<SDValue, 4> Chains; 11206 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 11207 for (const Argument &Arg : F.args()) { 11208 SmallVector<SDValue, 4> ArgValues; 11209 SmallVector<EVT, 4> ValueVTs; 11210 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 11211 unsigned NumValues = ValueVTs.size(); 11212 if (NumValues == 0) 11213 continue; 11214 11215 bool ArgHasUses = !Arg.use_empty(); 11216 11217 // Elide the copying store if the target loaded this argument from a 11218 // suitable fixed stack object. 11219 if (Ins[i].Flags.isCopyElisionCandidate()) { 11220 unsigned NumParts = 0; 11221 for (EVT VT : ValueVTs) 11222 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 11223 F.getCallingConv(), VT); 11224 11225 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 11226 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 11227 ArrayRef(&InVals[i], NumParts), ArgHasUses); 11228 } 11229 11230 // If this argument is unused then remember its value. It is used to generate 11231 // debugging information. 11232 bool isSwiftErrorArg = 11233 TLI->supportSwiftError() && 11234 Arg.hasAttribute(Attribute::SwiftError); 11235 if (!ArgHasUses && !isSwiftErrorArg) { 11236 SDB->setUnusedArgValue(&Arg, InVals[i]); 11237 11238 // Also remember any frame index for use in FastISel. 11239 if (FrameIndexSDNode *FI = 11240 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 11241 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11242 } 11243 11244 for (unsigned Val = 0; Val != NumValues; ++Val) { 11245 EVT VT = ValueVTs[Val]; 11246 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 11247 F.getCallingConv(), VT); 11248 unsigned NumParts = TLI->getNumRegistersForCallingConv( 11249 *CurDAG->getContext(), F.getCallingConv(), VT); 11250 11251 // Even an apparent 'unused' swifterror argument needs to be returned. So 11252 // we do generate a copy for it that can be used on return from the 11253 // function. 11254 if (ArgHasUses || isSwiftErrorArg) { 11255 std::optional<ISD::NodeType> AssertOp; 11256 if (Arg.hasAttribute(Attribute::SExt)) 11257 AssertOp = ISD::AssertSext; 11258 else if (Arg.hasAttribute(Attribute::ZExt)) 11259 AssertOp = ISD::AssertZext; 11260 11261 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 11262 PartVT, VT, nullptr, NewRoot, 11263 F.getCallingConv(), AssertOp)); 11264 } 11265 11266 i += NumParts; 11267 } 11268 11269 // We don't need to do anything else for unused arguments. 11270 if (ArgValues.empty()) 11271 continue; 11272 11273 // Note down frame index. 11274 if (FrameIndexSDNode *FI = 11275 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 11276 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11277 11278 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 11279 SDB->getCurSDLoc()); 11280 11281 SDB->setValue(&Arg, Res); 11282 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 11283 // We want to associate the argument with the frame index, among 11284 // involved operands, that correspond to the lowest address. The 11285 // getCopyFromParts function, called earlier, is swapping the order of 11286 // the operands to BUILD_PAIR depending on endianness. The result of 11287 // that swapping is that the least significant bits of the argument will 11288 // be in the first operand of the BUILD_PAIR node, and the most 11289 // significant bits will be in the second operand. 11290 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 11291 if (LoadSDNode *LNode = 11292 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 11293 if (FrameIndexSDNode *FI = 11294 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 11295 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11296 } 11297 11298 // Analyses past this point are naive and don't expect an assertion. 11299 if (Res.getOpcode() == ISD::AssertZext) 11300 Res = Res.getOperand(0); 11301 11302 // Update the SwiftErrorVRegDefMap. 11303 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11304 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11305 if (Register::isVirtualRegister(Reg)) 11306 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11307 Reg); 11308 } 11309 11310 // If this argument is live outside of the entry block, insert a copy from 11311 // wherever we got it to the vreg that other BB's will reference it as. 11312 if (Res.getOpcode() == ISD::CopyFromReg) { 11313 // If we can, though, try to skip creating an unnecessary vreg. 11314 // FIXME: This isn't very clean... it would be nice to make this more 11315 // general. 11316 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11317 if (Register::isVirtualRegister(Reg)) { 11318 FuncInfo->ValueMap[&Arg] = Reg; 11319 continue; 11320 } 11321 } 11322 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11323 FuncInfo->InitializeRegForValue(&Arg); 11324 SDB->CopyToExportRegsIfNeeded(&Arg); 11325 } 11326 } 11327 11328 if (!Chains.empty()) { 11329 Chains.push_back(NewRoot); 11330 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11331 } 11332 11333 DAG.setRoot(NewRoot); 11334 11335 assert(i == InVals.size() && "Argument register count mismatch!"); 11336 11337 // If any argument copy elisions occurred and we have debug info, update the 11338 // stale frame indices used in the dbg.declare variable info table. 11339 if (!ArgCopyElisionFrameIndexMap.empty()) { 11340 for (MachineFunction::VariableDbgInfo &VI : 11341 MF->getInStackSlotVariableDbgInfo()) { 11342 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11343 if (I != ArgCopyElisionFrameIndexMap.end()) 11344 VI.updateStackSlot(I->second); 11345 } 11346 } 11347 11348 // Finally, if the target has anything special to do, allow it to do so. 11349 emitFunctionEntryCode(); 11350 } 11351 11352 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11353 /// ensure constants are generated when needed. Remember the virtual registers 11354 /// that need to be added to the Machine PHI nodes as input. We cannot just 11355 /// directly add them, because expansion might result in multiple MBB's for one 11356 /// BB. As such, the start of the BB might correspond to a different MBB than 11357 /// the end. 11358 void 11359 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11360 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11361 11362 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11363 11364 // Check PHI nodes in successors that expect a value to be available from this 11365 // block. 11366 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11367 if (!isa<PHINode>(SuccBB->begin())) continue; 11368 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11369 11370 // If this terminator has multiple identical successors (common for 11371 // switches), only handle each succ once. 11372 if (!SuccsHandled.insert(SuccMBB).second) 11373 continue; 11374 11375 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11376 11377 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11378 // nodes and Machine PHI nodes, but the incoming operands have not been 11379 // emitted yet. 11380 for (const PHINode &PN : SuccBB->phis()) { 11381 // Ignore dead phi's. 11382 if (PN.use_empty()) 11383 continue; 11384 11385 // Skip empty types 11386 if (PN.getType()->isEmptyTy()) 11387 continue; 11388 11389 unsigned Reg; 11390 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11391 11392 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11393 unsigned &RegOut = ConstantsOut[C]; 11394 if (RegOut == 0) { 11395 RegOut = FuncInfo.CreateRegs(C); 11396 // We need to zero/sign extend ConstantInt phi operands to match 11397 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11398 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11399 if (auto *CI = dyn_cast<ConstantInt>(C)) 11400 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11401 : ISD::ZERO_EXTEND; 11402 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11403 } 11404 Reg = RegOut; 11405 } else { 11406 DenseMap<const Value *, Register>::iterator I = 11407 FuncInfo.ValueMap.find(PHIOp); 11408 if (I != FuncInfo.ValueMap.end()) 11409 Reg = I->second; 11410 else { 11411 assert(isa<AllocaInst>(PHIOp) && 11412 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11413 "Didn't codegen value into a register!??"); 11414 Reg = FuncInfo.CreateRegs(PHIOp); 11415 CopyValueToVirtualRegister(PHIOp, Reg); 11416 } 11417 } 11418 11419 // Remember that this register needs to added to the machine PHI node as 11420 // the input for this MBB. 11421 SmallVector<EVT, 4> ValueVTs; 11422 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11423 for (EVT VT : ValueVTs) { 11424 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11425 for (unsigned i = 0; i != NumRegisters; ++i) 11426 FuncInfo.PHINodesToUpdate.push_back( 11427 std::make_pair(&*MBBI++, Reg + i)); 11428 Reg += NumRegisters; 11429 } 11430 } 11431 } 11432 11433 ConstantsOut.clear(); 11434 } 11435 11436 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11437 MachineFunction::iterator I(MBB); 11438 if (++I == FuncInfo.MF->end()) 11439 return nullptr; 11440 return &*I; 11441 } 11442 11443 /// During lowering new call nodes can be created (such as memset, etc.). 11444 /// Those will become new roots of the current DAG, but complications arise 11445 /// when they are tail calls. In such cases, the call lowering will update 11446 /// the root, but the builder still needs to know that a tail call has been 11447 /// lowered in order to avoid generating an additional return. 11448 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11449 // If the node is null, we do have a tail call. 11450 if (MaybeTC.getNode() != nullptr) 11451 DAG.setRoot(MaybeTC); 11452 else 11453 HasTailCall = true; 11454 } 11455 11456 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11457 MachineBasicBlock *SwitchMBB, 11458 MachineBasicBlock *DefaultMBB) { 11459 MachineFunction *CurMF = FuncInfo.MF; 11460 MachineBasicBlock *NextMBB = nullptr; 11461 MachineFunction::iterator BBI(W.MBB); 11462 if (++BBI != FuncInfo.MF->end()) 11463 NextMBB = &*BBI; 11464 11465 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11466 11467 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11468 11469 if (Size == 2 && W.MBB == SwitchMBB) { 11470 // If any two of the cases has the same destination, and if one value 11471 // is the same as the other, but has one bit unset that the other has set, 11472 // use bit manipulation to do two compares at once. For example: 11473 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11474 // TODO: This could be extended to merge any 2 cases in switches with 3 11475 // cases. 11476 // TODO: Handle cases where W.CaseBB != SwitchBB. 11477 CaseCluster &Small = *W.FirstCluster; 11478 CaseCluster &Big = *W.LastCluster; 11479 11480 if (Small.Low == Small.High && Big.Low == Big.High && 11481 Small.MBB == Big.MBB) { 11482 const APInt &SmallValue = Small.Low->getValue(); 11483 const APInt &BigValue = Big.Low->getValue(); 11484 11485 // Check that there is only one bit different. 11486 APInt CommonBit = BigValue ^ SmallValue; 11487 if (CommonBit.isPowerOf2()) { 11488 SDValue CondLHS = getValue(Cond); 11489 EVT VT = CondLHS.getValueType(); 11490 SDLoc DL = getCurSDLoc(); 11491 11492 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11493 DAG.getConstant(CommonBit, DL, VT)); 11494 SDValue Cond = DAG.getSetCC( 11495 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11496 ISD::SETEQ); 11497 11498 // Update successor info. 11499 // Both Small and Big will jump to Small.BB, so we sum up the 11500 // probabilities. 11501 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11502 if (BPI) 11503 addSuccessorWithProb( 11504 SwitchMBB, DefaultMBB, 11505 // The default destination is the first successor in IR. 11506 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11507 else 11508 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11509 11510 // Insert the true branch. 11511 SDValue BrCond = 11512 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11513 DAG.getBasicBlock(Small.MBB)); 11514 // Insert the false branch. 11515 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11516 DAG.getBasicBlock(DefaultMBB)); 11517 11518 DAG.setRoot(BrCond); 11519 return; 11520 } 11521 } 11522 } 11523 11524 if (TM.getOptLevel() != CodeGenOptLevel::None) { 11525 // Here, we order cases by probability so the most likely case will be 11526 // checked first. However, two clusters can have the same probability in 11527 // which case their relative ordering is non-deterministic. So we use Low 11528 // as a tie-breaker as clusters are guaranteed to never overlap. 11529 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11530 [](const CaseCluster &a, const CaseCluster &b) { 11531 return a.Prob != b.Prob ? 11532 a.Prob > b.Prob : 11533 a.Low->getValue().slt(b.Low->getValue()); 11534 }); 11535 11536 // Rearrange the case blocks so that the last one falls through if possible 11537 // without changing the order of probabilities. 11538 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11539 --I; 11540 if (I->Prob > W.LastCluster->Prob) 11541 break; 11542 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11543 std::swap(*I, *W.LastCluster); 11544 break; 11545 } 11546 } 11547 } 11548 11549 // Compute total probability. 11550 BranchProbability DefaultProb = W.DefaultProb; 11551 BranchProbability UnhandledProbs = DefaultProb; 11552 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11553 UnhandledProbs += I->Prob; 11554 11555 MachineBasicBlock *CurMBB = W.MBB; 11556 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11557 bool FallthroughUnreachable = false; 11558 MachineBasicBlock *Fallthrough; 11559 if (I == W.LastCluster) { 11560 // For the last cluster, fall through to the default destination. 11561 Fallthrough = DefaultMBB; 11562 FallthroughUnreachable = isa<UnreachableInst>( 11563 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11564 } else { 11565 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11566 CurMF->insert(BBI, Fallthrough); 11567 // Put Cond in a virtual register to make it available from the new blocks. 11568 ExportFromCurrentBlock(Cond); 11569 } 11570 UnhandledProbs -= I->Prob; 11571 11572 switch (I->Kind) { 11573 case CC_JumpTable: { 11574 // FIXME: Optimize away range check based on pivot comparisons. 11575 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11576 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11577 11578 // The jump block hasn't been inserted yet; insert it here. 11579 MachineBasicBlock *JumpMBB = JT->MBB; 11580 CurMF->insert(BBI, JumpMBB); 11581 11582 auto JumpProb = I->Prob; 11583 auto FallthroughProb = UnhandledProbs; 11584 11585 // If the default statement is a target of the jump table, we evenly 11586 // distribute the default probability to successors of CurMBB. Also 11587 // update the probability on the edge from JumpMBB to Fallthrough. 11588 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11589 SE = JumpMBB->succ_end(); 11590 SI != SE; ++SI) { 11591 if (*SI == DefaultMBB) { 11592 JumpProb += DefaultProb / 2; 11593 FallthroughProb -= DefaultProb / 2; 11594 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11595 JumpMBB->normalizeSuccProbs(); 11596 break; 11597 } 11598 } 11599 11600 // If the default clause is unreachable, propagate that knowledge into 11601 // JTH->FallthroughUnreachable which will use it to suppress the range 11602 // check. 11603 // 11604 // However, don't do this if we're doing branch target enforcement, 11605 // because a table branch _without_ a range check can be a tempting JOP 11606 // gadget - out-of-bounds inputs that are impossible in correct 11607 // execution become possible again if an attacker can influence the 11608 // control flow. So if an attacker doesn't already have a BTI bypass 11609 // available, we don't want them to be able to get one out of this 11610 // table branch. 11611 if (FallthroughUnreachable) { 11612 Function &CurFunc = CurMF->getFunction(); 11613 bool HasBranchTargetEnforcement = false; 11614 if (CurFunc.hasFnAttribute("branch-target-enforcement")) { 11615 HasBranchTargetEnforcement = 11616 CurFunc.getFnAttribute("branch-target-enforcement") 11617 .getValueAsBool(); 11618 } else { 11619 HasBranchTargetEnforcement = 11620 CurMF->getMMI().getModule()->getModuleFlag( 11621 "branch-target-enforcement"); 11622 } 11623 if (!HasBranchTargetEnforcement) 11624 JTH->FallthroughUnreachable = true; 11625 } 11626 11627 if (!JTH->FallthroughUnreachable) 11628 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11629 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11630 CurMBB->normalizeSuccProbs(); 11631 11632 // The jump table header will be inserted in our current block, do the 11633 // range check, and fall through to our fallthrough block. 11634 JTH->HeaderBB = CurMBB; 11635 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11636 11637 // If we're in the right place, emit the jump table header right now. 11638 if (CurMBB == SwitchMBB) { 11639 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11640 JTH->Emitted = true; 11641 } 11642 break; 11643 } 11644 case CC_BitTests: { 11645 // FIXME: Optimize away range check based on pivot comparisons. 11646 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11647 11648 // The bit test blocks haven't been inserted yet; insert them here. 11649 for (BitTestCase &BTC : BTB->Cases) 11650 CurMF->insert(BBI, BTC.ThisBB); 11651 11652 // Fill in fields of the BitTestBlock. 11653 BTB->Parent = CurMBB; 11654 BTB->Default = Fallthrough; 11655 11656 BTB->DefaultProb = UnhandledProbs; 11657 // If the cases in bit test don't form a contiguous range, we evenly 11658 // distribute the probability on the edge to Fallthrough to two 11659 // successors of CurMBB. 11660 if (!BTB->ContiguousRange) { 11661 BTB->Prob += DefaultProb / 2; 11662 BTB->DefaultProb -= DefaultProb / 2; 11663 } 11664 11665 if (FallthroughUnreachable) 11666 BTB->FallthroughUnreachable = true; 11667 11668 // If we're in the right place, emit the bit test header right now. 11669 if (CurMBB == SwitchMBB) { 11670 visitBitTestHeader(*BTB, SwitchMBB); 11671 BTB->Emitted = true; 11672 } 11673 break; 11674 } 11675 case CC_Range: { 11676 const Value *RHS, *LHS, *MHS; 11677 ISD::CondCode CC; 11678 if (I->Low == I->High) { 11679 // Check Cond == I->Low. 11680 CC = ISD::SETEQ; 11681 LHS = Cond; 11682 RHS=I->Low; 11683 MHS = nullptr; 11684 } else { 11685 // Check I->Low <= Cond <= I->High. 11686 CC = ISD::SETLE; 11687 LHS = I->Low; 11688 MHS = Cond; 11689 RHS = I->High; 11690 } 11691 11692 // If Fallthrough is unreachable, fold away the comparison. 11693 if (FallthroughUnreachable) 11694 CC = ISD::SETTRUE; 11695 11696 // The false probability is the sum of all unhandled cases. 11697 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11698 getCurSDLoc(), I->Prob, UnhandledProbs); 11699 11700 if (CurMBB == SwitchMBB) 11701 visitSwitchCase(CB, SwitchMBB); 11702 else 11703 SL->SwitchCases.push_back(CB); 11704 11705 break; 11706 } 11707 } 11708 CurMBB = Fallthrough; 11709 } 11710 } 11711 11712 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11713 const SwitchWorkListItem &W, 11714 Value *Cond, 11715 MachineBasicBlock *SwitchMBB) { 11716 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11717 "Clusters not sorted?"); 11718 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11719 11720 auto [LastLeft, FirstRight, LeftProb, RightProb] = 11721 SL->computeSplitWorkItemInfo(W); 11722 11723 // Use the first element on the right as pivot since we will make less-than 11724 // comparisons against it. 11725 CaseClusterIt PivotCluster = FirstRight; 11726 assert(PivotCluster > W.FirstCluster); 11727 assert(PivotCluster <= W.LastCluster); 11728 11729 CaseClusterIt FirstLeft = W.FirstCluster; 11730 CaseClusterIt LastRight = W.LastCluster; 11731 11732 const ConstantInt *Pivot = PivotCluster->Low; 11733 11734 // New blocks will be inserted immediately after the current one. 11735 MachineFunction::iterator BBI(W.MBB); 11736 ++BBI; 11737 11738 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11739 // we can branch to its destination directly if it's squeezed exactly in 11740 // between the known lower bound and Pivot - 1. 11741 MachineBasicBlock *LeftMBB; 11742 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11743 FirstLeft->Low == W.GE && 11744 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11745 LeftMBB = FirstLeft->MBB; 11746 } else { 11747 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11748 FuncInfo.MF->insert(BBI, LeftMBB); 11749 WorkList.push_back( 11750 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11751 // Put Cond in a virtual register to make it available from the new blocks. 11752 ExportFromCurrentBlock(Cond); 11753 } 11754 11755 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11756 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11757 // directly if RHS.High equals the current upper bound. 11758 MachineBasicBlock *RightMBB; 11759 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11760 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11761 RightMBB = FirstRight->MBB; 11762 } else { 11763 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11764 FuncInfo.MF->insert(BBI, RightMBB); 11765 WorkList.push_back( 11766 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11767 // Put Cond in a virtual register to make it available from the new blocks. 11768 ExportFromCurrentBlock(Cond); 11769 } 11770 11771 // Create the CaseBlock record that will be used to lower the branch. 11772 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11773 getCurSDLoc(), LeftProb, RightProb); 11774 11775 if (W.MBB == SwitchMBB) 11776 visitSwitchCase(CB, SwitchMBB); 11777 else 11778 SL->SwitchCases.push_back(CB); 11779 } 11780 11781 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11782 // from the swith statement. 11783 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11784 BranchProbability PeeledCaseProb) { 11785 if (PeeledCaseProb == BranchProbability::getOne()) 11786 return BranchProbability::getZero(); 11787 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11788 11789 uint32_t Numerator = CaseProb.getNumerator(); 11790 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11791 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11792 } 11793 11794 // Try to peel the top probability case if it exceeds the threshold. 11795 // Return current MachineBasicBlock for the switch statement if the peeling 11796 // does not occur. 11797 // If the peeling is performed, return the newly created MachineBasicBlock 11798 // for the peeled switch statement. Also update Clusters to remove the peeled 11799 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11800 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11801 const SwitchInst &SI, CaseClusterVector &Clusters, 11802 BranchProbability &PeeledCaseProb) { 11803 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11804 // Don't perform if there is only one cluster or optimizing for size. 11805 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11806 TM.getOptLevel() == CodeGenOptLevel::None || 11807 SwitchMBB->getParent()->getFunction().hasMinSize()) 11808 return SwitchMBB; 11809 11810 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11811 unsigned PeeledCaseIndex = 0; 11812 bool SwitchPeeled = false; 11813 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11814 CaseCluster &CC = Clusters[Index]; 11815 if (CC.Prob < TopCaseProb) 11816 continue; 11817 TopCaseProb = CC.Prob; 11818 PeeledCaseIndex = Index; 11819 SwitchPeeled = true; 11820 } 11821 if (!SwitchPeeled) 11822 return SwitchMBB; 11823 11824 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11825 << TopCaseProb << "\n"); 11826 11827 // Record the MBB for the peeled switch statement. 11828 MachineFunction::iterator BBI(SwitchMBB); 11829 ++BBI; 11830 MachineBasicBlock *PeeledSwitchMBB = 11831 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11832 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11833 11834 ExportFromCurrentBlock(SI.getCondition()); 11835 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11836 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11837 nullptr, nullptr, TopCaseProb.getCompl()}; 11838 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11839 11840 Clusters.erase(PeeledCaseIt); 11841 for (CaseCluster &CC : Clusters) { 11842 LLVM_DEBUG( 11843 dbgs() << "Scale the probablity for one cluster, before scaling: " 11844 << CC.Prob << "\n"); 11845 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11846 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11847 } 11848 PeeledCaseProb = TopCaseProb; 11849 return PeeledSwitchMBB; 11850 } 11851 11852 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11853 // Extract cases from the switch. 11854 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11855 CaseClusterVector Clusters; 11856 Clusters.reserve(SI.getNumCases()); 11857 for (auto I : SI.cases()) { 11858 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11859 const ConstantInt *CaseVal = I.getCaseValue(); 11860 BranchProbability Prob = 11861 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11862 : BranchProbability(1, SI.getNumCases() + 1); 11863 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11864 } 11865 11866 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11867 11868 // Cluster adjacent cases with the same destination. We do this at all 11869 // optimization levels because it's cheap to do and will make codegen faster 11870 // if there are many clusters. 11871 sortAndRangeify(Clusters); 11872 11873 // The branch probablity of the peeled case. 11874 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11875 MachineBasicBlock *PeeledSwitchMBB = 11876 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11877 11878 // If there is only the default destination, jump there directly. 11879 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11880 if (Clusters.empty()) { 11881 assert(PeeledSwitchMBB == SwitchMBB); 11882 SwitchMBB->addSuccessor(DefaultMBB); 11883 if (DefaultMBB != NextBlock(SwitchMBB)) { 11884 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11885 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11886 } 11887 return; 11888 } 11889 11890 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(), 11891 DAG.getBFI()); 11892 SL->findBitTestClusters(Clusters, &SI); 11893 11894 LLVM_DEBUG({ 11895 dbgs() << "Case clusters: "; 11896 for (const CaseCluster &C : Clusters) { 11897 if (C.Kind == CC_JumpTable) 11898 dbgs() << "JT:"; 11899 if (C.Kind == CC_BitTests) 11900 dbgs() << "BT:"; 11901 11902 C.Low->getValue().print(dbgs(), true); 11903 if (C.Low != C.High) { 11904 dbgs() << '-'; 11905 C.High->getValue().print(dbgs(), true); 11906 } 11907 dbgs() << ' '; 11908 } 11909 dbgs() << '\n'; 11910 }); 11911 11912 assert(!Clusters.empty()); 11913 SwitchWorkList WorkList; 11914 CaseClusterIt First = Clusters.begin(); 11915 CaseClusterIt Last = Clusters.end() - 1; 11916 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11917 // Scale the branchprobability for DefaultMBB if the peel occurs and 11918 // DefaultMBB is not replaced. 11919 if (PeeledCaseProb != BranchProbability::getZero() && 11920 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11921 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11922 WorkList.push_back( 11923 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11924 11925 while (!WorkList.empty()) { 11926 SwitchWorkListItem W = WorkList.pop_back_val(); 11927 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11928 11929 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None && 11930 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11931 // For optimized builds, lower large range as a balanced binary tree. 11932 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11933 continue; 11934 } 11935 11936 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11937 } 11938 } 11939 11940 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11941 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11942 auto DL = getCurSDLoc(); 11943 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11944 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11945 } 11946 11947 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11948 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11949 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11950 11951 SDLoc DL = getCurSDLoc(); 11952 SDValue V = getValue(I.getOperand(0)); 11953 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11954 11955 if (VT.isScalableVector()) { 11956 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11957 return; 11958 } 11959 11960 // Use VECTOR_SHUFFLE for the fixed-length vector 11961 // to maintain existing behavior. 11962 SmallVector<int, 8> Mask; 11963 unsigned NumElts = VT.getVectorMinNumElements(); 11964 for (unsigned i = 0; i != NumElts; ++i) 11965 Mask.push_back(NumElts - 1 - i); 11966 11967 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11968 } 11969 11970 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11971 auto DL = getCurSDLoc(); 11972 SDValue InVec = getValue(I.getOperand(0)); 11973 EVT OutVT = 11974 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11975 11976 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11977 11978 // ISD Node needs the input vectors split into two equal parts 11979 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11980 DAG.getVectorIdxConstant(0, DL)); 11981 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11982 DAG.getVectorIdxConstant(OutNumElts, DL)); 11983 11984 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11985 // legalisation and combines. 11986 if (OutVT.isFixedLengthVector()) { 11987 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11988 createStrideMask(0, 2, OutNumElts)); 11989 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11990 createStrideMask(1, 2, OutNumElts)); 11991 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11992 setValue(&I, Res); 11993 return; 11994 } 11995 11996 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11997 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11998 setValue(&I, Res); 11999 } 12000 12001 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 12002 auto DL = getCurSDLoc(); 12003 EVT InVT = getValue(I.getOperand(0)).getValueType(); 12004 SDValue InVec0 = getValue(I.getOperand(0)); 12005 SDValue InVec1 = getValue(I.getOperand(1)); 12006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12007 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12008 12009 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 12010 // legalisation and combines. 12011 if (OutVT.isFixedLengthVector()) { 12012 unsigned NumElts = InVT.getVectorMinNumElements(); 12013 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 12014 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 12015 createInterleaveMask(NumElts, 2))); 12016 return; 12017 } 12018 12019 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 12020 DAG.getVTList(InVT, InVT), InVec0, InVec1); 12021 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 12022 Res.getValue(1)); 12023 setValue(&I, Res); 12024 } 12025 12026 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 12027 SmallVector<EVT, 4> ValueVTs; 12028 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 12029 ValueVTs); 12030 unsigned NumValues = ValueVTs.size(); 12031 if (NumValues == 0) return; 12032 12033 SmallVector<SDValue, 4> Values(NumValues); 12034 SDValue Op = getValue(I.getOperand(0)); 12035 12036 for (unsigned i = 0; i != NumValues; ++i) 12037 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 12038 SDValue(Op.getNode(), Op.getResNo() + i)); 12039 12040 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12041 DAG.getVTList(ValueVTs), Values)); 12042 } 12043 12044 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 12045 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12046 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 12047 12048 SDLoc DL = getCurSDLoc(); 12049 SDValue V1 = getValue(I.getOperand(0)); 12050 SDValue V2 = getValue(I.getOperand(1)); 12051 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 12052 12053 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 12054 if (VT.isScalableVector()) { 12055 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 12056 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 12057 DAG.getConstant(Imm, DL, IdxVT))); 12058 return; 12059 } 12060 12061 unsigned NumElts = VT.getVectorNumElements(); 12062 12063 uint64_t Idx = (NumElts + Imm) % NumElts; 12064 12065 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 12066 SmallVector<int, 8> Mask; 12067 for (unsigned i = 0; i < NumElts; ++i) 12068 Mask.push_back(Idx + i); 12069 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 12070 } 12071 12072 // Consider the following MIR after SelectionDAG, which produces output in 12073 // phyregs in the first case or virtregs in the second case. 12074 // 12075 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 12076 // %5:gr32 = COPY $ebx 12077 // %6:gr32 = COPY $edx 12078 // %1:gr32 = COPY %6:gr32 12079 // %0:gr32 = COPY %5:gr32 12080 // 12081 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 12082 // %1:gr32 = COPY %6:gr32 12083 // %0:gr32 = COPY %5:gr32 12084 // 12085 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 12086 // Given %1, we'd like to return $edx in the first case and %6 in the second. 12087 // 12088 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 12089 // to a single virtreg (such as %0). The remaining outputs monotonically 12090 // increase in virtreg number from there. If a callbr has no outputs, then it 12091 // should not have a corresponding callbr landingpad; in fact, the callbr 12092 // landingpad would not even be able to refer to such a callbr. 12093 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 12094 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 12095 // There is definitely at least one copy. 12096 assert(MI->getOpcode() == TargetOpcode::COPY && 12097 "start of copy chain MUST be COPY"); 12098 Reg = MI->getOperand(1).getReg(); 12099 MI = MRI.def_begin(Reg)->getParent(); 12100 // There may be an optional second copy. 12101 if (MI->getOpcode() == TargetOpcode::COPY) { 12102 assert(Reg.isVirtual() && "expected COPY of virtual register"); 12103 Reg = MI->getOperand(1).getReg(); 12104 assert(Reg.isPhysical() && "expected COPY of physical register"); 12105 MI = MRI.def_begin(Reg)->getParent(); 12106 } 12107 // The start of the chain must be an INLINEASM_BR. 12108 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 12109 "end of copy chain MUST be INLINEASM_BR"); 12110 return Reg; 12111 } 12112 12113 // We must do this walk rather than the simpler 12114 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 12115 // otherwise we will end up with copies of virtregs only valid along direct 12116 // edges. 12117 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 12118 SmallVector<EVT, 8> ResultVTs; 12119 SmallVector<SDValue, 8> ResultValues; 12120 const auto *CBR = 12121 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 12122 12123 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12124 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 12125 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 12126 12127 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 12128 SDValue Chain = DAG.getRoot(); 12129 12130 // Re-parse the asm constraints string. 12131 TargetLowering::AsmOperandInfoVector TargetConstraints = 12132 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 12133 for (auto &T : TargetConstraints) { 12134 SDISelAsmOperandInfo OpInfo(T); 12135 if (OpInfo.Type != InlineAsm::isOutput) 12136 continue; 12137 12138 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 12139 // individual constraint. 12140 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 12141 12142 switch (OpInfo.ConstraintType) { 12143 case TargetLowering::C_Register: 12144 case TargetLowering::C_RegisterClass: { 12145 // Fill in OpInfo.AssignedRegs.Regs. 12146 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 12147 12148 // getRegistersForValue may produce 1 to many registers based on whether 12149 // the OpInfo.ConstraintVT is legal on the target or not. 12150 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 12151 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 12152 if (Register::isPhysicalRegister(OriginalDef)) 12153 FuncInfo.MBB->addLiveIn(OriginalDef); 12154 // Update the assigned registers to use the original defs. 12155 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 12156 } 12157 12158 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 12159 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 12160 ResultValues.push_back(V); 12161 ResultVTs.push_back(OpInfo.ConstraintVT); 12162 break; 12163 } 12164 case TargetLowering::C_Other: { 12165 SDValue Flag; 12166 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 12167 OpInfo, DAG); 12168 ++InitialDef; 12169 ResultValues.push_back(V); 12170 ResultVTs.push_back(OpInfo.ConstraintVT); 12171 break; 12172 } 12173 default: 12174 break; 12175 } 12176 } 12177 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 12178 DAG.getVTList(ResultVTs), ResultValues); 12179 setValue(&I, V); 12180 } 12181