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/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineOperand.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RuntimeLibcalls.h" 46 #include "llvm/CodeGen/SelectionDAG.h" 47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 48 #include "llvm/CodeGen/StackMaps.h" 49 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 50 #include "llvm/CodeGen/TargetFrameLowering.h" 51 #include "llvm/CodeGen/TargetInstrInfo.h" 52 #include "llvm/CodeGen/TargetOpcodes.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/CodeGen/WinEHFuncInfo.h" 56 #include "llvm/IR/Argument.h" 57 #include "llvm/IR/Attributes.h" 58 #include "llvm/IR/BasicBlock.h" 59 #include "llvm/IR/CFG.h" 60 #include "llvm/IR/CallingConv.h" 61 #include "llvm/IR/Constant.h" 62 #include "llvm/IR/ConstantRange.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DataLayout.h" 65 #include "llvm/IR/DebugInfo.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/DiagnosticInfo.h" 69 #include "llvm/IR/EHPersonalities.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/TargetParser/Triple.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <iterator> 103 #include <limits> 104 #include <optional> 105 #include <tuple> 106 107 using namespace llvm; 108 using namespace PatternMatch; 109 using namespace SwitchCG; 110 111 #define DEBUG_TYPE "isel" 112 113 /// LimitFloatPrecision - Generate low-precision inline sequences for 114 /// some float libcalls (6, 8 or 12 bits). 115 static unsigned LimitFloatPrecision; 116 117 static cl::opt<bool> 118 InsertAssertAlign("insert-assert-align", cl::init(true), 119 cl::desc("Insert the experimental `assertalign` node."), 120 cl::ReallyHidden); 121 122 static cl::opt<unsigned, true> 123 LimitFPPrecision("limit-float-precision", 124 cl::desc("Generate low-precision inline sequences " 125 "for some float libcalls"), 126 cl::location(LimitFloatPrecision), cl::Hidden, 127 cl::init(0)); 128 129 static cl::opt<unsigned> SwitchPeelThreshold( 130 "switch-peel-threshold", cl::Hidden, cl::init(66), 131 cl::desc("Set the case probability threshold for peeling the case from a " 132 "switch statement. A value greater than 100 will void this " 133 "optimization")); 134 135 // Limit the width of DAG chains. This is important in general to prevent 136 // DAG-based analysis from blowing up. For example, alias analysis and 137 // load clustering may not complete in reasonable time. It is difficult to 138 // recognize and avoid this situation within each individual analysis, and 139 // future analyses are likely to have the same behavior. Limiting DAG width is 140 // the safe approach and will be especially important with global DAGs. 141 // 142 // MaxParallelChains default is arbitrarily high to avoid affecting 143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 144 // sequence over this should have been converted to llvm.memcpy by the 145 // frontend. It is easy to induce this behavior with .ll code such as: 146 // %buffer = alloca [4096 x i8] 147 // %data = load [4096 x i8]* %argPtr 148 // store [4096 x i8] %data, [4096 x i8]* %buffer 149 static const unsigned MaxParallelChains = 64; 150 151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 152 const SDValue *Parts, unsigned NumParts, 153 MVT PartVT, EVT ValueVT, const Value *V, 154 std::optional<CallingConv::ID> CC); 155 156 /// getCopyFromParts - Create a value that contains the specified legal parts 157 /// combined into the value they represent. If the parts combine to a type 158 /// larger than ValueVT then AssertOp can be used to specify whether the extra 159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 160 /// (ISD::AssertSext). 161 static SDValue 162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 164 std::optional<CallingConv::ID> CC = std::nullopt, 165 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 166 // Let the target assemble the parts if it wants to 167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 169 PartVT, ValueVT, CC)) 170 return Val; 171 172 if (ValueVT.isVector()) 173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 174 CC); 175 176 assert(NumParts > 0 && "No parts to assemble!"); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = llvm::bit_floor(NumParts); 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 std::optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void 483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 484 unsigned NumParts, MVT PartVT, const Value *V, 485 std::optional<CallingConv::ID> CallConv = std::nullopt, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned OrigNumParts = NumParts; 500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 501 "Copying to an illegal type!"); 502 503 if (NumParts == 0) 504 return; 505 506 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 507 EVT PartEVT = PartVT; 508 if (PartEVT == ValueVT) { 509 assert(NumParts == 1 && "No-op copy with multiple parts!"); 510 Parts[0] = Val; 511 return; 512 } 513 514 unsigned PartBits = PartVT.getSizeInBits(); 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = llvm::bit_floor(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 std::optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 724 RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 std::optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, std::optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 std::optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Glue, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = isABIMangled() 852 ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), *CallConv, RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Glue) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 863 *Glue = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = isABIMangled() 935 ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), *CallConv, RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Glue) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 955 *Glue = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Glue) 962 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1055 *DAG.getMachineFunction().getFunction().getParent()); 1056 } 1057 1058 void SelectionDAGBuilder::clear() { 1059 NodeMap.clear(); 1060 UnusedArgNodeMap.clear(); 1061 PendingLoads.clear(); 1062 PendingExports.clear(); 1063 PendingConstrainedFP.clear(); 1064 PendingConstrainedFPStrict.clear(); 1065 CurInst = nullptr; 1066 HasTailCall = false; 1067 SDNodeOrder = LowestSDNodeOrder; 1068 StatepointLowering.clear(); 1069 } 1070 1071 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1072 DanglingDebugInfoMap.clear(); 1073 } 1074 1075 // Update DAG root to include dependencies on Pending chains. 1076 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1077 SDValue Root = DAG.getRoot(); 1078 1079 if (Pending.empty()) 1080 return Root; 1081 1082 // Add current root to PendingChains, unless we already indirectly 1083 // depend on it. 1084 if (Root.getOpcode() != ISD::EntryToken) { 1085 unsigned i = 0, e = Pending.size(); 1086 for (; i != e; ++i) { 1087 assert(Pending[i].getNode()->getNumOperands() > 1); 1088 if (Pending[i].getNode()->getOperand(0) == Root) 1089 break; // Don't add the root if we already indirectly depend on it. 1090 } 1091 1092 if (i == e) 1093 Pending.push_back(Root); 1094 } 1095 1096 if (Pending.size() == 1) 1097 Root = Pending[0]; 1098 else 1099 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1100 1101 DAG.setRoot(Root); 1102 Pending.clear(); 1103 return Root; 1104 } 1105 1106 SDValue SelectionDAGBuilder::getMemoryRoot() { 1107 return updateRoot(PendingLoads); 1108 } 1109 1110 SDValue SelectionDAGBuilder::getRoot() { 1111 // Chain up all pending constrained intrinsics together with all 1112 // pending loads, by simply appending them to PendingLoads and 1113 // then calling getMemoryRoot(). 1114 PendingLoads.reserve(PendingLoads.size() + 1115 PendingConstrainedFP.size() + 1116 PendingConstrainedFPStrict.size()); 1117 PendingLoads.append(PendingConstrainedFP.begin(), 1118 PendingConstrainedFP.end()); 1119 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1120 PendingConstrainedFPStrict.end()); 1121 PendingConstrainedFP.clear(); 1122 PendingConstrainedFPStrict.clear(); 1123 return getMemoryRoot(); 1124 } 1125 1126 SDValue SelectionDAGBuilder::getControlRoot() { 1127 // We need to emit pending fpexcept.strict constrained intrinsics, 1128 // so append them to the PendingExports list. 1129 PendingExports.append(PendingConstrainedFPStrict.begin(), 1130 PendingConstrainedFPStrict.end()); 1131 PendingConstrainedFPStrict.clear(); 1132 return updateRoot(PendingExports); 1133 } 1134 1135 void SelectionDAGBuilder::visit(const Instruction &I) { 1136 // Set up outgoing PHI node register values before emitting the terminator. 1137 if (I.isTerminator()) { 1138 HandlePHINodesInSuccessorBlocks(I.getParent()); 1139 } 1140 1141 // Add SDDbgValue nodes for any var locs here. Do so before updating 1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1143 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1144 // Add SDDbgValue nodes for any var locs here. Do so before updating 1145 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1146 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1147 It != End; ++It) { 1148 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1149 dropDanglingDebugInfo(Var, It->Expr); 1150 if (It->Values.isKillLocation(It->Expr)) { 1151 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1152 continue; 1153 } 1154 SmallVector<Value *> Values(It->Values.location_ops()); 1155 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1156 It->Values.hasArgList())) 1157 addDanglingDebugInfo(It, SDNodeOrder); 1158 } 1159 } 1160 1161 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1162 if (!isa<DbgInfoIntrinsic>(I)) 1163 ++SDNodeOrder; 1164 1165 CurInst = &I; 1166 1167 // Set inserted listener only if required. 1168 bool NodeInserted = false; 1169 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1170 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1171 if (PCSectionsMD) { 1172 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1173 DAG, [&](SDNode *) { NodeInserted = true; }); 1174 } 1175 1176 visit(I.getOpcode(), I); 1177 1178 if (!I.isTerminator() && !HasTailCall && 1179 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1180 CopyToExportRegsIfNeeded(&I); 1181 1182 // Handle metadata. 1183 if (PCSectionsMD) { 1184 auto It = NodeMap.find(&I); 1185 if (It != NodeMap.end()) { 1186 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1187 } else if (NodeInserted) { 1188 // This should not happen; if it does, don't let it go unnoticed so we can 1189 // fix it. Relevant visit*() function is probably missing a setValue(). 1190 errs() << "warning: loosing !pcsections metadata [" 1191 << I.getModule()->getName() << "]\n"; 1192 LLVM_DEBUG(I.dump()); 1193 assert(false); 1194 } 1195 } 1196 1197 CurInst = nullptr; 1198 } 1199 1200 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1201 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1202 } 1203 1204 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1205 // Note: this doesn't use InstVisitor, because it has to work with 1206 // ConstantExpr's in addition to instructions. 1207 switch (Opcode) { 1208 default: llvm_unreachable("Unknown instruction type encountered!"); 1209 // Build the switch statement using the Instruction.def file. 1210 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1211 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1212 #include "llvm/IR/Instruction.def" 1213 } 1214 } 1215 1216 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1217 DILocalVariable *Variable, 1218 DebugLoc DL, unsigned Order, 1219 RawLocationWrapper Values, 1220 DIExpression *Expression) { 1221 if (!Values.hasArgList()) 1222 return false; 1223 // For variadic dbg_values we will now insert an undef. 1224 // FIXME: We can potentially recover these! 1225 SmallVector<SDDbgOperand, 2> Locs; 1226 for (const Value *V : Values.location_ops()) { 1227 auto *Undef = UndefValue::get(V->getType()); 1228 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1229 } 1230 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1231 /*IsIndirect=*/false, DL, Order, 1232 /*IsVariadic=*/true); 1233 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1234 return true; 1235 } 1236 1237 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1238 unsigned Order) { 1239 if (!handleDanglingVariadicDebugInfo( 1240 DAG, 1241 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1242 ->getVariable(VarLoc->VariableID) 1243 .getVariable()), 1244 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1245 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1246 VarLoc, Order); 1247 } 1248 } 1249 1250 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1251 unsigned Order) { 1252 // We treat variadic dbg_values differently at this stage. 1253 if (!handleDanglingVariadicDebugInfo( 1254 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1255 DI->getWrappedLocation(), DI->getExpression())) { 1256 // TODO: Dangling debug info will eventually either be resolved or produce 1257 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1258 // between the original dbg.value location and its resolved DBG_VALUE, 1259 // which we should ideally fill with an extra Undef DBG_VALUE. 1260 assert(DI->getNumVariableLocationOps() == 1 && 1261 "DbgValueInst without an ArgList should have a single location " 1262 "operand."); 1263 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1264 } 1265 } 1266 1267 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1268 const DIExpression *Expr) { 1269 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1270 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1271 DIExpression *DanglingExpr = DDI.getExpression(); 1272 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1273 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1274 << "\n"); 1275 return true; 1276 } 1277 return false; 1278 }; 1279 1280 for (auto &DDIMI : DanglingDebugInfoMap) { 1281 DanglingDebugInfoVector &DDIV = DDIMI.second; 1282 1283 // If debug info is to be dropped, run it through final checks to see 1284 // whether it can be salvaged. 1285 for (auto &DDI : DDIV) 1286 if (isMatchingDbgValue(DDI)) 1287 salvageUnresolvedDbgValue(DDI); 1288 1289 erase_if(DDIV, isMatchingDbgValue); 1290 } 1291 } 1292 1293 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1294 // generate the debug data structures now that we've seen its definition. 1295 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1296 SDValue Val) { 1297 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1298 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1299 return; 1300 1301 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1302 for (auto &DDI : DDIV) { 1303 DebugLoc DL = DDI.getDebugLoc(); 1304 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1305 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1306 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1307 DIExpression *Expr = DDI.getExpression(); 1308 assert(Variable->isValidLocationForIntrinsic(DL) && 1309 "Expected inlined-at fields to agree"); 1310 SDDbgValue *SDV; 1311 if (Val.getNode()) { 1312 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1313 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1314 // we couldn't resolve it directly when examining the DbgValue intrinsic 1315 // in the first place we should not be more successful here). Unless we 1316 // have some test case that prove this to be correct we should avoid 1317 // calling EmitFuncArgumentDbgValue here. 1318 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1319 FuncArgumentDbgValueKind::Value, Val)) { 1320 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1321 << "\n"); 1322 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1323 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1324 // inserted after the definition of Val when emitting the instructions 1325 // after ISel. An alternative could be to teach 1326 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1327 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1328 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1329 << ValSDNodeOrder << "\n"); 1330 SDV = getDbgValue(Val, Variable, Expr, DL, 1331 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1332 DAG.AddDbgValue(SDV, false); 1333 } else 1334 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1335 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1336 } else { 1337 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1338 auto Undef = UndefValue::get(V->getType()); 1339 auto SDV = 1340 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1341 DAG.AddDbgValue(SDV, false); 1342 } 1343 } 1344 DDIV.clear(); 1345 } 1346 1347 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1348 // TODO: For the variadic implementation, instead of only checking the fail 1349 // state of `handleDebugValue`, we need know specifically which values were 1350 // invalid, so that we attempt to salvage only those values when processing 1351 // a DIArgList. 1352 Value *V = DDI.getVariableLocationOp(0); 1353 Value *OrigV = V; 1354 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1355 DIExpression *Expr = DDI.getExpression(); 1356 DebugLoc DL = DDI.getDebugLoc(); 1357 unsigned SDOrder = DDI.getSDNodeOrder(); 1358 1359 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1360 // that DW_OP_stack_value is desired. 1361 bool StackValue = true; 1362 1363 // Can this Value can be encoded without any further work? 1364 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1365 return; 1366 1367 // Attempt to salvage back through as many instructions as possible. Bail if 1368 // a non-instruction is seen, such as a constant expression or global 1369 // variable. FIXME: Further work could recover those too. 1370 while (isa<Instruction>(V)) { 1371 Instruction &VAsInst = *cast<Instruction>(V); 1372 // Temporary "0", awaiting real implementation. 1373 SmallVector<uint64_t, 16> Ops; 1374 SmallVector<Value *, 4> AdditionalValues; 1375 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1376 AdditionalValues); 1377 // If we cannot salvage any further, and haven't yet found a suitable debug 1378 // expression, bail out. 1379 if (!V) 1380 break; 1381 1382 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1383 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1384 // here for variadic dbg_values, remove that condition. 1385 if (!AdditionalValues.empty()) 1386 break; 1387 1388 // New value and expr now represent this debuginfo. 1389 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1390 1391 // Some kind of simplification occurred: check whether the operand of the 1392 // salvaged debug expression can be encoded in this DAG. 1393 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1394 LLVM_DEBUG( 1395 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1396 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1397 return; 1398 } 1399 } 1400 1401 // This was the final opportunity to salvage this debug information, and it 1402 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1403 // any earlier variable location. 1404 assert(OrigV && "V shouldn't be null"); 1405 auto *Undef = UndefValue::get(OrigV->getType()); 1406 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1407 DAG.AddDbgValue(SDV, false); 1408 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1409 << "\n"); 1410 } 1411 1412 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1413 DIExpression *Expr, 1414 DebugLoc DbgLoc, 1415 unsigned Order) { 1416 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1417 DIExpression *NewExpr = 1418 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1419 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1420 /*IsVariadic*/ false); 1421 } 1422 1423 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1424 DILocalVariable *Var, 1425 DIExpression *Expr, DebugLoc DbgLoc, 1426 unsigned Order, bool IsVariadic) { 1427 if (Values.empty()) 1428 return true; 1429 SmallVector<SDDbgOperand> LocationOps; 1430 SmallVector<SDNode *> Dependencies; 1431 for (const Value *V : Values) { 1432 // Constant value. 1433 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1434 isa<ConstantPointerNull>(V)) { 1435 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1436 continue; 1437 } 1438 1439 // Look through IntToPtr constants. 1440 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1441 if (CE->getOpcode() == Instruction::IntToPtr) { 1442 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1443 continue; 1444 } 1445 1446 // If the Value is a frame index, we can create a FrameIndex debug value 1447 // without relying on the DAG at all. 1448 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1449 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1450 if (SI != FuncInfo.StaticAllocaMap.end()) { 1451 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1452 continue; 1453 } 1454 } 1455 1456 // Do not use getValue() in here; we don't want to generate code at 1457 // this point if it hasn't been done yet. 1458 SDValue N = NodeMap[V]; 1459 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1460 N = UnusedArgNodeMap[V]; 1461 if (N.getNode()) { 1462 // Only emit func arg dbg value for non-variadic dbg.values for now. 1463 if (!IsVariadic && 1464 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1465 FuncArgumentDbgValueKind::Value, N)) 1466 return true; 1467 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1468 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1469 // describe stack slot locations. 1470 // 1471 // Consider "int x = 0; int *px = &x;". There are two kinds of 1472 // interesting debug values here after optimization: 1473 // 1474 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1475 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1476 // 1477 // Both describe the direct values of their associated variables. 1478 Dependencies.push_back(N.getNode()); 1479 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1480 continue; 1481 } 1482 LocationOps.emplace_back( 1483 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1484 continue; 1485 } 1486 1487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1488 // Special rules apply for the first dbg.values of parameter variables in a 1489 // function. Identify them by the fact they reference Argument Values, that 1490 // they're parameters, and they are parameters of the current function. We 1491 // need to let them dangle until they get an SDNode. 1492 bool IsParamOfFunc = 1493 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1494 if (IsParamOfFunc) 1495 return false; 1496 1497 // The value is not used in this block yet (or it would have an SDNode). 1498 // We still want the value to appear for the user if possible -- if it has 1499 // an associated VReg, we can refer to that instead. 1500 auto VMI = FuncInfo.ValueMap.find(V); 1501 if (VMI != FuncInfo.ValueMap.end()) { 1502 unsigned Reg = VMI->second; 1503 // If this is a PHI node, it may be split up into several MI PHI nodes 1504 // (in FunctionLoweringInfo::set). 1505 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1506 V->getType(), std::nullopt); 1507 if (RFV.occupiesMultipleRegs()) { 1508 // FIXME: We could potentially support variadic dbg_values here. 1509 if (IsVariadic) 1510 return false; 1511 unsigned Offset = 0; 1512 unsigned BitsToDescribe = 0; 1513 if (auto VarSize = Var->getSizeInBits()) 1514 BitsToDescribe = *VarSize; 1515 if (auto Fragment = Expr->getFragmentInfo()) 1516 BitsToDescribe = Fragment->SizeInBits; 1517 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1518 // Bail out if all bits are described already. 1519 if (Offset >= BitsToDescribe) 1520 break; 1521 // TODO: handle scalable vectors. 1522 unsigned RegisterSize = RegAndSize.second; 1523 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1524 ? BitsToDescribe - Offset 1525 : RegisterSize; 1526 auto FragmentExpr = DIExpression::createFragmentExpression( 1527 Expr, Offset, FragmentSize); 1528 if (!FragmentExpr) 1529 continue; 1530 SDDbgValue *SDV = DAG.getVRegDbgValue( 1531 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1532 DAG.AddDbgValue(SDV, false); 1533 Offset += RegisterSize; 1534 } 1535 return true; 1536 } 1537 // We can use simple vreg locations for variadic dbg_values as well. 1538 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1539 continue; 1540 } 1541 // We failed to create a SDDbgOperand for V. 1542 return false; 1543 } 1544 1545 // We have created a SDDbgOperand for each Value in Values. 1546 // Should use Order instead of SDNodeOrder? 1547 assert(!LocationOps.empty()); 1548 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1549 /*IsIndirect=*/false, DbgLoc, 1550 SDNodeOrder, IsVariadic); 1551 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1552 return true; 1553 } 1554 1555 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1556 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1557 for (auto &Pair : DanglingDebugInfoMap) 1558 for (auto &DDI : Pair.second) 1559 salvageUnresolvedDbgValue(DDI); 1560 clearDanglingDebugInfo(); 1561 } 1562 1563 /// getCopyFromRegs - If there was virtual register allocated for the value V 1564 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1565 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1566 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1567 SDValue Result; 1568 1569 if (It != FuncInfo.ValueMap.end()) { 1570 Register InReg = It->second; 1571 1572 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1573 DAG.getDataLayout(), InReg, Ty, 1574 std::nullopt); // This is not an ABI copy. 1575 SDValue Chain = DAG.getEntryNode(); 1576 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1577 V); 1578 resolveDanglingDebugInfo(V, Result); 1579 } 1580 1581 return Result; 1582 } 1583 1584 /// getValue - Return an SDValue for the given Value. 1585 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1586 // If we already have an SDValue for this value, use it. It's important 1587 // to do this first, so that we don't create a CopyFromReg if we already 1588 // have a regular SDValue. 1589 SDValue &N = NodeMap[V]; 1590 if (N.getNode()) return N; 1591 1592 // If there's a virtual register allocated and initialized for this 1593 // value, use it. 1594 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1595 return copyFromReg; 1596 1597 // Otherwise create a new SDValue and remember it. 1598 SDValue Val = getValueImpl(V); 1599 NodeMap[V] = Val; 1600 resolveDanglingDebugInfo(V, Val); 1601 return Val; 1602 } 1603 1604 /// getNonRegisterValue - Return an SDValue for the given Value, but 1605 /// don't look in FuncInfo.ValueMap for a virtual register. 1606 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1607 // If we already have an SDValue for this value, use it. 1608 SDValue &N = NodeMap[V]; 1609 if (N.getNode()) { 1610 if (isIntOrFPConstant(N)) { 1611 // Remove the debug location from the node as the node is about to be used 1612 // in a location which may differ from the original debug location. This 1613 // is relevant to Constant and ConstantFP nodes because they can appear 1614 // as constant expressions inside PHI nodes. 1615 N->setDebugLoc(DebugLoc()); 1616 } 1617 return N; 1618 } 1619 1620 // Otherwise create a new SDValue and remember it. 1621 SDValue Val = getValueImpl(V); 1622 NodeMap[V] = Val; 1623 resolveDanglingDebugInfo(V, Val); 1624 return Val; 1625 } 1626 1627 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1628 /// Create an SDValue for the given value. 1629 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1631 1632 if (const Constant *C = dyn_cast<Constant>(V)) { 1633 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1634 1635 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1636 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1637 1638 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1639 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1640 1641 if (isa<ConstantPointerNull>(C)) { 1642 unsigned AS = V->getType()->getPointerAddressSpace(); 1643 return DAG.getConstant(0, getCurSDLoc(), 1644 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1645 } 1646 1647 if (match(C, m_VScale())) 1648 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1649 1650 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1651 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1652 1653 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1654 return DAG.getUNDEF(VT); 1655 1656 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1657 visit(CE->getOpcode(), *CE); 1658 SDValue N1 = NodeMap[V]; 1659 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1660 return N1; 1661 } 1662 1663 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1664 SmallVector<SDValue, 4> Constants; 1665 for (const Use &U : C->operands()) { 1666 SDNode *Val = getValue(U).getNode(); 1667 // If the operand is an empty aggregate, there are no values. 1668 if (!Val) continue; 1669 // Add each leaf value from the operand to the Constants list 1670 // to form a flattened list of all the values. 1671 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1672 Constants.push_back(SDValue(Val, i)); 1673 } 1674 1675 return DAG.getMergeValues(Constants, getCurSDLoc()); 1676 } 1677 1678 if (const ConstantDataSequential *CDS = 1679 dyn_cast<ConstantDataSequential>(C)) { 1680 SmallVector<SDValue, 4> Ops; 1681 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1682 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1683 // Add each leaf value from the operand to the Constants list 1684 // to form a flattened list of all the values. 1685 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1686 Ops.push_back(SDValue(Val, i)); 1687 } 1688 1689 if (isa<ArrayType>(CDS->getType())) 1690 return DAG.getMergeValues(Ops, getCurSDLoc()); 1691 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1692 } 1693 1694 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1695 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1696 "Unknown struct or array constant!"); 1697 1698 SmallVector<EVT, 4> ValueVTs; 1699 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1700 unsigned NumElts = ValueVTs.size(); 1701 if (NumElts == 0) 1702 return SDValue(); // empty struct 1703 SmallVector<SDValue, 4> Constants(NumElts); 1704 for (unsigned i = 0; i != NumElts; ++i) { 1705 EVT EltVT = ValueVTs[i]; 1706 if (isa<UndefValue>(C)) 1707 Constants[i] = DAG.getUNDEF(EltVT); 1708 else if (EltVT.isFloatingPoint()) 1709 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1710 else 1711 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1712 } 1713 1714 return DAG.getMergeValues(Constants, getCurSDLoc()); 1715 } 1716 1717 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1718 return DAG.getBlockAddress(BA, VT); 1719 1720 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1721 return getValue(Equiv->getGlobalValue()); 1722 1723 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1724 return getValue(NC->getGlobalValue()); 1725 1726 VectorType *VecTy = cast<VectorType>(V->getType()); 1727 1728 // Now that we know the number and type of the elements, get that number of 1729 // elements into the Ops array based on what kind of constant it is. 1730 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1731 SmallVector<SDValue, 16> Ops; 1732 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1733 for (unsigned i = 0; i != NumElements; ++i) 1734 Ops.push_back(getValue(CV->getOperand(i))); 1735 1736 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1737 } 1738 1739 if (isa<ConstantAggregateZero>(C)) { 1740 EVT EltVT = 1741 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1742 1743 SDValue Op; 1744 if (EltVT.isFloatingPoint()) 1745 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1746 else 1747 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1748 1749 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1750 } 1751 1752 llvm_unreachable("Unknown vector constant"); 1753 } 1754 1755 // If this is a static alloca, generate it as the frameindex instead of 1756 // computation. 1757 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1758 DenseMap<const AllocaInst*, int>::iterator SI = 1759 FuncInfo.StaticAllocaMap.find(AI); 1760 if (SI != FuncInfo.StaticAllocaMap.end()) 1761 return DAG.getFrameIndex( 1762 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1763 } 1764 1765 // If this is an instruction which fast-isel has deferred, select it now. 1766 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1767 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1768 1769 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1770 Inst->getType(), std::nullopt); 1771 SDValue Chain = DAG.getEntryNode(); 1772 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1773 } 1774 1775 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1776 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1777 1778 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1779 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1780 1781 llvm_unreachable("Can't get register for value!"); 1782 } 1783 1784 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1785 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1786 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1787 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1788 bool IsSEH = isAsynchronousEHPersonality(Pers); 1789 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1790 if (!IsSEH) 1791 CatchPadMBB->setIsEHScopeEntry(); 1792 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1793 if (IsMSVCCXX || IsCoreCLR) 1794 CatchPadMBB->setIsEHFuncletEntry(); 1795 } 1796 1797 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1798 // Update machine-CFG edge. 1799 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1800 FuncInfo.MBB->addSuccessor(TargetMBB); 1801 TargetMBB->setIsEHCatchretTarget(true); 1802 DAG.getMachineFunction().setHasEHCatchret(true); 1803 1804 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1805 bool IsSEH = isAsynchronousEHPersonality(Pers); 1806 if (IsSEH) { 1807 // If this is not a fall-through branch or optimizations are switched off, 1808 // emit the branch. 1809 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1810 TM.getOptLevel() == CodeGenOpt::None) 1811 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1812 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1813 return; 1814 } 1815 1816 // Figure out the funclet membership for the catchret's successor. 1817 // This will be used by the FuncletLayout pass to determine how to order the 1818 // BB's. 1819 // A 'catchret' returns to the outer scope's color. 1820 Value *ParentPad = I.getCatchSwitchParentPad(); 1821 const BasicBlock *SuccessorColor; 1822 if (isa<ConstantTokenNone>(ParentPad)) 1823 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1824 else 1825 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1826 assert(SuccessorColor && "No parent funclet for catchret!"); 1827 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1828 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1829 1830 // Create the terminator node. 1831 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1832 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1833 DAG.getBasicBlock(SuccessorColorMBB)); 1834 DAG.setRoot(Ret); 1835 } 1836 1837 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1838 // Don't emit any special code for the cleanuppad instruction. It just marks 1839 // the start of an EH scope/funclet. 1840 FuncInfo.MBB->setIsEHScopeEntry(); 1841 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1842 if (Pers != EHPersonality::Wasm_CXX) { 1843 FuncInfo.MBB->setIsEHFuncletEntry(); 1844 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1845 } 1846 } 1847 1848 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1849 // not match, it is OK to add only the first unwind destination catchpad to the 1850 // successors, because there will be at least one invoke instruction within the 1851 // catch scope that points to the next unwind destination, if one exists, so 1852 // CFGSort cannot mess up with BB sorting order. 1853 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1854 // call within them, and catchpads only consisting of 'catch (...)' have a 1855 // '__cxa_end_catch' call within them, both of which generate invokes in case 1856 // the next unwind destination exists, i.e., the next unwind destination is not 1857 // the caller.) 1858 // 1859 // Having at most one EH pad successor is also simpler and helps later 1860 // transformations. 1861 // 1862 // For example, 1863 // current: 1864 // invoke void @foo to ... unwind label %catch.dispatch 1865 // catch.dispatch: 1866 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1867 // catch.start: 1868 // ... 1869 // ... in this BB or some other child BB dominated by this BB there will be an 1870 // invoke that points to 'next' BB as an unwind destination 1871 // 1872 // next: ; We don't need to add this to 'current' BB's successor 1873 // ... 1874 static void findWasmUnwindDestinations( 1875 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1876 BranchProbability Prob, 1877 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1878 &UnwindDests) { 1879 while (EHPadBB) { 1880 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1881 if (isa<CleanupPadInst>(Pad)) { 1882 // Stop on cleanup pads. 1883 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1884 UnwindDests.back().first->setIsEHScopeEntry(); 1885 break; 1886 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1887 // Add the catchpad handlers to the possible destinations. We don't 1888 // continue to the unwind destination of the catchswitch for wasm. 1889 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1890 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1891 UnwindDests.back().first->setIsEHScopeEntry(); 1892 } 1893 break; 1894 } else { 1895 continue; 1896 } 1897 } 1898 } 1899 1900 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1901 /// many places it could ultimately go. In the IR, we have a single unwind 1902 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1903 /// This function skips over imaginary basic blocks that hold catchswitch 1904 /// instructions, and finds all the "real" machine 1905 /// basic block destinations. As those destinations may not be successors of 1906 /// EHPadBB, here we also calculate the edge probability to those destinations. 1907 /// The passed-in Prob is the edge probability to EHPadBB. 1908 static void findUnwindDestinations( 1909 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1910 BranchProbability Prob, 1911 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1912 &UnwindDests) { 1913 EHPersonality Personality = 1914 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1915 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1916 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1917 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1918 bool IsSEH = isAsynchronousEHPersonality(Personality); 1919 1920 if (IsWasmCXX) { 1921 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1922 assert(UnwindDests.size() <= 1 && 1923 "There should be at most one unwind destination for wasm"); 1924 return; 1925 } 1926 1927 while (EHPadBB) { 1928 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1929 BasicBlock *NewEHPadBB = nullptr; 1930 if (isa<LandingPadInst>(Pad)) { 1931 // Stop on landingpads. They are not funclets. 1932 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1933 break; 1934 } else if (isa<CleanupPadInst>(Pad)) { 1935 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1936 // personalities. 1937 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1938 UnwindDests.back().first->setIsEHScopeEntry(); 1939 UnwindDests.back().first->setIsEHFuncletEntry(); 1940 break; 1941 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1942 // Add the catchpad handlers to the possible destinations. 1943 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1944 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1945 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1946 if (IsMSVCCXX || IsCoreCLR) 1947 UnwindDests.back().first->setIsEHFuncletEntry(); 1948 if (!IsSEH) 1949 UnwindDests.back().first->setIsEHScopeEntry(); 1950 } 1951 NewEHPadBB = CatchSwitch->getUnwindDest(); 1952 } else { 1953 continue; 1954 } 1955 1956 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1957 if (BPI && NewEHPadBB) 1958 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1959 EHPadBB = NewEHPadBB; 1960 } 1961 } 1962 1963 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1964 // Update successor info. 1965 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1966 auto UnwindDest = I.getUnwindDest(); 1967 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1968 BranchProbability UnwindDestProb = 1969 (BPI && UnwindDest) 1970 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1971 : BranchProbability::getZero(); 1972 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1973 for (auto &UnwindDest : UnwindDests) { 1974 UnwindDest.first->setIsEHPad(); 1975 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1976 } 1977 FuncInfo.MBB->normalizeSuccProbs(); 1978 1979 // Create the terminator node. 1980 SDValue Ret = 1981 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1982 DAG.setRoot(Ret); 1983 } 1984 1985 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1986 report_fatal_error("visitCatchSwitch not yet implemented!"); 1987 } 1988 1989 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1991 auto &DL = DAG.getDataLayout(); 1992 SDValue Chain = getControlRoot(); 1993 SmallVector<ISD::OutputArg, 8> Outs; 1994 SmallVector<SDValue, 8> OutVals; 1995 1996 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1997 // lower 1998 // 1999 // %val = call <ty> @llvm.experimental.deoptimize() 2000 // ret <ty> %val 2001 // 2002 // differently. 2003 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2004 LowerDeoptimizingReturn(); 2005 return; 2006 } 2007 2008 if (!FuncInfo.CanLowerReturn) { 2009 unsigned DemoteReg = FuncInfo.DemoteRegister; 2010 const Function *F = I.getParent()->getParent(); 2011 2012 // Emit a store of the return value through the virtual register. 2013 // Leave Outs empty so that LowerReturn won't try to load return 2014 // registers the usual way. 2015 SmallVector<EVT, 1> PtrValueVTs; 2016 ComputeValueVTs(TLI, DL, 2017 F->getReturnType()->getPointerTo( 2018 DAG.getDataLayout().getAllocaAddrSpace()), 2019 PtrValueVTs); 2020 2021 SDValue RetPtr = 2022 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2023 SDValue RetOp = getValue(I.getOperand(0)); 2024 2025 SmallVector<EVT, 4> ValueVTs, MemVTs; 2026 SmallVector<uint64_t, 4> Offsets; 2027 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2028 &Offsets, 0); 2029 unsigned NumValues = ValueVTs.size(); 2030 2031 SmallVector<SDValue, 4> Chains(NumValues); 2032 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2033 for (unsigned i = 0; i != NumValues; ++i) { 2034 // An aggregate return value cannot wrap around the address space, so 2035 // offsets to its parts don't wrap either. 2036 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2037 TypeSize::Fixed(Offsets[i])); 2038 2039 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2040 if (MemVTs[i] != ValueVTs[i]) 2041 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2042 Chains[i] = DAG.getStore( 2043 Chain, getCurSDLoc(), Val, 2044 // FIXME: better loc info would be nice. 2045 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2046 commonAlignment(BaseAlign, Offsets[i])); 2047 } 2048 2049 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2050 MVT::Other, Chains); 2051 } else if (I.getNumOperands() != 0) { 2052 SmallVector<EVT, 4> ValueVTs; 2053 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2054 unsigned NumValues = ValueVTs.size(); 2055 if (NumValues) { 2056 SDValue RetOp = getValue(I.getOperand(0)); 2057 2058 const Function *F = I.getParent()->getParent(); 2059 2060 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2061 I.getOperand(0)->getType(), F->getCallingConv(), 2062 /*IsVarArg*/ false, DL); 2063 2064 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2065 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2066 ExtendKind = ISD::SIGN_EXTEND; 2067 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2068 ExtendKind = ISD::ZERO_EXTEND; 2069 2070 LLVMContext &Context = F->getContext(); 2071 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2072 2073 for (unsigned j = 0; j != NumValues; ++j) { 2074 EVT VT = ValueVTs[j]; 2075 2076 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2077 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2078 2079 CallingConv::ID CC = F->getCallingConv(); 2080 2081 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2082 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2083 SmallVector<SDValue, 4> Parts(NumParts); 2084 getCopyToParts(DAG, getCurSDLoc(), 2085 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2086 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2087 2088 // 'inreg' on function refers to return value 2089 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2090 if (RetInReg) 2091 Flags.setInReg(); 2092 2093 if (I.getOperand(0)->getType()->isPointerTy()) { 2094 Flags.setPointer(); 2095 Flags.setPointerAddrSpace( 2096 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2097 } 2098 2099 if (NeedsRegBlock) { 2100 Flags.setInConsecutiveRegs(); 2101 if (j == NumValues - 1) 2102 Flags.setInConsecutiveRegsLast(); 2103 } 2104 2105 // Propagate extension type if any 2106 if (ExtendKind == ISD::SIGN_EXTEND) 2107 Flags.setSExt(); 2108 else if (ExtendKind == ISD::ZERO_EXTEND) 2109 Flags.setZExt(); 2110 2111 for (unsigned i = 0; i < NumParts; ++i) { 2112 Outs.push_back(ISD::OutputArg(Flags, 2113 Parts[i].getValueType().getSimpleVT(), 2114 VT, /*isfixed=*/true, 0, 0)); 2115 OutVals.push_back(Parts[i]); 2116 } 2117 } 2118 } 2119 } 2120 2121 // Push in swifterror virtual register as the last element of Outs. This makes 2122 // sure swifterror virtual register will be returned in the swifterror 2123 // physical register. 2124 const Function *F = I.getParent()->getParent(); 2125 if (TLI.supportSwiftError() && 2126 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2127 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2128 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2129 Flags.setSwiftError(); 2130 Outs.push_back(ISD::OutputArg( 2131 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2132 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2133 // Create SDNode for the swifterror virtual register. 2134 OutVals.push_back( 2135 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2136 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2137 EVT(TLI.getPointerTy(DL)))); 2138 } 2139 2140 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2141 CallingConv::ID CallConv = 2142 DAG.getMachineFunction().getFunction().getCallingConv(); 2143 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2144 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2145 2146 // Verify that the target's LowerReturn behaved as expected. 2147 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2148 "LowerReturn didn't return a valid chain!"); 2149 2150 // Update the DAG with the new chain value resulting from return lowering. 2151 DAG.setRoot(Chain); 2152 } 2153 2154 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2155 /// created for it, emit nodes to copy the value into the virtual 2156 /// registers. 2157 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2158 // Skip empty types 2159 if (V->getType()->isEmptyTy()) 2160 return; 2161 2162 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2163 if (VMI != FuncInfo.ValueMap.end()) { 2164 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2165 "Unused value assigned virtual registers!"); 2166 CopyValueToVirtualRegister(V, VMI->second); 2167 } 2168 } 2169 2170 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2171 /// the current basic block, add it to ValueMap now so that we'll get a 2172 /// CopyTo/FromReg. 2173 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2174 // No need to export constants. 2175 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2176 2177 // Already exported? 2178 if (FuncInfo.isExportedInst(V)) return; 2179 2180 Register Reg = FuncInfo.InitializeRegForValue(V); 2181 CopyValueToVirtualRegister(V, Reg); 2182 } 2183 2184 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2185 const BasicBlock *FromBB) { 2186 // The operands of the setcc have to be in this block. We don't know 2187 // how to export them from some other block. 2188 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2189 // Can export from current BB. 2190 if (VI->getParent() == FromBB) 2191 return true; 2192 2193 // Is already exported, noop. 2194 return FuncInfo.isExportedInst(V); 2195 } 2196 2197 // If this is an argument, we can export it if the BB is the entry block or 2198 // if it is already exported. 2199 if (isa<Argument>(V)) { 2200 if (FromBB->isEntryBlock()) 2201 return true; 2202 2203 // Otherwise, can only export this if it is already exported. 2204 return FuncInfo.isExportedInst(V); 2205 } 2206 2207 // Otherwise, constants can always be exported. 2208 return true; 2209 } 2210 2211 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2212 BranchProbability 2213 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2214 const MachineBasicBlock *Dst) const { 2215 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2216 const BasicBlock *SrcBB = Src->getBasicBlock(); 2217 const BasicBlock *DstBB = Dst->getBasicBlock(); 2218 if (!BPI) { 2219 // If BPI is not available, set the default probability as 1 / N, where N is 2220 // the number of successors. 2221 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2222 return BranchProbability(1, SuccSize); 2223 } 2224 return BPI->getEdgeProbability(SrcBB, DstBB); 2225 } 2226 2227 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2228 MachineBasicBlock *Dst, 2229 BranchProbability Prob) { 2230 if (!FuncInfo.BPI) 2231 Src->addSuccessorWithoutProb(Dst); 2232 else { 2233 if (Prob.isUnknown()) 2234 Prob = getEdgeProbability(Src, Dst); 2235 Src->addSuccessor(Dst, Prob); 2236 } 2237 } 2238 2239 static bool InBlock(const Value *V, const BasicBlock *BB) { 2240 if (const Instruction *I = dyn_cast<Instruction>(V)) 2241 return I->getParent() == BB; 2242 return true; 2243 } 2244 2245 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2246 /// This function emits a branch and is used at the leaves of an OR or an 2247 /// AND operator tree. 2248 void 2249 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2250 MachineBasicBlock *TBB, 2251 MachineBasicBlock *FBB, 2252 MachineBasicBlock *CurBB, 2253 MachineBasicBlock *SwitchBB, 2254 BranchProbability TProb, 2255 BranchProbability FProb, 2256 bool InvertCond) { 2257 const BasicBlock *BB = CurBB->getBasicBlock(); 2258 2259 // If the leaf of the tree is a comparison, merge the condition into 2260 // the caseblock. 2261 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2262 // The operands of the cmp have to be in this block. We don't know 2263 // how to export them from some other block. If this is the first block 2264 // of the sequence, no exporting is needed. 2265 if (CurBB == SwitchBB || 2266 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2267 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2268 ISD::CondCode Condition; 2269 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2270 ICmpInst::Predicate Pred = 2271 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2272 Condition = getICmpCondCode(Pred); 2273 } else { 2274 const FCmpInst *FC = cast<FCmpInst>(Cond); 2275 FCmpInst::Predicate Pred = 2276 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2277 Condition = getFCmpCondCode(Pred); 2278 if (TM.Options.NoNaNsFPMath) 2279 Condition = getFCmpCodeWithoutNaN(Condition); 2280 } 2281 2282 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2283 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2284 SL->SwitchCases.push_back(CB); 2285 return; 2286 } 2287 } 2288 2289 // Create a CaseBlock record representing this branch. 2290 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2291 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2292 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2293 SL->SwitchCases.push_back(CB); 2294 } 2295 2296 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2297 MachineBasicBlock *TBB, 2298 MachineBasicBlock *FBB, 2299 MachineBasicBlock *CurBB, 2300 MachineBasicBlock *SwitchBB, 2301 Instruction::BinaryOps Opc, 2302 BranchProbability TProb, 2303 BranchProbability FProb, 2304 bool InvertCond) { 2305 // Skip over not part of the tree and remember to invert op and operands at 2306 // next level. 2307 Value *NotCond; 2308 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2309 InBlock(NotCond, CurBB->getBasicBlock())) { 2310 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2311 !InvertCond); 2312 return; 2313 } 2314 2315 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2316 const Value *BOpOp0, *BOpOp1; 2317 // Compute the effective opcode for Cond, taking into account whether it needs 2318 // to be inverted, e.g. 2319 // and (not (or A, B)), C 2320 // gets lowered as 2321 // and (and (not A, not B), C) 2322 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2323 if (BOp) { 2324 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2325 ? Instruction::And 2326 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2327 ? Instruction::Or 2328 : (Instruction::BinaryOps)0); 2329 if (InvertCond) { 2330 if (BOpc == Instruction::And) 2331 BOpc = Instruction::Or; 2332 else if (BOpc == Instruction::Or) 2333 BOpc = Instruction::And; 2334 } 2335 } 2336 2337 // If this node is not part of the or/and tree, emit it as a branch. 2338 // Note that all nodes in the tree should have same opcode. 2339 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2340 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2341 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2342 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2343 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2344 TProb, FProb, InvertCond); 2345 return; 2346 } 2347 2348 // Create TmpBB after CurBB. 2349 MachineFunction::iterator BBI(CurBB); 2350 MachineFunction &MF = DAG.getMachineFunction(); 2351 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2352 CurBB->getParent()->insert(++BBI, TmpBB); 2353 2354 if (Opc == Instruction::Or) { 2355 // Codegen X | Y as: 2356 // BB1: 2357 // jmp_if_X TBB 2358 // jmp TmpBB 2359 // TmpBB: 2360 // jmp_if_Y TBB 2361 // jmp FBB 2362 // 2363 2364 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2365 // The requirement is that 2366 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2367 // = TrueProb for original BB. 2368 // Assuming the original probabilities are A and B, one choice is to set 2369 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2370 // A/(1+B) and 2B/(1+B). This choice assumes that 2371 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2372 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2373 // TmpBB, but the math is more complicated. 2374 2375 auto NewTrueProb = TProb / 2; 2376 auto NewFalseProb = TProb / 2 + FProb; 2377 // Emit the LHS condition. 2378 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2379 NewFalseProb, InvertCond); 2380 2381 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2382 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2383 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2384 // Emit the RHS condition into TmpBB. 2385 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2386 Probs[1], InvertCond); 2387 } else { 2388 assert(Opc == Instruction::And && "Unknown merge op!"); 2389 // Codegen X & Y as: 2390 // BB1: 2391 // jmp_if_X TmpBB 2392 // jmp FBB 2393 // TmpBB: 2394 // jmp_if_Y TBB 2395 // jmp FBB 2396 // 2397 // This requires creation of TmpBB after CurBB. 2398 2399 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2400 // The requirement is that 2401 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2402 // = FalseProb for original BB. 2403 // Assuming the original probabilities are A and B, one choice is to set 2404 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2405 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2406 // TrueProb for BB1 * FalseProb for TmpBB. 2407 2408 auto NewTrueProb = TProb + FProb / 2; 2409 auto NewFalseProb = FProb / 2; 2410 // Emit the LHS condition. 2411 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2412 NewFalseProb, InvertCond); 2413 2414 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2415 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2416 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2417 // Emit the RHS condition into TmpBB. 2418 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2419 Probs[1], InvertCond); 2420 } 2421 } 2422 2423 /// If the set of cases should be emitted as a series of branches, return true. 2424 /// If we should emit this as a bunch of and/or'd together conditions, return 2425 /// false. 2426 bool 2427 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2428 if (Cases.size() != 2) return true; 2429 2430 // If this is two comparisons of the same values or'd or and'd together, they 2431 // will get folded into a single comparison, so don't emit two blocks. 2432 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2433 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2434 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2435 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2436 return false; 2437 } 2438 2439 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2440 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2441 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2442 Cases[0].CC == Cases[1].CC && 2443 isa<Constant>(Cases[0].CmpRHS) && 2444 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2445 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2446 return false; 2447 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2448 return false; 2449 } 2450 2451 return true; 2452 } 2453 2454 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2455 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2456 2457 // Update machine-CFG edges. 2458 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2459 2460 if (I.isUnconditional()) { 2461 // Update machine-CFG edges. 2462 BrMBB->addSuccessor(Succ0MBB); 2463 2464 // If this is not a fall-through branch or optimizations are switched off, 2465 // emit the branch. 2466 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2467 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2468 MVT::Other, getControlRoot(), 2469 DAG.getBasicBlock(Succ0MBB))); 2470 2471 return; 2472 } 2473 2474 // If this condition is one of the special cases we handle, do special stuff 2475 // now. 2476 const Value *CondVal = I.getCondition(); 2477 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2478 2479 // If this is a series of conditions that are or'd or and'd together, emit 2480 // this as a sequence of branches instead of setcc's with and/or operations. 2481 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2482 // unpredictable branches, and vector extracts because those jumps are likely 2483 // expensive for any target), this should improve performance. 2484 // For example, instead of something like: 2485 // cmp A, B 2486 // C = seteq 2487 // cmp D, E 2488 // F = setle 2489 // or C, F 2490 // jnz foo 2491 // Emit: 2492 // cmp A, B 2493 // je foo 2494 // cmp D, E 2495 // jle foo 2496 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2497 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2498 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2499 Value *Vec; 2500 const Value *BOp0, *BOp1; 2501 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2502 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2503 Opcode = Instruction::And; 2504 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2505 Opcode = Instruction::Or; 2506 2507 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2508 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2509 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2510 getEdgeProbability(BrMBB, Succ0MBB), 2511 getEdgeProbability(BrMBB, Succ1MBB), 2512 /*InvertCond=*/false); 2513 // If the compares in later blocks need to use values not currently 2514 // exported from this block, export them now. This block should always 2515 // be the first entry. 2516 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2517 2518 // Allow some cases to be rejected. 2519 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2520 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2521 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2522 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2523 } 2524 2525 // Emit the branch for this block. 2526 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2527 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2528 return; 2529 } 2530 2531 // Okay, we decided not to do this, remove any inserted MBB's and clear 2532 // SwitchCases. 2533 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2534 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2535 2536 SL->SwitchCases.clear(); 2537 } 2538 } 2539 2540 // Create a CaseBlock record representing this branch. 2541 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2542 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2543 2544 // Use visitSwitchCase to actually insert the fast branch sequence for this 2545 // cond branch. 2546 visitSwitchCase(CB, BrMBB); 2547 } 2548 2549 /// visitSwitchCase - Emits the necessary code to represent a single node in 2550 /// the binary search tree resulting from lowering a switch instruction. 2551 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2552 MachineBasicBlock *SwitchBB) { 2553 SDValue Cond; 2554 SDValue CondLHS = getValue(CB.CmpLHS); 2555 SDLoc dl = CB.DL; 2556 2557 if (CB.CC == ISD::SETTRUE) { 2558 // Branch or fall through to TrueBB. 2559 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2560 SwitchBB->normalizeSuccProbs(); 2561 if (CB.TrueBB != NextBlock(SwitchBB)) { 2562 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2563 DAG.getBasicBlock(CB.TrueBB))); 2564 } 2565 return; 2566 } 2567 2568 auto &TLI = DAG.getTargetLoweringInfo(); 2569 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2570 2571 // Build the setcc now. 2572 if (!CB.CmpMHS) { 2573 // Fold "(X == true)" to X and "(X == false)" to !X to 2574 // handle common cases produced by branch lowering. 2575 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2576 CB.CC == ISD::SETEQ) 2577 Cond = CondLHS; 2578 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2579 CB.CC == ISD::SETEQ) { 2580 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2581 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2582 } else { 2583 SDValue CondRHS = getValue(CB.CmpRHS); 2584 2585 // If a pointer's DAG type is larger than its memory type then the DAG 2586 // values are zero-extended. This breaks signed comparisons so truncate 2587 // back to the underlying type before doing the compare. 2588 if (CondLHS.getValueType() != MemVT) { 2589 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2590 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2591 } 2592 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2593 } 2594 } else { 2595 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2596 2597 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2598 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2599 2600 SDValue CmpOp = getValue(CB.CmpMHS); 2601 EVT VT = CmpOp.getValueType(); 2602 2603 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2604 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2605 ISD::SETLE); 2606 } else { 2607 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2608 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2609 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2610 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2611 } 2612 } 2613 2614 // Update successor info 2615 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2616 // TrueBB and FalseBB are always different unless the incoming IR is 2617 // degenerate. This only happens when running llc on weird IR. 2618 if (CB.TrueBB != CB.FalseBB) 2619 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2620 SwitchBB->normalizeSuccProbs(); 2621 2622 // If the lhs block is the next block, invert the condition so that we can 2623 // fall through to the lhs instead of the rhs block. 2624 if (CB.TrueBB == NextBlock(SwitchBB)) { 2625 std::swap(CB.TrueBB, CB.FalseBB); 2626 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2627 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2628 } 2629 2630 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2631 MVT::Other, getControlRoot(), Cond, 2632 DAG.getBasicBlock(CB.TrueBB)); 2633 2634 setValue(CurInst, BrCond); 2635 2636 // Insert the false branch. Do this even if it's a fall through branch, 2637 // this makes it easier to do DAG optimizations which require inverting 2638 // the branch condition. 2639 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2640 DAG.getBasicBlock(CB.FalseBB)); 2641 2642 DAG.setRoot(BrCond); 2643 } 2644 2645 /// visitJumpTable - Emit JumpTable node in the current MBB 2646 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2647 // Emit the code for the jump table 2648 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2649 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2650 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2651 JT.Reg, PTy); 2652 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2653 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2654 MVT::Other, Index.getValue(1), 2655 Table, Index); 2656 DAG.setRoot(BrJumpTable); 2657 } 2658 2659 /// visitJumpTableHeader - This function emits necessary code to produce index 2660 /// in the JumpTable from switch case. 2661 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2662 JumpTableHeader &JTH, 2663 MachineBasicBlock *SwitchBB) { 2664 SDLoc dl = getCurSDLoc(); 2665 2666 // Subtract the lowest switch case value from the value being switched on. 2667 SDValue SwitchOp = getValue(JTH.SValue); 2668 EVT VT = SwitchOp.getValueType(); 2669 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2670 DAG.getConstant(JTH.First, dl, VT)); 2671 2672 // The SDNode we just created, which holds the value being switched on minus 2673 // the smallest case value, needs to be copied to a virtual register so it 2674 // can be used as an index into the jump table in a subsequent basic block. 2675 // This value may be smaller or larger than the target's pointer type, and 2676 // therefore require extension or truncating. 2677 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2678 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2679 2680 unsigned JumpTableReg = 2681 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2682 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2683 JumpTableReg, SwitchOp); 2684 JT.Reg = JumpTableReg; 2685 2686 if (!JTH.FallthroughUnreachable) { 2687 // Emit the range check for the jump table, and branch to the default block 2688 // for the switch statement if the value being switched on exceeds the 2689 // largest case in the switch. 2690 SDValue CMP = DAG.getSetCC( 2691 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2692 Sub.getValueType()), 2693 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2694 2695 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2696 MVT::Other, CopyTo, CMP, 2697 DAG.getBasicBlock(JT.Default)); 2698 2699 // Avoid emitting unnecessary branches to the next block. 2700 if (JT.MBB != NextBlock(SwitchBB)) 2701 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2702 DAG.getBasicBlock(JT.MBB)); 2703 2704 DAG.setRoot(BrCond); 2705 } else { 2706 // Avoid emitting unnecessary branches to the next block. 2707 if (JT.MBB != NextBlock(SwitchBB)) 2708 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2709 DAG.getBasicBlock(JT.MBB))); 2710 else 2711 DAG.setRoot(CopyTo); 2712 } 2713 } 2714 2715 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2716 /// variable if there exists one. 2717 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2718 SDValue &Chain) { 2719 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2720 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2721 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2722 MachineFunction &MF = DAG.getMachineFunction(); 2723 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2724 MachineSDNode *Node = 2725 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2726 if (Global) { 2727 MachinePointerInfo MPInfo(Global); 2728 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2729 MachineMemOperand::MODereferenceable; 2730 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2731 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2732 DAG.setNodeMemRefs(Node, {MemRef}); 2733 } 2734 if (PtrTy != PtrMemTy) 2735 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2736 return SDValue(Node, 0); 2737 } 2738 2739 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2740 /// tail spliced into a stack protector check success bb. 2741 /// 2742 /// For a high level explanation of how this fits into the stack protector 2743 /// generation see the comment on the declaration of class 2744 /// StackProtectorDescriptor. 2745 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2746 MachineBasicBlock *ParentBB) { 2747 2748 // First create the loads to the guard/stack slot for the comparison. 2749 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2750 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2751 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2752 2753 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2754 int FI = MFI.getStackProtectorIndex(); 2755 2756 SDValue Guard; 2757 SDLoc dl = getCurSDLoc(); 2758 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2759 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2760 Align Align = 2761 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2762 2763 // Generate code to load the content of the guard slot. 2764 SDValue GuardVal = DAG.getLoad( 2765 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2766 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2767 MachineMemOperand::MOVolatile); 2768 2769 if (TLI.useStackGuardXorFP()) 2770 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2771 2772 // Retrieve guard check function, nullptr if instrumentation is inlined. 2773 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2774 // The target provides a guard check function to validate the guard value. 2775 // Generate a call to that function with the content of the guard slot as 2776 // argument. 2777 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2778 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2779 2780 TargetLowering::ArgListTy Args; 2781 TargetLowering::ArgListEntry Entry; 2782 Entry.Node = GuardVal; 2783 Entry.Ty = FnTy->getParamType(0); 2784 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2785 Entry.IsInReg = true; 2786 Args.push_back(Entry); 2787 2788 TargetLowering::CallLoweringInfo CLI(DAG); 2789 CLI.setDebugLoc(getCurSDLoc()) 2790 .setChain(DAG.getEntryNode()) 2791 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2792 getValue(GuardCheckFn), std::move(Args)); 2793 2794 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2795 DAG.setRoot(Result.second); 2796 return; 2797 } 2798 2799 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2800 // Otherwise, emit a volatile load to retrieve the stack guard value. 2801 SDValue Chain = DAG.getEntryNode(); 2802 if (TLI.useLoadStackGuardNode()) { 2803 Guard = getLoadStackGuard(DAG, dl, Chain); 2804 } else { 2805 const Value *IRGuard = TLI.getSDagStackGuard(M); 2806 SDValue GuardPtr = getValue(IRGuard); 2807 2808 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2809 MachinePointerInfo(IRGuard, 0), Align, 2810 MachineMemOperand::MOVolatile); 2811 } 2812 2813 // Perform the comparison via a getsetcc. 2814 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2815 *DAG.getContext(), 2816 Guard.getValueType()), 2817 Guard, GuardVal, ISD::SETNE); 2818 2819 // If the guard/stackslot do not equal, branch to failure MBB. 2820 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2821 MVT::Other, GuardVal.getOperand(0), 2822 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2823 // Otherwise branch to success MBB. 2824 SDValue Br = DAG.getNode(ISD::BR, dl, 2825 MVT::Other, BrCond, 2826 DAG.getBasicBlock(SPD.getSuccessMBB())); 2827 2828 DAG.setRoot(Br); 2829 } 2830 2831 /// Codegen the failure basic block for a stack protector check. 2832 /// 2833 /// A failure stack protector machine basic block consists simply of a call to 2834 /// __stack_chk_fail(). 2835 /// 2836 /// For a high level explanation of how this fits into the stack protector 2837 /// generation see the comment on the declaration of class 2838 /// StackProtectorDescriptor. 2839 void 2840 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2841 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2842 TargetLowering::MakeLibCallOptions CallOptions; 2843 CallOptions.setDiscardResult(true); 2844 SDValue Chain = 2845 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2846 std::nullopt, CallOptions, getCurSDLoc()) 2847 .second; 2848 // On PS4/PS5, the "return address" must still be within the calling 2849 // function, even if it's at the very end, so emit an explicit TRAP here. 2850 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2851 if (TM.getTargetTriple().isPS()) 2852 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2853 // WebAssembly needs an unreachable instruction after a non-returning call, 2854 // because the function return type can be different from __stack_chk_fail's 2855 // return type (void). 2856 if (TM.getTargetTriple().isWasm()) 2857 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2858 2859 DAG.setRoot(Chain); 2860 } 2861 2862 /// visitBitTestHeader - This function emits necessary code to produce value 2863 /// suitable for "bit tests" 2864 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2865 MachineBasicBlock *SwitchBB) { 2866 SDLoc dl = getCurSDLoc(); 2867 2868 // Subtract the minimum value. 2869 SDValue SwitchOp = getValue(B.SValue); 2870 EVT VT = SwitchOp.getValueType(); 2871 SDValue RangeSub = 2872 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2873 2874 // Determine the type of the test operands. 2875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2876 bool UsePtrType = false; 2877 if (!TLI.isTypeLegal(VT)) { 2878 UsePtrType = true; 2879 } else { 2880 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2881 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2882 // Switch table case range are encoded into series of masks. 2883 // Just use pointer type, it's guaranteed to fit. 2884 UsePtrType = true; 2885 break; 2886 } 2887 } 2888 SDValue Sub = RangeSub; 2889 if (UsePtrType) { 2890 VT = TLI.getPointerTy(DAG.getDataLayout()); 2891 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2892 } 2893 2894 B.RegVT = VT.getSimpleVT(); 2895 B.Reg = FuncInfo.CreateReg(B.RegVT); 2896 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2897 2898 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2899 2900 if (!B.FallthroughUnreachable) 2901 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2902 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2903 SwitchBB->normalizeSuccProbs(); 2904 2905 SDValue Root = CopyTo; 2906 if (!B.FallthroughUnreachable) { 2907 // Conditional branch to the default block. 2908 SDValue RangeCmp = DAG.getSetCC(dl, 2909 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2910 RangeSub.getValueType()), 2911 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2912 ISD::SETUGT); 2913 2914 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2915 DAG.getBasicBlock(B.Default)); 2916 } 2917 2918 // Avoid emitting unnecessary branches to the next block. 2919 if (MBB != NextBlock(SwitchBB)) 2920 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2921 2922 DAG.setRoot(Root); 2923 } 2924 2925 /// visitBitTestCase - this function produces one "bit test" 2926 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2927 MachineBasicBlock* NextMBB, 2928 BranchProbability BranchProbToNext, 2929 unsigned Reg, 2930 BitTestCase &B, 2931 MachineBasicBlock *SwitchBB) { 2932 SDLoc dl = getCurSDLoc(); 2933 MVT VT = BB.RegVT; 2934 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2935 SDValue Cmp; 2936 unsigned PopCount = llvm::popcount(B.Mask); 2937 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2938 if (PopCount == 1) { 2939 // Testing for a single bit; just compare the shift count with what it 2940 // would need to be to shift a 1 bit in that position. 2941 Cmp = DAG.getSetCC( 2942 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2943 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2944 ISD::SETEQ); 2945 } else if (PopCount == BB.Range) { 2946 // There is only one zero bit in the range, test for it directly. 2947 Cmp = DAG.getSetCC( 2948 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2949 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2950 } else { 2951 // Make desired shift 2952 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2953 DAG.getConstant(1, dl, VT), ShiftOp); 2954 2955 // Emit bit tests and jumps 2956 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2957 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2958 Cmp = DAG.getSetCC( 2959 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2960 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2961 } 2962 2963 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2964 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2965 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2966 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2967 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2968 // one as they are relative probabilities (and thus work more like weights), 2969 // and hence we need to normalize them to let the sum of them become one. 2970 SwitchBB->normalizeSuccProbs(); 2971 2972 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2973 MVT::Other, getControlRoot(), 2974 Cmp, DAG.getBasicBlock(B.TargetBB)); 2975 2976 // Avoid emitting unnecessary branches to the next block. 2977 if (NextMBB != NextBlock(SwitchBB)) 2978 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2979 DAG.getBasicBlock(NextMBB)); 2980 2981 DAG.setRoot(BrAnd); 2982 } 2983 2984 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2985 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2986 2987 // Retrieve successors. Look through artificial IR level blocks like 2988 // catchswitch for successors. 2989 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2990 const BasicBlock *EHPadBB = I.getSuccessor(1); 2991 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 2992 2993 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2994 // have to do anything here to lower funclet bundles. 2995 assert(!I.hasOperandBundlesOtherThan( 2996 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2997 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2998 LLVMContext::OB_cfguardtarget, 2999 LLVMContext::OB_clang_arc_attachedcall}) && 3000 "Cannot lower invokes with arbitrary operand bundles yet!"); 3001 3002 const Value *Callee(I.getCalledOperand()); 3003 const Function *Fn = dyn_cast<Function>(Callee); 3004 if (isa<InlineAsm>(Callee)) 3005 visitInlineAsm(I, EHPadBB); 3006 else if (Fn && Fn->isIntrinsic()) { 3007 switch (Fn->getIntrinsicID()) { 3008 default: 3009 llvm_unreachable("Cannot invoke this intrinsic"); 3010 case Intrinsic::donothing: 3011 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3012 case Intrinsic::seh_try_begin: 3013 case Intrinsic::seh_scope_begin: 3014 case Intrinsic::seh_try_end: 3015 case Intrinsic::seh_scope_end: 3016 if (EHPadMBB) 3017 // a block referenced by EH table 3018 // so dtor-funclet not removed by opts 3019 EHPadMBB->setMachineBlockAddressTaken(); 3020 break; 3021 case Intrinsic::experimental_patchpoint_void: 3022 case Intrinsic::experimental_patchpoint_i64: 3023 visitPatchpoint(I, EHPadBB); 3024 break; 3025 case Intrinsic::experimental_gc_statepoint: 3026 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3027 break; 3028 case Intrinsic::wasm_rethrow: { 3029 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3030 // special because it can be invoked, so we manually lower it to a DAG 3031 // node here. 3032 SmallVector<SDValue, 8> Ops; 3033 Ops.push_back(getRoot()); // inchain 3034 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3035 Ops.push_back( 3036 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3037 TLI.getPointerTy(DAG.getDataLayout()))); 3038 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3039 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3040 break; 3041 } 3042 } 3043 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3044 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3045 // Eventually we will support lowering the @llvm.experimental.deoptimize 3046 // intrinsic, and right now there are no plans to support other intrinsics 3047 // with deopt state. 3048 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3049 } else { 3050 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3051 } 3052 3053 // If the value of the invoke is used outside of its defining block, make it 3054 // available as a virtual register. 3055 // We already took care of the exported value for the statepoint instruction 3056 // during call to the LowerStatepoint. 3057 if (!isa<GCStatepointInst>(I)) { 3058 CopyToExportRegsIfNeeded(&I); 3059 } 3060 3061 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3062 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3063 BranchProbability EHPadBBProb = 3064 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3065 : BranchProbability::getZero(); 3066 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3067 3068 // Update successor info. 3069 addSuccessorWithProb(InvokeMBB, Return); 3070 for (auto &UnwindDest : UnwindDests) { 3071 UnwindDest.first->setIsEHPad(); 3072 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3073 } 3074 InvokeMBB->normalizeSuccProbs(); 3075 3076 // Drop into normal successor. 3077 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3078 DAG.getBasicBlock(Return))); 3079 } 3080 3081 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3082 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3083 3084 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3085 // have to do anything here to lower funclet bundles. 3086 assert(!I.hasOperandBundlesOtherThan( 3087 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3088 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3089 3090 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3091 visitInlineAsm(I); 3092 CopyToExportRegsIfNeeded(&I); 3093 3094 // Retrieve successors. 3095 SmallPtrSet<BasicBlock *, 8> Dests; 3096 Dests.insert(I.getDefaultDest()); 3097 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3098 3099 // Update successor info. 3100 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3101 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3102 BasicBlock *Dest = I.getIndirectDest(i); 3103 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3104 Target->setIsInlineAsmBrIndirectTarget(); 3105 Target->setMachineBlockAddressTaken(); 3106 Target->setLabelMustBeEmitted(); 3107 // Don't add duplicate machine successors. 3108 if (Dests.insert(Dest).second) 3109 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3110 } 3111 CallBrMBB->normalizeSuccProbs(); 3112 3113 // Drop into default successor. 3114 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3115 MVT::Other, getControlRoot(), 3116 DAG.getBasicBlock(Return))); 3117 } 3118 3119 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3120 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3121 } 3122 3123 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3124 assert(FuncInfo.MBB->isEHPad() && 3125 "Call to landingpad not in landing pad!"); 3126 3127 // If there aren't registers to copy the values into (e.g., during SjLj 3128 // exceptions), then don't bother to create these DAG nodes. 3129 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3130 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3131 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3132 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3133 return; 3134 3135 // If landingpad's return type is token type, we don't create DAG nodes 3136 // for its exception pointer and selector value. The extraction of exception 3137 // pointer or selector value from token type landingpads is not currently 3138 // supported. 3139 if (LP.getType()->isTokenTy()) 3140 return; 3141 3142 SmallVector<EVT, 2> ValueVTs; 3143 SDLoc dl = getCurSDLoc(); 3144 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3145 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3146 3147 // Get the two live-in registers as SDValues. The physregs have already been 3148 // copied into virtual registers. 3149 SDValue Ops[2]; 3150 if (FuncInfo.ExceptionPointerVirtReg) { 3151 Ops[0] = DAG.getZExtOrTrunc( 3152 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3153 FuncInfo.ExceptionPointerVirtReg, 3154 TLI.getPointerTy(DAG.getDataLayout())), 3155 dl, ValueVTs[0]); 3156 } else { 3157 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3158 } 3159 Ops[1] = DAG.getZExtOrTrunc( 3160 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3161 FuncInfo.ExceptionSelectorVirtReg, 3162 TLI.getPointerTy(DAG.getDataLayout())), 3163 dl, ValueVTs[1]); 3164 3165 // Merge into one. 3166 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3167 DAG.getVTList(ValueVTs), Ops); 3168 setValue(&LP, Res); 3169 } 3170 3171 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3172 MachineBasicBlock *Last) { 3173 // Update JTCases. 3174 for (JumpTableBlock &JTB : SL->JTCases) 3175 if (JTB.first.HeaderBB == First) 3176 JTB.first.HeaderBB = Last; 3177 3178 // Update BitTestCases. 3179 for (BitTestBlock &BTB : SL->BitTestCases) 3180 if (BTB.Parent == First) 3181 BTB.Parent = Last; 3182 } 3183 3184 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3185 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3186 3187 // Update machine-CFG edges with unique successors. 3188 SmallSet<BasicBlock*, 32> Done; 3189 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3190 BasicBlock *BB = I.getSuccessor(i); 3191 bool Inserted = Done.insert(BB).second; 3192 if (!Inserted) 3193 continue; 3194 3195 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3196 addSuccessorWithProb(IndirectBrMBB, Succ); 3197 } 3198 IndirectBrMBB->normalizeSuccProbs(); 3199 3200 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3201 MVT::Other, getControlRoot(), 3202 getValue(I.getAddress()))); 3203 } 3204 3205 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3206 if (!DAG.getTarget().Options.TrapUnreachable) 3207 return; 3208 3209 // We may be able to ignore unreachable behind a noreturn call. 3210 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3211 const BasicBlock &BB = *I.getParent(); 3212 if (&I != &BB.front()) { 3213 BasicBlock::const_iterator PredI = 3214 std::prev(BasicBlock::const_iterator(&I)); 3215 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3216 if (Call->doesNotReturn()) 3217 return; 3218 } 3219 } 3220 } 3221 3222 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3223 } 3224 3225 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3226 SDNodeFlags Flags; 3227 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3228 Flags.copyFMF(*FPOp); 3229 3230 SDValue Op = getValue(I.getOperand(0)); 3231 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3232 Op, Flags); 3233 setValue(&I, UnNodeValue); 3234 } 3235 3236 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3237 SDNodeFlags Flags; 3238 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3239 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3240 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3241 } 3242 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3243 Flags.setExact(ExactOp->isExact()); 3244 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3245 Flags.copyFMF(*FPOp); 3246 3247 SDValue Op1 = getValue(I.getOperand(0)); 3248 SDValue Op2 = getValue(I.getOperand(1)); 3249 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3250 Op1, Op2, Flags); 3251 setValue(&I, BinNodeValue); 3252 } 3253 3254 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3255 SDValue Op1 = getValue(I.getOperand(0)); 3256 SDValue Op2 = getValue(I.getOperand(1)); 3257 3258 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3259 Op1.getValueType(), DAG.getDataLayout()); 3260 3261 // Coerce the shift amount to the right type if we can. This exposes the 3262 // truncate or zext to optimization early. 3263 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3264 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3265 "Unexpected shift type"); 3266 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3267 } 3268 3269 bool nuw = false; 3270 bool nsw = false; 3271 bool exact = false; 3272 3273 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3274 3275 if (const OverflowingBinaryOperator *OFBinOp = 3276 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3277 nuw = OFBinOp->hasNoUnsignedWrap(); 3278 nsw = OFBinOp->hasNoSignedWrap(); 3279 } 3280 if (const PossiblyExactOperator *ExactOp = 3281 dyn_cast<const PossiblyExactOperator>(&I)) 3282 exact = ExactOp->isExact(); 3283 } 3284 SDNodeFlags Flags; 3285 Flags.setExact(exact); 3286 Flags.setNoSignedWrap(nsw); 3287 Flags.setNoUnsignedWrap(nuw); 3288 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3289 Flags); 3290 setValue(&I, Res); 3291 } 3292 3293 void SelectionDAGBuilder::visitSDiv(const User &I) { 3294 SDValue Op1 = getValue(I.getOperand(0)); 3295 SDValue Op2 = getValue(I.getOperand(1)); 3296 3297 SDNodeFlags Flags; 3298 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3299 cast<PossiblyExactOperator>(&I)->isExact()); 3300 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3301 Op2, Flags)); 3302 } 3303 3304 void SelectionDAGBuilder::visitICmp(const User &I) { 3305 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3306 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3307 predicate = IC->getPredicate(); 3308 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3309 predicate = ICmpInst::Predicate(IC->getPredicate()); 3310 SDValue Op1 = getValue(I.getOperand(0)); 3311 SDValue Op2 = getValue(I.getOperand(1)); 3312 ISD::CondCode Opcode = getICmpCondCode(predicate); 3313 3314 auto &TLI = DAG.getTargetLoweringInfo(); 3315 EVT MemVT = 3316 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3317 3318 // If a pointer's DAG type is larger than its memory type then the DAG values 3319 // are zero-extended. This breaks signed comparisons so truncate back to the 3320 // underlying type before doing the compare. 3321 if (Op1.getValueType() != MemVT) { 3322 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3323 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3324 } 3325 3326 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3327 I.getType()); 3328 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3329 } 3330 3331 void SelectionDAGBuilder::visitFCmp(const User &I) { 3332 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3333 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3334 predicate = FC->getPredicate(); 3335 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3336 predicate = FCmpInst::Predicate(FC->getPredicate()); 3337 SDValue Op1 = getValue(I.getOperand(0)); 3338 SDValue Op2 = getValue(I.getOperand(1)); 3339 3340 ISD::CondCode Condition = getFCmpCondCode(predicate); 3341 auto *FPMO = cast<FPMathOperator>(&I); 3342 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3343 Condition = getFCmpCodeWithoutNaN(Condition); 3344 3345 SDNodeFlags Flags; 3346 Flags.copyFMF(*FPMO); 3347 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3348 3349 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3350 I.getType()); 3351 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3352 } 3353 3354 // Check if the condition of the select has one use or two users that are both 3355 // selects with the same condition. 3356 static bool hasOnlySelectUsers(const Value *Cond) { 3357 return llvm::all_of(Cond->users(), [](const Value *V) { 3358 return isa<SelectInst>(V); 3359 }); 3360 } 3361 3362 void SelectionDAGBuilder::visitSelect(const User &I) { 3363 SmallVector<EVT, 4> ValueVTs; 3364 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3365 ValueVTs); 3366 unsigned NumValues = ValueVTs.size(); 3367 if (NumValues == 0) return; 3368 3369 SmallVector<SDValue, 4> Values(NumValues); 3370 SDValue Cond = getValue(I.getOperand(0)); 3371 SDValue LHSVal = getValue(I.getOperand(1)); 3372 SDValue RHSVal = getValue(I.getOperand(2)); 3373 SmallVector<SDValue, 1> BaseOps(1, Cond); 3374 ISD::NodeType OpCode = 3375 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3376 3377 bool IsUnaryAbs = false; 3378 bool Negate = false; 3379 3380 SDNodeFlags Flags; 3381 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3382 Flags.copyFMF(*FPOp); 3383 3384 // Min/max matching is only viable if all output VTs are the same. 3385 if (all_equal(ValueVTs)) { 3386 EVT VT = ValueVTs[0]; 3387 LLVMContext &Ctx = *DAG.getContext(); 3388 auto &TLI = DAG.getTargetLoweringInfo(); 3389 3390 // We care about the legality of the operation after it has been type 3391 // legalized. 3392 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3393 VT = TLI.getTypeToTransformTo(Ctx, VT); 3394 3395 // If the vselect is legal, assume we want to leave this as a vector setcc + 3396 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3397 // min/max is legal on the scalar type. 3398 bool UseScalarMinMax = VT.isVector() && 3399 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3400 3401 // ValueTracking's select pattern matching does not account for -0.0, 3402 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3403 // -0.0 is less than +0.0. 3404 Value *LHS, *RHS; 3405 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3406 ISD::NodeType Opc = ISD::DELETED_NODE; 3407 switch (SPR.Flavor) { 3408 case SPF_UMAX: Opc = ISD::UMAX; break; 3409 case SPF_UMIN: Opc = ISD::UMIN; break; 3410 case SPF_SMAX: Opc = ISD::SMAX; break; 3411 case SPF_SMIN: Opc = ISD::SMIN; break; 3412 case SPF_FMINNUM: 3413 switch (SPR.NaNBehavior) { 3414 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3415 case SPNB_RETURNS_NAN: break; 3416 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3417 case SPNB_RETURNS_ANY: 3418 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3419 (UseScalarMinMax && 3420 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3421 Opc = ISD::FMINNUM; 3422 break; 3423 } 3424 break; 3425 case SPF_FMAXNUM: 3426 switch (SPR.NaNBehavior) { 3427 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3428 case SPNB_RETURNS_NAN: break; 3429 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3430 case SPNB_RETURNS_ANY: 3431 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3432 (UseScalarMinMax && 3433 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3434 Opc = ISD::FMAXNUM; 3435 break; 3436 } 3437 break; 3438 case SPF_NABS: 3439 Negate = true; 3440 [[fallthrough]]; 3441 case SPF_ABS: 3442 IsUnaryAbs = true; 3443 Opc = ISD::ABS; 3444 break; 3445 default: break; 3446 } 3447 3448 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3449 (TLI.isOperationLegalOrCustom(Opc, VT) || 3450 (UseScalarMinMax && 3451 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3452 // If the underlying comparison instruction is used by any other 3453 // instruction, the consumed instructions won't be destroyed, so it is 3454 // not profitable to convert to a min/max. 3455 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3456 OpCode = Opc; 3457 LHSVal = getValue(LHS); 3458 RHSVal = getValue(RHS); 3459 BaseOps.clear(); 3460 } 3461 3462 if (IsUnaryAbs) { 3463 OpCode = Opc; 3464 LHSVal = getValue(LHS); 3465 BaseOps.clear(); 3466 } 3467 } 3468 3469 if (IsUnaryAbs) { 3470 for (unsigned i = 0; i != NumValues; ++i) { 3471 SDLoc dl = getCurSDLoc(); 3472 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3473 Values[i] = 3474 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3475 if (Negate) 3476 Values[i] = DAG.getNegative(Values[i], dl, VT); 3477 } 3478 } else { 3479 for (unsigned i = 0; i != NumValues; ++i) { 3480 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3481 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3482 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3483 Values[i] = DAG.getNode( 3484 OpCode, getCurSDLoc(), 3485 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3486 } 3487 } 3488 3489 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3490 DAG.getVTList(ValueVTs), Values)); 3491 } 3492 3493 void SelectionDAGBuilder::visitTrunc(const User &I) { 3494 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3495 SDValue N = getValue(I.getOperand(0)); 3496 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3497 I.getType()); 3498 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3499 } 3500 3501 void SelectionDAGBuilder::visitZExt(const User &I) { 3502 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3503 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3504 SDValue N = getValue(I.getOperand(0)); 3505 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3506 I.getType()); 3507 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3508 } 3509 3510 void SelectionDAGBuilder::visitSExt(const User &I) { 3511 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3512 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3513 SDValue N = getValue(I.getOperand(0)); 3514 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3515 I.getType()); 3516 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3517 } 3518 3519 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3520 // FPTrunc is never a no-op cast, no need to check 3521 SDValue N = getValue(I.getOperand(0)); 3522 SDLoc dl = getCurSDLoc(); 3523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3524 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3525 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3526 DAG.getTargetConstant( 3527 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3528 } 3529 3530 void SelectionDAGBuilder::visitFPExt(const User &I) { 3531 // FPExt is never a no-op cast, no need to check 3532 SDValue N = getValue(I.getOperand(0)); 3533 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3534 I.getType()); 3535 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3536 } 3537 3538 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3539 // FPToUI is never a no-op cast, no need to check 3540 SDValue N = getValue(I.getOperand(0)); 3541 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3542 I.getType()); 3543 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3544 } 3545 3546 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3547 // FPToSI is never a no-op cast, no need to check 3548 SDValue N = getValue(I.getOperand(0)); 3549 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3550 I.getType()); 3551 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3552 } 3553 3554 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3555 // UIToFP is never a no-op cast, no need to check 3556 SDValue N = getValue(I.getOperand(0)); 3557 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3558 I.getType()); 3559 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3560 } 3561 3562 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3563 // SIToFP is never a no-op cast, no need to check 3564 SDValue N = getValue(I.getOperand(0)); 3565 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3566 I.getType()); 3567 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3568 } 3569 3570 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3571 // What to do depends on the size of the integer and the size of the pointer. 3572 // We can either truncate, zero extend, or no-op, accordingly. 3573 SDValue N = getValue(I.getOperand(0)); 3574 auto &TLI = DAG.getTargetLoweringInfo(); 3575 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3576 I.getType()); 3577 EVT PtrMemVT = 3578 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3579 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3580 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3581 setValue(&I, N); 3582 } 3583 3584 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3585 // What to do depends on the size of the integer and the size of the pointer. 3586 // We can either truncate, zero extend, or no-op, accordingly. 3587 SDValue N = getValue(I.getOperand(0)); 3588 auto &TLI = DAG.getTargetLoweringInfo(); 3589 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3590 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3591 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3592 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3593 setValue(&I, N); 3594 } 3595 3596 void SelectionDAGBuilder::visitBitCast(const User &I) { 3597 SDValue N = getValue(I.getOperand(0)); 3598 SDLoc dl = getCurSDLoc(); 3599 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3600 I.getType()); 3601 3602 // BitCast assures us that source and destination are the same size so this is 3603 // either a BITCAST or a no-op. 3604 if (DestVT != N.getValueType()) 3605 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3606 DestVT, N)); // convert types. 3607 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3608 // might fold any kind of constant expression to an integer constant and that 3609 // is not what we are looking for. Only recognize a bitcast of a genuine 3610 // constant integer as an opaque constant. 3611 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3612 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3613 /*isOpaque*/true)); 3614 else 3615 setValue(&I, N); // noop cast. 3616 } 3617 3618 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3620 const Value *SV = I.getOperand(0); 3621 SDValue N = getValue(SV); 3622 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3623 3624 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3625 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3626 3627 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3628 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3629 3630 setValue(&I, N); 3631 } 3632 3633 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3635 SDValue InVec = getValue(I.getOperand(0)); 3636 SDValue InVal = getValue(I.getOperand(1)); 3637 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3638 TLI.getVectorIdxTy(DAG.getDataLayout())); 3639 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3640 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3641 InVec, InVal, InIdx)); 3642 } 3643 3644 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3645 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3646 SDValue InVec = getValue(I.getOperand(0)); 3647 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3648 TLI.getVectorIdxTy(DAG.getDataLayout())); 3649 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3650 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3651 InVec, InIdx)); 3652 } 3653 3654 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3655 SDValue Src1 = getValue(I.getOperand(0)); 3656 SDValue Src2 = getValue(I.getOperand(1)); 3657 ArrayRef<int> Mask; 3658 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3659 Mask = SVI->getShuffleMask(); 3660 else 3661 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3662 SDLoc DL = getCurSDLoc(); 3663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3664 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3665 EVT SrcVT = Src1.getValueType(); 3666 3667 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3668 VT.isScalableVector()) { 3669 // Canonical splat form of first element of first input vector. 3670 SDValue FirstElt = 3671 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3672 DAG.getVectorIdxConstant(0, DL)); 3673 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3674 return; 3675 } 3676 3677 // For now, we only handle splats for scalable vectors. 3678 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3679 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3680 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3681 3682 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3683 unsigned MaskNumElts = Mask.size(); 3684 3685 if (SrcNumElts == MaskNumElts) { 3686 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3687 return; 3688 } 3689 3690 // Normalize the shuffle vector since mask and vector length don't match. 3691 if (SrcNumElts < MaskNumElts) { 3692 // Mask is longer than the source vectors. We can use concatenate vector to 3693 // make the mask and vectors lengths match. 3694 3695 if (MaskNumElts % SrcNumElts == 0) { 3696 // Mask length is a multiple of the source vector length. 3697 // Check if the shuffle is some kind of concatenation of the input 3698 // vectors. 3699 unsigned NumConcat = MaskNumElts / SrcNumElts; 3700 bool IsConcat = true; 3701 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3702 for (unsigned i = 0; i != MaskNumElts; ++i) { 3703 int Idx = Mask[i]; 3704 if (Idx < 0) 3705 continue; 3706 // Ensure the indices in each SrcVT sized piece are sequential and that 3707 // the same source is used for the whole piece. 3708 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3709 (ConcatSrcs[i / SrcNumElts] >= 0 && 3710 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3711 IsConcat = false; 3712 break; 3713 } 3714 // Remember which source this index came from. 3715 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3716 } 3717 3718 // The shuffle is concatenating multiple vectors together. Just emit 3719 // a CONCAT_VECTORS operation. 3720 if (IsConcat) { 3721 SmallVector<SDValue, 8> ConcatOps; 3722 for (auto Src : ConcatSrcs) { 3723 if (Src < 0) 3724 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3725 else if (Src == 0) 3726 ConcatOps.push_back(Src1); 3727 else 3728 ConcatOps.push_back(Src2); 3729 } 3730 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3731 return; 3732 } 3733 } 3734 3735 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3736 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3737 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3738 PaddedMaskNumElts); 3739 3740 // Pad both vectors with undefs to make them the same length as the mask. 3741 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3742 3743 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3744 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3745 MOps1[0] = Src1; 3746 MOps2[0] = Src2; 3747 3748 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3749 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3750 3751 // Readjust mask for new input vector length. 3752 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3753 for (unsigned i = 0; i != MaskNumElts; ++i) { 3754 int Idx = Mask[i]; 3755 if (Idx >= (int)SrcNumElts) 3756 Idx -= SrcNumElts - PaddedMaskNumElts; 3757 MappedOps[i] = Idx; 3758 } 3759 3760 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3761 3762 // If the concatenated vector was padded, extract a subvector with the 3763 // correct number of elements. 3764 if (MaskNumElts != PaddedMaskNumElts) 3765 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3766 DAG.getVectorIdxConstant(0, DL)); 3767 3768 setValue(&I, Result); 3769 return; 3770 } 3771 3772 if (SrcNumElts > MaskNumElts) { 3773 // Analyze the access pattern of the vector to see if we can extract 3774 // two subvectors and do the shuffle. 3775 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3776 bool CanExtract = true; 3777 for (int Idx : Mask) { 3778 unsigned Input = 0; 3779 if (Idx < 0) 3780 continue; 3781 3782 if (Idx >= (int)SrcNumElts) { 3783 Input = 1; 3784 Idx -= SrcNumElts; 3785 } 3786 3787 // If all the indices come from the same MaskNumElts sized portion of 3788 // the sources we can use extract. Also make sure the extract wouldn't 3789 // extract past the end of the source. 3790 int NewStartIdx = alignDown(Idx, MaskNumElts); 3791 if (NewStartIdx + MaskNumElts > SrcNumElts || 3792 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3793 CanExtract = false; 3794 // Make sure we always update StartIdx as we use it to track if all 3795 // elements are undef. 3796 StartIdx[Input] = NewStartIdx; 3797 } 3798 3799 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3800 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3801 return; 3802 } 3803 if (CanExtract) { 3804 // Extract appropriate subvector and generate a vector shuffle 3805 for (unsigned Input = 0; Input < 2; ++Input) { 3806 SDValue &Src = Input == 0 ? Src1 : Src2; 3807 if (StartIdx[Input] < 0) 3808 Src = DAG.getUNDEF(VT); 3809 else { 3810 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3811 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3812 } 3813 } 3814 3815 // Calculate new mask. 3816 SmallVector<int, 8> MappedOps(Mask); 3817 for (int &Idx : MappedOps) { 3818 if (Idx >= (int)SrcNumElts) 3819 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3820 else if (Idx >= 0) 3821 Idx -= StartIdx[0]; 3822 } 3823 3824 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3825 return; 3826 } 3827 } 3828 3829 // We can't use either concat vectors or extract subvectors so fall back to 3830 // replacing the shuffle with extract and build vector. 3831 // to insert and build vector. 3832 EVT EltVT = VT.getVectorElementType(); 3833 SmallVector<SDValue,8> Ops; 3834 for (int Idx : Mask) { 3835 SDValue Res; 3836 3837 if (Idx < 0) { 3838 Res = DAG.getUNDEF(EltVT); 3839 } else { 3840 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3841 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3842 3843 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3844 DAG.getVectorIdxConstant(Idx, DL)); 3845 } 3846 3847 Ops.push_back(Res); 3848 } 3849 3850 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3851 } 3852 3853 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3854 ArrayRef<unsigned> Indices = I.getIndices(); 3855 const Value *Op0 = I.getOperand(0); 3856 const Value *Op1 = I.getOperand(1); 3857 Type *AggTy = I.getType(); 3858 Type *ValTy = Op1->getType(); 3859 bool IntoUndef = isa<UndefValue>(Op0); 3860 bool FromUndef = isa<UndefValue>(Op1); 3861 3862 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3863 3864 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3865 SmallVector<EVT, 4> AggValueVTs; 3866 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3867 SmallVector<EVT, 4> ValValueVTs; 3868 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3869 3870 unsigned NumAggValues = AggValueVTs.size(); 3871 unsigned NumValValues = ValValueVTs.size(); 3872 SmallVector<SDValue, 4> Values(NumAggValues); 3873 3874 // Ignore an insertvalue that produces an empty object 3875 if (!NumAggValues) { 3876 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3877 return; 3878 } 3879 3880 SDValue Agg = getValue(Op0); 3881 unsigned i = 0; 3882 // Copy the beginning value(s) from the original aggregate. 3883 for (; i != LinearIndex; ++i) 3884 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3885 SDValue(Agg.getNode(), Agg.getResNo() + i); 3886 // Copy values from the inserted value(s). 3887 if (NumValValues) { 3888 SDValue Val = getValue(Op1); 3889 for (; i != LinearIndex + NumValValues; ++i) 3890 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3891 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3892 } 3893 // Copy remaining value(s) from the original aggregate. 3894 for (; i != NumAggValues; ++i) 3895 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3896 SDValue(Agg.getNode(), Agg.getResNo() + i); 3897 3898 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3899 DAG.getVTList(AggValueVTs), Values)); 3900 } 3901 3902 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3903 ArrayRef<unsigned> Indices = I.getIndices(); 3904 const Value *Op0 = I.getOperand(0); 3905 Type *AggTy = Op0->getType(); 3906 Type *ValTy = I.getType(); 3907 bool OutOfUndef = isa<UndefValue>(Op0); 3908 3909 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3910 3911 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3912 SmallVector<EVT, 4> ValValueVTs; 3913 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3914 3915 unsigned NumValValues = ValValueVTs.size(); 3916 3917 // Ignore a extractvalue that produces an empty object 3918 if (!NumValValues) { 3919 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3920 return; 3921 } 3922 3923 SmallVector<SDValue, 4> Values(NumValValues); 3924 3925 SDValue Agg = getValue(Op0); 3926 // Copy out the selected value(s). 3927 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3928 Values[i - LinearIndex] = 3929 OutOfUndef ? 3930 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3931 SDValue(Agg.getNode(), Agg.getResNo() + i); 3932 3933 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3934 DAG.getVTList(ValValueVTs), Values)); 3935 } 3936 3937 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3938 Value *Op0 = I.getOperand(0); 3939 // Note that the pointer operand may be a vector of pointers. Take the scalar 3940 // element which holds a pointer. 3941 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3942 SDValue N = getValue(Op0); 3943 SDLoc dl = getCurSDLoc(); 3944 auto &TLI = DAG.getTargetLoweringInfo(); 3945 3946 // Normalize Vector GEP - all scalar operands should be converted to the 3947 // splat vector. 3948 bool IsVectorGEP = I.getType()->isVectorTy(); 3949 ElementCount VectorElementCount = 3950 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3951 : ElementCount::getFixed(0); 3952 3953 if (IsVectorGEP && !N.getValueType().isVector()) { 3954 LLVMContext &Context = *DAG.getContext(); 3955 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3956 N = DAG.getSplat(VT, dl, N); 3957 } 3958 3959 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3960 GTI != E; ++GTI) { 3961 const Value *Idx = GTI.getOperand(); 3962 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3963 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3964 if (Field) { 3965 // N = N + Offset 3966 uint64_t Offset = 3967 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3968 3969 // In an inbounds GEP with an offset that is nonnegative even when 3970 // interpreted as signed, assume there is no unsigned overflow. 3971 SDNodeFlags Flags; 3972 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3973 Flags.setNoUnsignedWrap(true); 3974 3975 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3976 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3977 } 3978 } else { 3979 // IdxSize is the width of the arithmetic according to IR semantics. 3980 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3981 // (and fix up the result later). 3982 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3983 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3984 TypeSize ElementSize = 3985 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3986 // We intentionally mask away the high bits here; ElementSize may not 3987 // fit in IdxTy. 3988 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3989 bool ElementScalable = ElementSize.isScalable(); 3990 3991 // If this is a scalar constant or a splat vector of constants, 3992 // handle it quickly. 3993 const auto *C = dyn_cast<Constant>(Idx); 3994 if (C && isa<VectorType>(C->getType())) 3995 C = C->getSplatValue(); 3996 3997 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3998 if (CI && CI->isZero()) 3999 continue; 4000 if (CI && !ElementScalable) { 4001 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4002 LLVMContext &Context = *DAG.getContext(); 4003 SDValue OffsVal; 4004 if (IsVectorGEP) 4005 OffsVal = DAG.getConstant( 4006 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4007 else 4008 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4009 4010 // In an inbounds GEP with an offset that is nonnegative even when 4011 // interpreted as signed, assume there is no unsigned overflow. 4012 SDNodeFlags Flags; 4013 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4014 Flags.setNoUnsignedWrap(true); 4015 4016 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4017 4018 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4019 continue; 4020 } 4021 4022 // N = N + Idx * ElementMul; 4023 SDValue IdxN = getValue(Idx); 4024 4025 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4026 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4027 VectorElementCount); 4028 IdxN = DAG.getSplat(VT, dl, IdxN); 4029 } 4030 4031 // If the index is smaller or larger than intptr_t, truncate or extend 4032 // it. 4033 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4034 4035 if (ElementScalable) { 4036 EVT VScaleTy = N.getValueType().getScalarType(); 4037 SDValue VScale = DAG.getNode( 4038 ISD::VSCALE, dl, VScaleTy, 4039 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4040 if (IsVectorGEP) 4041 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4042 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4043 } else { 4044 // If this is a multiply by a power of two, turn it into a shl 4045 // immediately. This is a very common case. 4046 if (ElementMul != 1) { 4047 if (ElementMul.isPowerOf2()) { 4048 unsigned Amt = ElementMul.logBase2(); 4049 IdxN = DAG.getNode(ISD::SHL, dl, 4050 N.getValueType(), IdxN, 4051 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4052 } else { 4053 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4054 IdxN.getValueType()); 4055 IdxN = DAG.getNode(ISD::MUL, dl, 4056 N.getValueType(), IdxN, Scale); 4057 } 4058 } 4059 } 4060 4061 N = DAG.getNode(ISD::ADD, dl, 4062 N.getValueType(), N, IdxN); 4063 } 4064 } 4065 4066 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4067 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4068 if (IsVectorGEP) { 4069 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4070 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4071 } 4072 4073 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4074 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4075 4076 setValue(&I, N); 4077 } 4078 4079 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4080 // If this is a fixed sized alloca in the entry block of the function, 4081 // allocate it statically on the stack. 4082 if (FuncInfo.StaticAllocaMap.count(&I)) 4083 return; // getValue will auto-populate this. 4084 4085 SDLoc dl = getCurSDLoc(); 4086 Type *Ty = I.getAllocatedType(); 4087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4088 auto &DL = DAG.getDataLayout(); 4089 TypeSize TySize = DL.getTypeAllocSize(Ty); 4090 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4091 4092 SDValue AllocSize = getValue(I.getArraySize()); 4093 4094 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4095 if (AllocSize.getValueType() != IntPtr) 4096 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4097 4098 if (TySize.isScalable()) 4099 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4100 DAG.getVScale(dl, IntPtr, 4101 APInt(IntPtr.getScalarSizeInBits(), 4102 TySize.getKnownMinValue()))); 4103 else 4104 AllocSize = 4105 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4106 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4107 4108 // Handle alignment. If the requested alignment is less than or equal to 4109 // the stack alignment, ignore it. If the size is greater than or equal to 4110 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4111 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4112 if (*Alignment <= StackAlign) 4113 Alignment = std::nullopt; 4114 4115 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4116 // Round the size of the allocation up to the stack alignment size 4117 // by add SA-1 to the size. This doesn't overflow because we're computing 4118 // an address inside an alloca. 4119 SDNodeFlags Flags; 4120 Flags.setNoUnsignedWrap(true); 4121 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4122 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4123 4124 // Mask out the low bits for alignment purposes. 4125 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4126 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4127 4128 SDValue Ops[] = { 4129 getRoot(), AllocSize, 4130 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4131 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4132 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4133 setValue(&I, DSA); 4134 DAG.setRoot(DSA.getValue(1)); 4135 4136 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4137 } 4138 4139 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4140 if (I.isAtomic()) 4141 return visitAtomicLoad(I); 4142 4143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4144 const Value *SV = I.getOperand(0); 4145 if (TLI.supportSwiftError()) { 4146 // Swifterror values can come from either a function parameter with 4147 // swifterror attribute or an alloca with swifterror attribute. 4148 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4149 if (Arg->hasSwiftErrorAttr()) 4150 return visitLoadFromSwiftError(I); 4151 } 4152 4153 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4154 if (Alloca->isSwiftError()) 4155 return visitLoadFromSwiftError(I); 4156 } 4157 } 4158 4159 SDValue Ptr = getValue(SV); 4160 4161 Type *Ty = I.getType(); 4162 SmallVector<EVT, 4> ValueVTs, MemVTs; 4163 SmallVector<uint64_t, 4> Offsets; 4164 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4165 unsigned NumValues = ValueVTs.size(); 4166 if (NumValues == 0) 4167 return; 4168 4169 Align Alignment = I.getAlign(); 4170 AAMDNodes AAInfo = I.getAAMetadata(); 4171 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4172 bool isVolatile = I.isVolatile(); 4173 MachineMemOperand::Flags MMOFlags = 4174 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4175 4176 SDValue Root; 4177 bool ConstantMemory = false; 4178 if (isVolatile) 4179 // Serialize volatile loads with other side effects. 4180 Root = getRoot(); 4181 else if (NumValues > MaxParallelChains) 4182 Root = getMemoryRoot(); 4183 else if (AA && 4184 AA->pointsToConstantMemory(MemoryLocation( 4185 SV, 4186 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4187 AAInfo))) { 4188 // Do not serialize (non-volatile) loads of constant memory with anything. 4189 Root = DAG.getEntryNode(); 4190 ConstantMemory = true; 4191 MMOFlags |= MachineMemOperand::MOInvariant; 4192 } else { 4193 // Do not serialize non-volatile loads against each other. 4194 Root = DAG.getRoot(); 4195 } 4196 4197 SDLoc dl = getCurSDLoc(); 4198 4199 if (isVolatile) 4200 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4201 4202 // An aggregate load cannot wrap around the address space, so offsets to its 4203 // parts don't wrap either. 4204 SDNodeFlags Flags; 4205 Flags.setNoUnsignedWrap(true); 4206 4207 SmallVector<SDValue, 4> Values(NumValues); 4208 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4209 EVT PtrVT = Ptr.getValueType(); 4210 4211 unsigned ChainI = 0; 4212 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4213 // Serializing loads here may result in excessive register pressure, and 4214 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4215 // could recover a bit by hoisting nodes upward in the chain by recognizing 4216 // they are side-effect free or do not alias. The optimizer should really 4217 // avoid this case by converting large object/array copies to llvm.memcpy 4218 // (MaxParallelChains should always remain as failsafe). 4219 if (ChainI == MaxParallelChains) { 4220 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4221 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4222 ArrayRef(Chains.data(), ChainI)); 4223 Root = Chain; 4224 ChainI = 0; 4225 } 4226 SDValue A = DAG.getNode(ISD::ADD, dl, 4227 PtrVT, Ptr, 4228 DAG.getConstant(Offsets[i], dl, PtrVT), 4229 Flags); 4230 4231 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4232 MachinePointerInfo(SV, Offsets[i]), Alignment, 4233 MMOFlags, AAInfo, Ranges); 4234 Chains[ChainI] = L.getValue(1); 4235 4236 if (MemVTs[i] != ValueVTs[i]) 4237 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4238 4239 Values[i] = L; 4240 } 4241 4242 if (!ConstantMemory) { 4243 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4244 ArrayRef(Chains.data(), ChainI)); 4245 if (isVolatile) 4246 DAG.setRoot(Chain); 4247 else 4248 PendingLoads.push_back(Chain); 4249 } 4250 4251 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4252 DAG.getVTList(ValueVTs), Values)); 4253 } 4254 4255 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4256 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4257 "call visitStoreToSwiftError when backend supports swifterror"); 4258 4259 SmallVector<EVT, 4> ValueVTs; 4260 SmallVector<uint64_t, 4> Offsets; 4261 const Value *SrcV = I.getOperand(0); 4262 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4263 SrcV->getType(), ValueVTs, &Offsets, 0); 4264 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4265 "expect a single EVT for swifterror"); 4266 4267 SDValue Src = getValue(SrcV); 4268 // Create a virtual register, then update the virtual register. 4269 Register VReg = 4270 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4271 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4272 // Chain can be getRoot or getControlRoot. 4273 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4274 SDValue(Src.getNode(), Src.getResNo())); 4275 DAG.setRoot(CopyNode); 4276 } 4277 4278 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4279 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4280 "call visitLoadFromSwiftError when backend supports swifterror"); 4281 4282 assert(!I.isVolatile() && 4283 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4284 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4285 "Support volatile, non temporal, invariant for load_from_swift_error"); 4286 4287 const Value *SV = I.getOperand(0); 4288 Type *Ty = I.getType(); 4289 assert( 4290 (!AA || 4291 !AA->pointsToConstantMemory(MemoryLocation( 4292 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4293 I.getAAMetadata()))) && 4294 "load_from_swift_error should not be constant memory"); 4295 4296 SmallVector<EVT, 4> ValueVTs; 4297 SmallVector<uint64_t, 4> Offsets; 4298 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4299 ValueVTs, &Offsets, 0); 4300 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4301 "expect a single EVT for swifterror"); 4302 4303 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4304 SDValue L = DAG.getCopyFromReg( 4305 getRoot(), getCurSDLoc(), 4306 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4307 4308 setValue(&I, L); 4309 } 4310 4311 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4312 if (I.isAtomic()) 4313 return visitAtomicStore(I); 4314 4315 const Value *SrcV = I.getOperand(0); 4316 const Value *PtrV = I.getOperand(1); 4317 4318 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4319 if (TLI.supportSwiftError()) { 4320 // Swifterror values can come from either a function parameter with 4321 // swifterror attribute or an alloca with swifterror attribute. 4322 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4323 if (Arg->hasSwiftErrorAttr()) 4324 return visitStoreToSwiftError(I); 4325 } 4326 4327 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4328 if (Alloca->isSwiftError()) 4329 return visitStoreToSwiftError(I); 4330 } 4331 } 4332 4333 SmallVector<EVT, 4> ValueVTs, MemVTs; 4334 SmallVector<uint64_t, 4> Offsets; 4335 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4336 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4337 unsigned NumValues = ValueVTs.size(); 4338 if (NumValues == 0) 4339 return; 4340 4341 // Get the lowered operands. Note that we do this after 4342 // checking if NumResults is zero, because with zero results 4343 // the operands won't have values in the map. 4344 SDValue Src = getValue(SrcV); 4345 SDValue Ptr = getValue(PtrV); 4346 4347 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4348 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4349 SDLoc dl = getCurSDLoc(); 4350 Align Alignment = I.getAlign(); 4351 AAMDNodes AAInfo = I.getAAMetadata(); 4352 4353 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4354 4355 // An aggregate load cannot wrap around the address space, so offsets to its 4356 // parts don't wrap either. 4357 SDNodeFlags Flags; 4358 Flags.setNoUnsignedWrap(true); 4359 4360 unsigned ChainI = 0; 4361 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4362 // See visitLoad comments. 4363 if (ChainI == MaxParallelChains) { 4364 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4365 ArrayRef(Chains.data(), ChainI)); 4366 Root = Chain; 4367 ChainI = 0; 4368 } 4369 SDValue Add = 4370 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4371 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4372 if (MemVTs[i] != ValueVTs[i]) 4373 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4374 SDValue St = 4375 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4376 Alignment, MMOFlags, AAInfo); 4377 Chains[ChainI] = St; 4378 } 4379 4380 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4381 ArrayRef(Chains.data(), ChainI)); 4382 setValue(&I, StoreNode); 4383 DAG.setRoot(StoreNode); 4384 } 4385 4386 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4387 bool IsCompressing) { 4388 SDLoc sdl = getCurSDLoc(); 4389 4390 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4391 MaybeAlign &Alignment) { 4392 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4393 Src0 = I.getArgOperand(0); 4394 Ptr = I.getArgOperand(1); 4395 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4396 Mask = I.getArgOperand(3); 4397 }; 4398 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4399 MaybeAlign &Alignment) { 4400 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4401 Src0 = I.getArgOperand(0); 4402 Ptr = I.getArgOperand(1); 4403 Mask = I.getArgOperand(2); 4404 Alignment = std::nullopt; 4405 }; 4406 4407 Value *PtrOperand, *MaskOperand, *Src0Operand; 4408 MaybeAlign Alignment; 4409 if (IsCompressing) 4410 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4411 else 4412 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4413 4414 SDValue Ptr = getValue(PtrOperand); 4415 SDValue Src0 = getValue(Src0Operand); 4416 SDValue Mask = getValue(MaskOperand); 4417 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4418 4419 EVT VT = Src0.getValueType(); 4420 if (!Alignment) 4421 Alignment = DAG.getEVTAlign(VT); 4422 4423 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4424 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4425 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4426 SDValue StoreNode = 4427 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4428 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4429 DAG.setRoot(StoreNode); 4430 setValue(&I, StoreNode); 4431 } 4432 4433 // Get a uniform base for the Gather/Scatter intrinsic. 4434 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4435 // We try to represent it as a base pointer + vector of indices. 4436 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4437 // The first operand of the GEP may be a single pointer or a vector of pointers 4438 // Example: 4439 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4440 // or 4441 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4442 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4443 // 4444 // When the first GEP operand is a single pointer - it is the uniform base we 4445 // are looking for. If first operand of the GEP is a splat vector - we 4446 // extract the splat value and use it as a uniform base. 4447 // In all other cases the function returns 'false'. 4448 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4449 ISD::MemIndexType &IndexType, SDValue &Scale, 4450 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4451 uint64_t ElemSize) { 4452 SelectionDAG& DAG = SDB->DAG; 4453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4454 const DataLayout &DL = DAG.getDataLayout(); 4455 4456 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4457 4458 // Handle splat constant pointer. 4459 if (auto *C = dyn_cast<Constant>(Ptr)) { 4460 C = C->getSplatValue(); 4461 if (!C) 4462 return false; 4463 4464 Base = SDB->getValue(C); 4465 4466 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4467 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4468 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4469 IndexType = ISD::SIGNED_SCALED; 4470 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4471 return true; 4472 } 4473 4474 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4475 if (!GEP || GEP->getParent() != CurBB) 4476 return false; 4477 4478 if (GEP->getNumOperands() != 2) 4479 return false; 4480 4481 const Value *BasePtr = GEP->getPointerOperand(); 4482 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4483 4484 // Make sure the base is scalar and the index is a vector. 4485 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4486 return false; 4487 4488 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4489 4490 // Target may not support the required addressing mode. 4491 if (ScaleVal != 1 && 4492 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4493 return false; 4494 4495 Base = SDB->getValue(BasePtr); 4496 Index = SDB->getValue(IndexVal); 4497 IndexType = ISD::SIGNED_SCALED; 4498 4499 Scale = 4500 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4501 return true; 4502 } 4503 4504 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4505 SDLoc sdl = getCurSDLoc(); 4506 4507 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4508 const Value *Ptr = I.getArgOperand(1); 4509 SDValue Src0 = getValue(I.getArgOperand(0)); 4510 SDValue Mask = getValue(I.getArgOperand(3)); 4511 EVT VT = Src0.getValueType(); 4512 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4513 ->getMaybeAlignValue() 4514 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4515 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4516 4517 SDValue Base; 4518 SDValue Index; 4519 ISD::MemIndexType IndexType; 4520 SDValue Scale; 4521 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4522 I.getParent(), VT.getScalarStoreSize()); 4523 4524 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4525 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4526 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4527 // TODO: Make MachineMemOperands aware of scalable 4528 // vectors. 4529 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4530 if (!UniformBase) { 4531 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4532 Index = getValue(Ptr); 4533 IndexType = ISD::SIGNED_SCALED; 4534 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4535 } 4536 4537 EVT IdxVT = Index.getValueType(); 4538 EVT EltTy = IdxVT.getVectorElementType(); 4539 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4540 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4541 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4542 } 4543 4544 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4545 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4546 Ops, MMO, IndexType, false); 4547 DAG.setRoot(Scatter); 4548 setValue(&I, Scatter); 4549 } 4550 4551 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4552 SDLoc sdl = getCurSDLoc(); 4553 4554 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4555 MaybeAlign &Alignment) { 4556 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4557 Ptr = I.getArgOperand(0); 4558 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4559 Mask = I.getArgOperand(2); 4560 Src0 = I.getArgOperand(3); 4561 }; 4562 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4563 MaybeAlign &Alignment) { 4564 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4565 Ptr = I.getArgOperand(0); 4566 Alignment = std::nullopt; 4567 Mask = I.getArgOperand(1); 4568 Src0 = I.getArgOperand(2); 4569 }; 4570 4571 Value *PtrOperand, *MaskOperand, *Src0Operand; 4572 MaybeAlign Alignment; 4573 if (IsExpanding) 4574 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4575 else 4576 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4577 4578 SDValue Ptr = getValue(PtrOperand); 4579 SDValue Src0 = getValue(Src0Operand); 4580 SDValue Mask = getValue(MaskOperand); 4581 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4582 4583 EVT VT = Src0.getValueType(); 4584 if (!Alignment) 4585 Alignment = DAG.getEVTAlign(VT); 4586 4587 AAMDNodes AAInfo = I.getAAMetadata(); 4588 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4589 4590 // Do not serialize masked loads of constant memory with anything. 4591 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4592 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4593 4594 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4595 4596 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4597 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4598 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4599 4600 SDValue Load = 4601 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4602 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4603 if (AddToChain) 4604 PendingLoads.push_back(Load.getValue(1)); 4605 setValue(&I, Load); 4606 } 4607 4608 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4609 SDLoc sdl = getCurSDLoc(); 4610 4611 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4612 const Value *Ptr = I.getArgOperand(0); 4613 SDValue Src0 = getValue(I.getArgOperand(3)); 4614 SDValue Mask = getValue(I.getArgOperand(2)); 4615 4616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4617 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4618 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4619 ->getMaybeAlignValue() 4620 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4621 4622 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4623 4624 SDValue Root = DAG.getRoot(); 4625 SDValue Base; 4626 SDValue Index; 4627 ISD::MemIndexType IndexType; 4628 SDValue Scale; 4629 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4630 I.getParent(), VT.getScalarStoreSize()); 4631 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4632 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4633 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4634 // TODO: Make MachineMemOperands aware of scalable 4635 // vectors. 4636 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4637 4638 if (!UniformBase) { 4639 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4640 Index = getValue(Ptr); 4641 IndexType = ISD::SIGNED_SCALED; 4642 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4643 } 4644 4645 EVT IdxVT = Index.getValueType(); 4646 EVT EltTy = IdxVT.getVectorElementType(); 4647 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4648 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4649 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4650 } 4651 4652 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4653 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4654 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4655 4656 PendingLoads.push_back(Gather.getValue(1)); 4657 setValue(&I, Gather); 4658 } 4659 4660 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4661 SDLoc dl = getCurSDLoc(); 4662 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4663 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4664 SyncScope::ID SSID = I.getSyncScopeID(); 4665 4666 SDValue InChain = getRoot(); 4667 4668 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4669 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4670 4671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4672 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4673 4674 MachineFunction &MF = DAG.getMachineFunction(); 4675 MachineMemOperand *MMO = MF.getMachineMemOperand( 4676 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4677 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4678 FailureOrdering); 4679 4680 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4681 dl, MemVT, VTs, InChain, 4682 getValue(I.getPointerOperand()), 4683 getValue(I.getCompareOperand()), 4684 getValue(I.getNewValOperand()), MMO); 4685 4686 SDValue OutChain = L.getValue(2); 4687 4688 setValue(&I, L); 4689 DAG.setRoot(OutChain); 4690 } 4691 4692 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4693 SDLoc dl = getCurSDLoc(); 4694 ISD::NodeType NT; 4695 switch (I.getOperation()) { 4696 default: llvm_unreachable("Unknown atomicrmw operation"); 4697 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4698 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4699 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4700 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4701 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4702 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4703 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4704 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4705 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4706 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4707 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4708 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4709 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4710 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4711 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4712 case AtomicRMWInst::UIncWrap: 4713 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4714 break; 4715 case AtomicRMWInst::UDecWrap: 4716 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4717 break; 4718 } 4719 AtomicOrdering Ordering = I.getOrdering(); 4720 SyncScope::ID SSID = I.getSyncScopeID(); 4721 4722 SDValue InChain = getRoot(); 4723 4724 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4725 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4726 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4727 4728 MachineFunction &MF = DAG.getMachineFunction(); 4729 MachineMemOperand *MMO = MF.getMachineMemOperand( 4730 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4731 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4732 4733 SDValue L = 4734 DAG.getAtomic(NT, dl, MemVT, InChain, 4735 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4736 MMO); 4737 4738 SDValue OutChain = L.getValue(1); 4739 4740 setValue(&I, L); 4741 DAG.setRoot(OutChain); 4742 } 4743 4744 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4745 SDLoc dl = getCurSDLoc(); 4746 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4747 SDValue Ops[3]; 4748 Ops[0] = getRoot(); 4749 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4750 TLI.getFenceOperandTy(DAG.getDataLayout())); 4751 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4752 TLI.getFenceOperandTy(DAG.getDataLayout())); 4753 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4754 setValue(&I, N); 4755 DAG.setRoot(N); 4756 } 4757 4758 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4759 SDLoc dl = getCurSDLoc(); 4760 AtomicOrdering Order = I.getOrdering(); 4761 SyncScope::ID SSID = I.getSyncScopeID(); 4762 4763 SDValue InChain = getRoot(); 4764 4765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4766 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4767 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4768 4769 if (!TLI.supportsUnalignedAtomics() && 4770 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4771 report_fatal_error("Cannot generate unaligned atomic load"); 4772 4773 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4774 4775 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4776 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4777 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4778 4779 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4780 4781 SDValue Ptr = getValue(I.getPointerOperand()); 4782 4783 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4784 // TODO: Once this is better exercised by tests, it should be merged with 4785 // the normal path for loads to prevent future divergence. 4786 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4787 if (MemVT != VT) 4788 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4789 4790 setValue(&I, L); 4791 SDValue OutChain = L.getValue(1); 4792 if (!I.isUnordered()) 4793 DAG.setRoot(OutChain); 4794 else 4795 PendingLoads.push_back(OutChain); 4796 return; 4797 } 4798 4799 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4800 Ptr, MMO); 4801 4802 SDValue OutChain = L.getValue(1); 4803 if (MemVT != VT) 4804 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4805 4806 setValue(&I, L); 4807 DAG.setRoot(OutChain); 4808 } 4809 4810 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4811 SDLoc dl = getCurSDLoc(); 4812 4813 AtomicOrdering Ordering = I.getOrdering(); 4814 SyncScope::ID SSID = I.getSyncScopeID(); 4815 4816 SDValue InChain = getRoot(); 4817 4818 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4819 EVT MemVT = 4820 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4821 4822 if (!TLI.supportsUnalignedAtomics() && 4823 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4824 report_fatal_error("Cannot generate unaligned atomic store"); 4825 4826 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4827 4828 MachineFunction &MF = DAG.getMachineFunction(); 4829 MachineMemOperand *MMO = MF.getMachineMemOperand( 4830 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4831 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4832 4833 SDValue Val = getValue(I.getValueOperand()); 4834 if (Val.getValueType() != MemVT) 4835 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4836 SDValue Ptr = getValue(I.getPointerOperand()); 4837 4838 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4839 // TODO: Once this is better exercised by tests, it should be merged with 4840 // the normal path for stores to prevent future divergence. 4841 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4842 setValue(&I, S); 4843 DAG.setRoot(S); 4844 return; 4845 } 4846 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4847 Ptr, Val, MMO); 4848 4849 setValue(&I, OutChain); 4850 DAG.setRoot(OutChain); 4851 } 4852 4853 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4854 /// node. 4855 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4856 unsigned Intrinsic) { 4857 // Ignore the callsite's attributes. A specific call site may be marked with 4858 // readnone, but the lowering code will expect the chain based on the 4859 // definition. 4860 const Function *F = I.getCalledFunction(); 4861 bool HasChain = !F->doesNotAccessMemory(); 4862 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4863 4864 // Build the operand list. 4865 SmallVector<SDValue, 8> Ops; 4866 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4867 if (OnlyLoad) { 4868 // We don't need to serialize loads against other loads. 4869 Ops.push_back(DAG.getRoot()); 4870 } else { 4871 Ops.push_back(getRoot()); 4872 } 4873 } 4874 4875 // Info is set by getTgtMemIntrinsic 4876 TargetLowering::IntrinsicInfo Info; 4877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4878 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4879 DAG.getMachineFunction(), 4880 Intrinsic); 4881 4882 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4883 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4884 Info.opc == ISD::INTRINSIC_W_CHAIN) 4885 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4886 TLI.getPointerTy(DAG.getDataLayout()))); 4887 4888 // Add all operands of the call to the operand list. 4889 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4890 const Value *Arg = I.getArgOperand(i); 4891 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4892 Ops.push_back(getValue(Arg)); 4893 continue; 4894 } 4895 4896 // Use TargetConstant instead of a regular constant for immarg. 4897 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4898 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4899 assert(CI->getBitWidth() <= 64 && 4900 "large intrinsic immediates not handled"); 4901 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4902 } else { 4903 Ops.push_back( 4904 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4905 } 4906 } 4907 4908 SmallVector<EVT, 4> ValueVTs; 4909 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4910 4911 if (HasChain) 4912 ValueVTs.push_back(MVT::Other); 4913 4914 SDVTList VTs = DAG.getVTList(ValueVTs); 4915 4916 // Propagate fast-math-flags from IR to node(s). 4917 SDNodeFlags Flags; 4918 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4919 Flags.copyFMF(*FPMO); 4920 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4921 4922 // Create the node. 4923 SDValue Result; 4924 // In some cases, custom collection of operands from CallInst I may be needed. 4925 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4926 if (IsTgtIntrinsic) { 4927 // This is target intrinsic that touches memory 4928 // 4929 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4930 // didn't yield anything useful. 4931 MachinePointerInfo MPI; 4932 if (Info.ptrVal) 4933 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4934 else if (Info.fallbackAddressSpace) 4935 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4936 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4937 Info.memVT, MPI, Info.align, Info.flags, 4938 Info.size, I.getAAMetadata()); 4939 } else if (!HasChain) { 4940 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4941 } else if (!I.getType()->isVoidTy()) { 4942 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4943 } else { 4944 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4945 } 4946 4947 if (HasChain) { 4948 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4949 if (OnlyLoad) 4950 PendingLoads.push_back(Chain); 4951 else 4952 DAG.setRoot(Chain); 4953 } 4954 4955 if (!I.getType()->isVoidTy()) { 4956 if (!isa<VectorType>(I.getType())) 4957 Result = lowerRangeToAssertZExt(DAG, I, Result); 4958 4959 MaybeAlign Alignment = I.getRetAlign(); 4960 4961 // Insert `assertalign` node if there's an alignment. 4962 if (InsertAssertAlign && Alignment) { 4963 Result = 4964 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4965 } 4966 4967 setValue(&I, Result); 4968 } 4969 } 4970 4971 /// GetSignificand - Get the significand and build it into a floating-point 4972 /// number with exponent of 1: 4973 /// 4974 /// Op = (Op & 0x007fffff) | 0x3f800000; 4975 /// 4976 /// where Op is the hexadecimal representation of floating point value. 4977 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4978 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4979 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4980 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4981 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4982 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4983 } 4984 4985 /// GetExponent - Get the exponent: 4986 /// 4987 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4988 /// 4989 /// where Op is the hexadecimal representation of floating point value. 4990 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4991 const TargetLowering &TLI, const SDLoc &dl) { 4992 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4993 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4994 SDValue t1 = DAG.getNode( 4995 ISD::SRL, dl, MVT::i32, t0, 4996 DAG.getConstant(23, dl, 4997 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4998 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4999 DAG.getConstant(127, dl, MVT::i32)); 5000 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5001 } 5002 5003 /// getF32Constant - Get 32-bit floating point constant. 5004 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5005 const SDLoc &dl) { 5006 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5007 MVT::f32); 5008 } 5009 5010 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5011 SelectionDAG &DAG) { 5012 // TODO: What fast-math-flags should be set on the floating-point nodes? 5013 5014 // IntegerPartOfX = ((int32_t)(t0); 5015 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5016 5017 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5018 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5019 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5020 5021 // IntegerPartOfX <<= 23; 5022 IntegerPartOfX = 5023 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5024 DAG.getConstant(23, dl, 5025 DAG.getTargetLoweringInfo().getShiftAmountTy( 5026 MVT::i32, DAG.getDataLayout()))); 5027 5028 SDValue TwoToFractionalPartOfX; 5029 if (LimitFloatPrecision <= 6) { 5030 // For floating-point precision of 6: 5031 // 5032 // TwoToFractionalPartOfX = 5033 // 0.997535578f + 5034 // (0.735607626f + 0.252464424f * x) * x; 5035 // 5036 // error 0.0144103317, which is 6 bits 5037 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5038 getF32Constant(DAG, 0x3e814304, dl)); 5039 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5040 getF32Constant(DAG, 0x3f3c50c8, dl)); 5041 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5042 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5043 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5044 } else if (LimitFloatPrecision <= 12) { 5045 // For floating-point precision of 12: 5046 // 5047 // TwoToFractionalPartOfX = 5048 // 0.999892986f + 5049 // (0.696457318f + 5050 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5051 // 5052 // error 0.000107046256, which is 13 to 14 bits 5053 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5054 getF32Constant(DAG, 0x3da235e3, dl)); 5055 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5056 getF32Constant(DAG, 0x3e65b8f3, dl)); 5057 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5058 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5059 getF32Constant(DAG, 0x3f324b07, dl)); 5060 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5061 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5062 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5063 } else { // LimitFloatPrecision <= 18 5064 // For floating-point precision of 18: 5065 // 5066 // TwoToFractionalPartOfX = 5067 // 0.999999982f + 5068 // (0.693148872f + 5069 // (0.240227044f + 5070 // (0.554906021e-1f + 5071 // (0.961591928e-2f + 5072 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5073 // error 2.47208000*10^(-7), which is better than 18 bits 5074 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5075 getF32Constant(DAG, 0x3924b03e, dl)); 5076 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5077 getF32Constant(DAG, 0x3ab24b87, dl)); 5078 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5079 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5080 getF32Constant(DAG, 0x3c1d8c17, dl)); 5081 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5082 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5083 getF32Constant(DAG, 0x3d634a1d, dl)); 5084 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5085 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5086 getF32Constant(DAG, 0x3e75fe14, dl)); 5087 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5088 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5089 getF32Constant(DAG, 0x3f317234, dl)); 5090 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5091 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5092 getF32Constant(DAG, 0x3f800000, dl)); 5093 } 5094 5095 // Add the exponent into the result in integer domain. 5096 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5097 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5098 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5099 } 5100 5101 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5102 /// limited-precision mode. 5103 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5104 const TargetLowering &TLI, SDNodeFlags Flags) { 5105 if (Op.getValueType() == MVT::f32 && 5106 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5107 5108 // Put the exponent in the right bit position for later addition to the 5109 // final result: 5110 // 5111 // t0 = Op * log2(e) 5112 5113 // TODO: What fast-math-flags should be set here? 5114 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5115 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5116 return getLimitedPrecisionExp2(t0, dl, DAG); 5117 } 5118 5119 // No special expansion. 5120 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5121 } 5122 5123 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5124 /// limited-precision mode. 5125 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5126 const TargetLowering &TLI, SDNodeFlags Flags) { 5127 // TODO: What fast-math-flags should be set on the floating-point nodes? 5128 5129 if (Op.getValueType() == MVT::f32 && 5130 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5131 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5132 5133 // Scale the exponent by log(2). 5134 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5135 SDValue LogOfExponent = 5136 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5137 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5138 5139 // Get the significand and build it into a floating-point number with 5140 // exponent of 1. 5141 SDValue X = GetSignificand(DAG, Op1, dl); 5142 5143 SDValue LogOfMantissa; 5144 if (LimitFloatPrecision <= 6) { 5145 // For floating-point precision of 6: 5146 // 5147 // LogofMantissa = 5148 // -1.1609546f + 5149 // (1.4034025f - 0.23903021f * x) * x; 5150 // 5151 // error 0.0034276066, which is better than 8 bits 5152 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5153 getF32Constant(DAG, 0xbe74c456, dl)); 5154 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5155 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5156 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5157 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5158 getF32Constant(DAG, 0x3f949a29, dl)); 5159 } else if (LimitFloatPrecision <= 12) { 5160 // For floating-point precision of 12: 5161 // 5162 // LogOfMantissa = 5163 // -1.7417939f + 5164 // (2.8212026f + 5165 // (-1.4699568f + 5166 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5167 // 5168 // error 0.000061011436, which is 14 bits 5169 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5170 getF32Constant(DAG, 0xbd67b6d6, dl)); 5171 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5172 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5173 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5174 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5175 getF32Constant(DAG, 0x3fbc278b, dl)); 5176 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5177 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5178 getF32Constant(DAG, 0x40348e95, dl)); 5179 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5180 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5181 getF32Constant(DAG, 0x3fdef31a, dl)); 5182 } else { // LimitFloatPrecision <= 18 5183 // For floating-point precision of 18: 5184 // 5185 // LogOfMantissa = 5186 // -2.1072184f + 5187 // (4.2372794f + 5188 // (-3.7029485f + 5189 // (2.2781945f + 5190 // (-0.87823314f + 5191 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5192 // 5193 // error 0.0000023660568, which is better than 18 bits 5194 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5195 getF32Constant(DAG, 0xbc91e5ac, dl)); 5196 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5197 getF32Constant(DAG, 0x3e4350aa, dl)); 5198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5199 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5200 getF32Constant(DAG, 0x3f60d3e3, dl)); 5201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5203 getF32Constant(DAG, 0x4011cdf0, dl)); 5204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5205 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5206 getF32Constant(DAG, 0x406cfd1c, dl)); 5207 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5208 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5209 getF32Constant(DAG, 0x408797cb, dl)); 5210 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5211 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5212 getF32Constant(DAG, 0x4006dcab, dl)); 5213 } 5214 5215 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5216 } 5217 5218 // No special expansion. 5219 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5220 } 5221 5222 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5223 /// limited-precision mode. 5224 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5225 const TargetLowering &TLI, SDNodeFlags Flags) { 5226 // TODO: What fast-math-flags should be set on the floating-point nodes? 5227 5228 if (Op.getValueType() == MVT::f32 && 5229 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5230 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5231 5232 // Get the exponent. 5233 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5234 5235 // Get the significand and build it into a floating-point number with 5236 // exponent of 1. 5237 SDValue X = GetSignificand(DAG, Op1, dl); 5238 5239 // Different possible minimax approximations of significand in 5240 // floating-point for various degrees of accuracy over [1,2]. 5241 SDValue Log2ofMantissa; 5242 if (LimitFloatPrecision <= 6) { 5243 // For floating-point precision of 6: 5244 // 5245 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5246 // 5247 // error 0.0049451742, which is more than 7 bits 5248 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5249 getF32Constant(DAG, 0xbeb08fe0, dl)); 5250 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5251 getF32Constant(DAG, 0x40019463, dl)); 5252 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5253 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5254 getF32Constant(DAG, 0x3fd6633d, dl)); 5255 } else if (LimitFloatPrecision <= 12) { 5256 // For floating-point precision of 12: 5257 // 5258 // Log2ofMantissa = 5259 // -2.51285454f + 5260 // (4.07009056f + 5261 // (-2.12067489f + 5262 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5263 // 5264 // error 0.0000876136000, which is better than 13 bits 5265 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5266 getF32Constant(DAG, 0xbda7262e, dl)); 5267 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5268 getF32Constant(DAG, 0x3f25280b, dl)); 5269 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5270 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5271 getF32Constant(DAG, 0x4007b923, dl)); 5272 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5273 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5274 getF32Constant(DAG, 0x40823e2f, dl)); 5275 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5276 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5277 getF32Constant(DAG, 0x4020d29c, dl)); 5278 } else { // LimitFloatPrecision <= 18 5279 // For floating-point precision of 18: 5280 // 5281 // Log2ofMantissa = 5282 // -3.0400495f + 5283 // (6.1129976f + 5284 // (-5.3420409f + 5285 // (3.2865683f + 5286 // (-1.2669343f + 5287 // (0.27515199f - 5288 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5289 // 5290 // error 0.0000018516, which is better than 18 bits 5291 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5292 getF32Constant(DAG, 0xbcd2769e, dl)); 5293 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5294 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5295 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5296 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5297 getF32Constant(DAG, 0x3fa22ae7, dl)); 5298 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5299 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5300 getF32Constant(DAG, 0x40525723, dl)); 5301 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5302 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5303 getF32Constant(DAG, 0x40aaf200, dl)); 5304 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5305 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5306 getF32Constant(DAG, 0x40c39dad, dl)); 5307 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5308 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5309 getF32Constant(DAG, 0x4042902c, dl)); 5310 } 5311 5312 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5313 } 5314 5315 // No special expansion. 5316 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5317 } 5318 5319 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5320 /// limited-precision mode. 5321 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5322 const TargetLowering &TLI, SDNodeFlags Flags) { 5323 // TODO: What fast-math-flags should be set on the floating-point nodes? 5324 5325 if (Op.getValueType() == MVT::f32 && 5326 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5327 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5328 5329 // Scale the exponent by log10(2) [0.30102999f]. 5330 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5331 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5332 getF32Constant(DAG, 0x3e9a209a, dl)); 5333 5334 // Get the significand and build it into a floating-point number with 5335 // exponent of 1. 5336 SDValue X = GetSignificand(DAG, Op1, dl); 5337 5338 SDValue Log10ofMantissa; 5339 if (LimitFloatPrecision <= 6) { 5340 // For floating-point precision of 6: 5341 // 5342 // Log10ofMantissa = 5343 // -0.50419619f + 5344 // (0.60948995f - 0.10380950f * x) * x; 5345 // 5346 // error 0.0014886165, which is 6 bits 5347 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5348 getF32Constant(DAG, 0xbdd49a13, dl)); 5349 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5350 getF32Constant(DAG, 0x3f1c0789, dl)); 5351 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5352 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5353 getF32Constant(DAG, 0x3f011300, dl)); 5354 } else if (LimitFloatPrecision <= 12) { 5355 // For floating-point precision of 12: 5356 // 5357 // Log10ofMantissa = 5358 // -0.64831180f + 5359 // (0.91751397f + 5360 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5361 // 5362 // error 0.00019228036, which is better than 12 bits 5363 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5364 getF32Constant(DAG, 0x3d431f31, dl)); 5365 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5366 getF32Constant(DAG, 0x3ea21fb2, dl)); 5367 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5368 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5369 getF32Constant(DAG, 0x3f6ae232, dl)); 5370 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5371 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5372 getF32Constant(DAG, 0x3f25f7c3, dl)); 5373 } else { // LimitFloatPrecision <= 18 5374 // For floating-point precision of 18: 5375 // 5376 // Log10ofMantissa = 5377 // -0.84299375f + 5378 // (1.5327582f + 5379 // (-1.0688956f + 5380 // (0.49102474f + 5381 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5382 // 5383 // error 0.0000037995730, which is better than 18 bits 5384 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5385 getF32Constant(DAG, 0x3c5d51ce, dl)); 5386 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5387 getF32Constant(DAG, 0x3e00685a, dl)); 5388 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5389 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5390 getF32Constant(DAG, 0x3efb6798, dl)); 5391 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5392 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5393 getF32Constant(DAG, 0x3f88d192, dl)); 5394 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5395 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5396 getF32Constant(DAG, 0x3fc4316c, dl)); 5397 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5398 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5399 getF32Constant(DAG, 0x3f57ce70, dl)); 5400 } 5401 5402 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5403 } 5404 5405 // No special expansion. 5406 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5407 } 5408 5409 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5410 /// limited-precision mode. 5411 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5412 const TargetLowering &TLI, SDNodeFlags Flags) { 5413 if (Op.getValueType() == MVT::f32 && 5414 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5415 return getLimitedPrecisionExp2(Op, dl, DAG); 5416 5417 // No special expansion. 5418 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5419 } 5420 5421 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5422 /// limited-precision mode with x == 10.0f. 5423 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5424 SelectionDAG &DAG, const TargetLowering &TLI, 5425 SDNodeFlags Flags) { 5426 bool IsExp10 = false; 5427 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5428 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5429 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5430 APFloat Ten(10.0f); 5431 IsExp10 = LHSC->isExactlyValue(Ten); 5432 } 5433 } 5434 5435 // TODO: What fast-math-flags should be set on the FMUL node? 5436 if (IsExp10) { 5437 // Put the exponent in the right bit position for later addition to the 5438 // final result: 5439 // 5440 // #define LOG2OF10 3.3219281f 5441 // t0 = Op * LOG2OF10; 5442 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5443 getF32Constant(DAG, 0x40549a78, dl)); 5444 return getLimitedPrecisionExp2(t0, dl, DAG); 5445 } 5446 5447 // No special expansion. 5448 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5449 } 5450 5451 /// ExpandPowI - Expand a llvm.powi intrinsic. 5452 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5453 SelectionDAG &DAG) { 5454 // If RHS is a constant, we can expand this out to a multiplication tree if 5455 // it's beneficial on the target, otherwise we end up lowering to a call to 5456 // __powidf2 (for example). 5457 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5458 unsigned Val = RHSC->getSExtValue(); 5459 5460 // powi(x, 0) -> 1.0 5461 if (Val == 0) 5462 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5463 5464 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5465 Val, DAG.shouldOptForSize())) { 5466 // Get the exponent as a positive value. 5467 if ((int)Val < 0) 5468 Val = -Val; 5469 // We use the simple binary decomposition method to generate the multiply 5470 // sequence. There are more optimal ways to do this (for example, 5471 // powi(x,15) generates one more multiply than it should), but this has 5472 // the benefit of being both really simple and much better than a libcall. 5473 SDValue Res; // Logically starts equal to 1.0 5474 SDValue CurSquare = LHS; 5475 // TODO: Intrinsics should have fast-math-flags that propagate to these 5476 // nodes. 5477 while (Val) { 5478 if (Val & 1) { 5479 if (Res.getNode()) 5480 Res = 5481 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5482 else 5483 Res = CurSquare; // 1.0*CurSquare. 5484 } 5485 5486 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5487 CurSquare, CurSquare); 5488 Val >>= 1; 5489 } 5490 5491 // If the original was negative, invert the result, producing 1/(x*x*x). 5492 if (RHSC->getSExtValue() < 0) 5493 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5494 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5495 return Res; 5496 } 5497 } 5498 5499 // Otherwise, expand to a libcall. 5500 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5501 } 5502 5503 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5504 SDValue LHS, SDValue RHS, SDValue Scale, 5505 SelectionDAG &DAG, const TargetLowering &TLI) { 5506 EVT VT = LHS.getValueType(); 5507 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5508 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5509 LLVMContext &Ctx = *DAG.getContext(); 5510 5511 // If the type is legal but the operation isn't, this node might survive all 5512 // the way to operation legalization. If we end up there and we do not have 5513 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5514 // node. 5515 5516 // Coax the legalizer into expanding the node during type legalization instead 5517 // by bumping the size by one bit. This will force it to Promote, enabling the 5518 // early expansion and avoiding the need to expand later. 5519 5520 // We don't have to do this if Scale is 0; that can always be expanded, unless 5521 // it's a saturating signed operation. Those can experience true integer 5522 // division overflow, a case which we must avoid. 5523 5524 // FIXME: We wouldn't have to do this (or any of the early 5525 // expansion/promotion) if it was possible to expand a libcall of an 5526 // illegal type during operation legalization. But it's not, so things 5527 // get a bit hacky. 5528 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5529 if ((ScaleInt > 0 || (Saturating && Signed)) && 5530 (TLI.isTypeLegal(VT) || 5531 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5532 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5533 Opcode, VT, ScaleInt); 5534 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5535 EVT PromVT; 5536 if (VT.isScalarInteger()) 5537 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5538 else if (VT.isVector()) { 5539 PromVT = VT.getVectorElementType(); 5540 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5541 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5542 } else 5543 llvm_unreachable("Wrong VT for DIVFIX?"); 5544 if (Signed) { 5545 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5546 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5547 } else { 5548 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5549 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5550 } 5551 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5552 // For saturating operations, we need to shift up the LHS to get the 5553 // proper saturation width, and then shift down again afterwards. 5554 if (Saturating) 5555 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5556 DAG.getConstant(1, DL, ShiftTy)); 5557 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5558 if (Saturating) 5559 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5560 DAG.getConstant(1, DL, ShiftTy)); 5561 return DAG.getZExtOrTrunc(Res, DL, VT); 5562 } 5563 } 5564 5565 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5566 } 5567 5568 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5569 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5570 static void 5571 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5572 const SDValue &N) { 5573 switch (N.getOpcode()) { 5574 case ISD::CopyFromReg: { 5575 SDValue Op = N.getOperand(1); 5576 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5577 Op.getValueType().getSizeInBits()); 5578 return; 5579 } 5580 case ISD::BITCAST: 5581 case ISD::AssertZext: 5582 case ISD::AssertSext: 5583 case ISD::TRUNCATE: 5584 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5585 return; 5586 case ISD::BUILD_PAIR: 5587 case ISD::BUILD_VECTOR: 5588 case ISD::CONCAT_VECTORS: 5589 for (SDValue Op : N->op_values()) 5590 getUnderlyingArgRegs(Regs, Op); 5591 return; 5592 default: 5593 return; 5594 } 5595 } 5596 5597 /// If the DbgValueInst is a dbg_value of a function argument, create the 5598 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5599 /// instruction selection, they will be inserted to the entry BB. 5600 /// We don't currently support this for variadic dbg_values, as they shouldn't 5601 /// appear for function arguments or in the prologue. 5602 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5603 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5604 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5605 const Argument *Arg = dyn_cast<Argument>(V); 5606 if (!Arg) 5607 return false; 5608 5609 MachineFunction &MF = DAG.getMachineFunction(); 5610 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5611 5612 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5613 // we've been asked to pursue. 5614 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5615 bool Indirect) { 5616 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5617 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5618 // pointing at the VReg, which will be patched up later. 5619 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5620 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5621 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5622 /* isKill */ false, /* isDead */ false, 5623 /* isUndef */ false, /* isEarlyClobber */ false, 5624 /* SubReg */ 0, /* isDebug */ true)}); 5625 5626 auto *NewDIExpr = FragExpr; 5627 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5628 // the DIExpression. 5629 if (Indirect) 5630 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5631 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5632 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5633 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5634 } else { 5635 // Create a completely standard DBG_VALUE. 5636 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5637 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5638 } 5639 }; 5640 5641 if (Kind == FuncArgumentDbgValueKind::Value) { 5642 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5643 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5644 // the entry block. 5645 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5646 if (!IsInEntryBlock) 5647 return false; 5648 5649 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5650 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5651 // variable that also is a param. 5652 // 5653 // Although, if we are at the top of the entry block already, we can still 5654 // emit using ArgDbgValue. This might catch some situations when the 5655 // dbg.value refers to an argument that isn't used in the entry block, so 5656 // any CopyToReg node would be optimized out and the only way to express 5657 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5658 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5659 // we should only emit as ArgDbgValue if the Variable is an argument to the 5660 // current function, and the dbg.value intrinsic is found in the entry 5661 // block. 5662 bool VariableIsFunctionInputArg = Variable->isParameter() && 5663 !DL->getInlinedAt(); 5664 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5665 if (!IsInPrologue && !VariableIsFunctionInputArg) 5666 return false; 5667 5668 // Here we assume that a function argument on IR level only can be used to 5669 // describe one input parameter on source level. If we for example have 5670 // source code like this 5671 // 5672 // struct A { long x, y; }; 5673 // void foo(struct A a, long b) { 5674 // ... 5675 // b = a.x; 5676 // ... 5677 // } 5678 // 5679 // and IR like this 5680 // 5681 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5682 // entry: 5683 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5684 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5685 // call void @llvm.dbg.value(metadata i32 %b, "b", 5686 // ... 5687 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5688 // ... 5689 // 5690 // then the last dbg.value is describing a parameter "b" using a value that 5691 // is an argument. But since we already has used %a1 to describe a parameter 5692 // we should not handle that last dbg.value here (that would result in an 5693 // incorrect hoisting of the DBG_VALUE to the function entry). 5694 // Notice that we allow one dbg.value per IR level argument, to accommodate 5695 // for the situation with fragments above. 5696 if (VariableIsFunctionInputArg) { 5697 unsigned ArgNo = Arg->getArgNo(); 5698 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5699 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5700 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5701 return false; 5702 FuncInfo.DescribedArgs.set(ArgNo); 5703 } 5704 } 5705 5706 bool IsIndirect = false; 5707 std::optional<MachineOperand> Op; 5708 // Some arguments' frame index is recorded during argument lowering. 5709 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5710 if (FI != std::numeric_limits<int>::max()) 5711 Op = MachineOperand::CreateFI(FI); 5712 5713 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5714 if (!Op && N.getNode()) { 5715 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5716 Register Reg; 5717 if (ArgRegsAndSizes.size() == 1) 5718 Reg = ArgRegsAndSizes.front().first; 5719 5720 if (Reg && Reg.isVirtual()) { 5721 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5722 Register PR = RegInfo.getLiveInPhysReg(Reg); 5723 if (PR) 5724 Reg = PR; 5725 } 5726 if (Reg) { 5727 Op = MachineOperand::CreateReg(Reg, false); 5728 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5729 } 5730 } 5731 5732 if (!Op && N.getNode()) { 5733 // Check if frame index is available. 5734 SDValue LCandidate = peekThroughBitcasts(N); 5735 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5736 if (FrameIndexSDNode *FINode = 5737 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5738 Op = MachineOperand::CreateFI(FINode->getIndex()); 5739 } 5740 5741 if (!Op) { 5742 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5743 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5744 SplitRegs) { 5745 unsigned Offset = 0; 5746 for (const auto &RegAndSize : SplitRegs) { 5747 // If the expression is already a fragment, the current register 5748 // offset+size might extend beyond the fragment. In this case, only 5749 // the register bits that are inside the fragment are relevant. 5750 int RegFragmentSizeInBits = RegAndSize.second; 5751 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5752 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5753 // The register is entirely outside the expression fragment, 5754 // so is irrelevant for debug info. 5755 if (Offset >= ExprFragmentSizeInBits) 5756 break; 5757 // The register is partially outside the expression fragment, only 5758 // the low bits within the fragment are relevant for debug info. 5759 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5760 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5761 } 5762 } 5763 5764 auto FragmentExpr = DIExpression::createFragmentExpression( 5765 Expr, Offset, RegFragmentSizeInBits); 5766 Offset += RegAndSize.second; 5767 // If a valid fragment expression cannot be created, the variable's 5768 // correct value cannot be determined and so it is set as Undef. 5769 if (!FragmentExpr) { 5770 SDDbgValue *SDV = DAG.getConstantDbgValue( 5771 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5772 DAG.AddDbgValue(SDV, false); 5773 continue; 5774 } 5775 MachineInstr *NewMI = 5776 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5777 Kind != FuncArgumentDbgValueKind::Value); 5778 FuncInfo.ArgDbgValues.push_back(NewMI); 5779 } 5780 }; 5781 5782 // Check if ValueMap has reg number. 5783 DenseMap<const Value *, Register>::const_iterator 5784 VMI = FuncInfo.ValueMap.find(V); 5785 if (VMI != FuncInfo.ValueMap.end()) { 5786 const auto &TLI = DAG.getTargetLoweringInfo(); 5787 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5788 V->getType(), std::nullopt); 5789 if (RFV.occupiesMultipleRegs()) { 5790 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5791 return true; 5792 } 5793 5794 Op = MachineOperand::CreateReg(VMI->second, false); 5795 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5796 } else if (ArgRegsAndSizes.size() > 1) { 5797 // This was split due to the calling convention, and no virtual register 5798 // mapping exists for the value. 5799 splitMultiRegDbgValue(ArgRegsAndSizes); 5800 return true; 5801 } 5802 } 5803 5804 if (!Op) 5805 return false; 5806 5807 // If the expression refers to the entry value of an Argument, use the 5808 // corresponding livein physical register. As per the Verifier, this is only 5809 // allowed for swiftasync Arguments. 5810 if (Op->isReg() && Expr->isEntryValue()) { 5811 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 5812 auto OpReg = Op->getReg(); 5813 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 5814 if (OpReg == VirtReg || OpReg == PhysReg) { 5815 SDDbgValue *SDV = DAG.getVRegDbgValue( 5816 Variable, Expr, PhysReg, 5817 Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL, 5818 SDNodeOrder); 5819 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 5820 return true; 5821 } 5822 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 5823 "couldn't find a physical register\n"); 5824 return true; 5825 } 5826 5827 assert(Variable->isValidLocationForIntrinsic(DL) && 5828 "Expected inlined-at fields to agree"); 5829 MachineInstr *NewMI = nullptr; 5830 5831 if (Op->isReg()) 5832 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5833 else 5834 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5835 Variable, Expr); 5836 5837 // Otherwise, use ArgDbgValues. 5838 FuncInfo.ArgDbgValues.push_back(NewMI); 5839 return true; 5840 } 5841 5842 /// Return the appropriate SDDbgValue based on N. 5843 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5844 DILocalVariable *Variable, 5845 DIExpression *Expr, 5846 const DebugLoc &dl, 5847 unsigned DbgSDNodeOrder) { 5848 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5849 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5850 // stack slot locations. 5851 // 5852 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5853 // debug values here after optimization: 5854 // 5855 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5856 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5857 // 5858 // Both describe the direct values of their associated variables. 5859 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5860 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5861 } 5862 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5863 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5864 } 5865 5866 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5867 switch (Intrinsic) { 5868 case Intrinsic::smul_fix: 5869 return ISD::SMULFIX; 5870 case Intrinsic::umul_fix: 5871 return ISD::UMULFIX; 5872 case Intrinsic::smul_fix_sat: 5873 return ISD::SMULFIXSAT; 5874 case Intrinsic::umul_fix_sat: 5875 return ISD::UMULFIXSAT; 5876 case Intrinsic::sdiv_fix: 5877 return ISD::SDIVFIX; 5878 case Intrinsic::udiv_fix: 5879 return ISD::UDIVFIX; 5880 case Intrinsic::sdiv_fix_sat: 5881 return ISD::SDIVFIXSAT; 5882 case Intrinsic::udiv_fix_sat: 5883 return ISD::UDIVFIXSAT; 5884 default: 5885 llvm_unreachable("Unhandled fixed point intrinsic"); 5886 } 5887 } 5888 5889 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5890 const char *FunctionName) { 5891 assert(FunctionName && "FunctionName must not be nullptr"); 5892 SDValue Callee = DAG.getExternalSymbol( 5893 FunctionName, 5894 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5895 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5896 } 5897 5898 /// Given a @llvm.call.preallocated.setup, return the corresponding 5899 /// preallocated call. 5900 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5901 assert(cast<CallBase>(PreallocatedSetup) 5902 ->getCalledFunction() 5903 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5904 "expected call_preallocated_setup Value"); 5905 for (const auto *U : PreallocatedSetup->users()) { 5906 auto *UseCall = cast<CallBase>(U); 5907 const Function *Fn = UseCall->getCalledFunction(); 5908 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5909 return UseCall; 5910 } 5911 } 5912 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5913 } 5914 5915 /// Lower the call to the specified intrinsic function. 5916 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5917 unsigned Intrinsic) { 5918 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5919 SDLoc sdl = getCurSDLoc(); 5920 DebugLoc dl = getCurDebugLoc(); 5921 SDValue Res; 5922 5923 SDNodeFlags Flags; 5924 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5925 Flags.copyFMF(*FPOp); 5926 5927 switch (Intrinsic) { 5928 default: 5929 // By default, turn this into a target intrinsic node. 5930 visitTargetIntrinsic(I, Intrinsic); 5931 return; 5932 case Intrinsic::vscale: { 5933 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5934 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5935 return; 5936 } 5937 case Intrinsic::vastart: visitVAStart(I); return; 5938 case Intrinsic::vaend: visitVAEnd(I); return; 5939 case Intrinsic::vacopy: visitVACopy(I); return; 5940 case Intrinsic::returnaddress: 5941 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5942 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5943 getValue(I.getArgOperand(0)))); 5944 return; 5945 case Intrinsic::addressofreturnaddress: 5946 setValue(&I, 5947 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5948 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5949 return; 5950 case Intrinsic::sponentry: 5951 setValue(&I, 5952 DAG.getNode(ISD::SPONENTRY, sdl, 5953 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5954 return; 5955 case Intrinsic::frameaddress: 5956 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5957 TLI.getFrameIndexTy(DAG.getDataLayout()), 5958 getValue(I.getArgOperand(0)))); 5959 return; 5960 case Intrinsic::read_volatile_register: 5961 case Intrinsic::read_register: { 5962 Value *Reg = I.getArgOperand(0); 5963 SDValue Chain = getRoot(); 5964 SDValue RegName = 5965 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5966 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5967 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5968 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5969 setValue(&I, Res); 5970 DAG.setRoot(Res.getValue(1)); 5971 return; 5972 } 5973 case Intrinsic::write_register: { 5974 Value *Reg = I.getArgOperand(0); 5975 Value *RegValue = I.getArgOperand(1); 5976 SDValue Chain = getRoot(); 5977 SDValue RegName = 5978 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5979 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5980 RegName, getValue(RegValue))); 5981 return; 5982 } 5983 case Intrinsic::memcpy: { 5984 const auto &MCI = cast<MemCpyInst>(I); 5985 SDValue Op1 = getValue(I.getArgOperand(0)); 5986 SDValue Op2 = getValue(I.getArgOperand(1)); 5987 SDValue Op3 = getValue(I.getArgOperand(2)); 5988 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5989 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5990 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5991 Align Alignment = std::min(DstAlign, SrcAlign); 5992 bool isVol = MCI.isVolatile(); 5993 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5994 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5995 // node. 5996 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5997 SDValue MC = DAG.getMemcpy( 5998 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5999 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6000 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6001 updateDAGForMaybeTailCall(MC); 6002 return; 6003 } 6004 case Intrinsic::memcpy_inline: { 6005 const auto &MCI = cast<MemCpyInlineInst>(I); 6006 SDValue Dst = getValue(I.getArgOperand(0)); 6007 SDValue Src = getValue(I.getArgOperand(1)); 6008 SDValue Size = getValue(I.getArgOperand(2)); 6009 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6010 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6011 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6012 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6013 Align Alignment = std::min(DstAlign, SrcAlign); 6014 bool isVol = MCI.isVolatile(); 6015 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6016 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6017 // node. 6018 SDValue MC = DAG.getMemcpy( 6019 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6020 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6021 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6022 updateDAGForMaybeTailCall(MC); 6023 return; 6024 } 6025 case Intrinsic::memset: { 6026 const auto &MSI = cast<MemSetInst>(I); 6027 SDValue Op1 = getValue(I.getArgOperand(0)); 6028 SDValue Op2 = getValue(I.getArgOperand(1)); 6029 SDValue Op3 = getValue(I.getArgOperand(2)); 6030 // @llvm.memset defines 0 and 1 to both mean no alignment. 6031 Align Alignment = MSI.getDestAlign().valueOrOne(); 6032 bool isVol = MSI.isVolatile(); 6033 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6034 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6035 SDValue MS = DAG.getMemset( 6036 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6037 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6038 updateDAGForMaybeTailCall(MS); 6039 return; 6040 } 6041 case Intrinsic::memset_inline: { 6042 const auto &MSII = cast<MemSetInlineInst>(I); 6043 SDValue Dst = getValue(I.getArgOperand(0)); 6044 SDValue Value = getValue(I.getArgOperand(1)); 6045 SDValue Size = getValue(I.getArgOperand(2)); 6046 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6047 // @llvm.memset defines 0 and 1 to both mean no alignment. 6048 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6049 bool isVol = MSII.isVolatile(); 6050 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6051 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6052 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6053 /* AlwaysInline */ true, isTC, 6054 MachinePointerInfo(I.getArgOperand(0)), 6055 I.getAAMetadata()); 6056 updateDAGForMaybeTailCall(MC); 6057 return; 6058 } 6059 case Intrinsic::memmove: { 6060 const auto &MMI = cast<MemMoveInst>(I); 6061 SDValue Op1 = getValue(I.getArgOperand(0)); 6062 SDValue Op2 = getValue(I.getArgOperand(1)); 6063 SDValue Op3 = getValue(I.getArgOperand(2)); 6064 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6065 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6066 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6067 Align Alignment = std::min(DstAlign, SrcAlign); 6068 bool isVol = MMI.isVolatile(); 6069 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6070 // FIXME: Support passing different dest/src alignments to the memmove DAG 6071 // node. 6072 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6073 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6074 isTC, MachinePointerInfo(I.getArgOperand(0)), 6075 MachinePointerInfo(I.getArgOperand(1)), 6076 I.getAAMetadata(), AA); 6077 updateDAGForMaybeTailCall(MM); 6078 return; 6079 } 6080 case Intrinsic::memcpy_element_unordered_atomic: { 6081 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6082 SDValue Dst = getValue(MI.getRawDest()); 6083 SDValue Src = getValue(MI.getRawSource()); 6084 SDValue Length = getValue(MI.getLength()); 6085 6086 Type *LengthTy = MI.getLength()->getType(); 6087 unsigned ElemSz = MI.getElementSizeInBytes(); 6088 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6089 SDValue MC = 6090 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6091 isTC, MachinePointerInfo(MI.getRawDest()), 6092 MachinePointerInfo(MI.getRawSource())); 6093 updateDAGForMaybeTailCall(MC); 6094 return; 6095 } 6096 case Intrinsic::memmove_element_unordered_atomic: { 6097 auto &MI = cast<AtomicMemMoveInst>(I); 6098 SDValue Dst = getValue(MI.getRawDest()); 6099 SDValue Src = getValue(MI.getRawSource()); 6100 SDValue Length = getValue(MI.getLength()); 6101 6102 Type *LengthTy = MI.getLength()->getType(); 6103 unsigned ElemSz = MI.getElementSizeInBytes(); 6104 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6105 SDValue MC = 6106 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6107 isTC, MachinePointerInfo(MI.getRawDest()), 6108 MachinePointerInfo(MI.getRawSource())); 6109 updateDAGForMaybeTailCall(MC); 6110 return; 6111 } 6112 case Intrinsic::memset_element_unordered_atomic: { 6113 auto &MI = cast<AtomicMemSetInst>(I); 6114 SDValue Dst = getValue(MI.getRawDest()); 6115 SDValue Val = getValue(MI.getValue()); 6116 SDValue Length = getValue(MI.getLength()); 6117 6118 Type *LengthTy = MI.getLength()->getType(); 6119 unsigned ElemSz = MI.getElementSizeInBytes(); 6120 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6121 SDValue MC = 6122 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6123 isTC, MachinePointerInfo(MI.getRawDest())); 6124 updateDAGForMaybeTailCall(MC); 6125 return; 6126 } 6127 case Intrinsic::call_preallocated_setup: { 6128 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6129 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6130 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6131 getRoot(), SrcValue); 6132 setValue(&I, Res); 6133 DAG.setRoot(Res); 6134 return; 6135 } 6136 case Intrinsic::call_preallocated_arg: { 6137 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6138 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6139 SDValue Ops[3]; 6140 Ops[0] = getRoot(); 6141 Ops[1] = SrcValue; 6142 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6143 MVT::i32); // arg index 6144 SDValue Res = DAG.getNode( 6145 ISD::PREALLOCATED_ARG, sdl, 6146 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6147 setValue(&I, Res); 6148 DAG.setRoot(Res.getValue(1)); 6149 return; 6150 } 6151 case Intrinsic::dbg_declare: { 6152 const auto &DI = cast<DbgDeclareInst>(I); 6153 // Debug intrinsics are handled separately in assignment tracking mode. 6154 // Some intrinsics are handled right after Argument lowering. 6155 if (AssignmentTrackingEnabled || 6156 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6157 return; 6158 // Assume dbg.declare can not currently use DIArgList, i.e. 6159 // it is non-variadic. 6160 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6161 DILocalVariable *Variable = DI.getVariable(); 6162 DIExpression *Expression = DI.getExpression(); 6163 dropDanglingDebugInfo(Variable, Expression); 6164 assert(Variable && "Missing variable"); 6165 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6166 << "\n"); 6167 // Check if address has undef value. 6168 const Value *Address = DI.getVariableLocationOp(0); 6169 if (!Address || isa<UndefValue>(Address) || 6170 (Address->use_empty() && !isa<Argument>(Address))) { 6171 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6172 << " (bad/undef/unused-arg address)\n"); 6173 return; 6174 } 6175 6176 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6177 6178 SDValue &N = NodeMap[Address]; 6179 if (!N.getNode() && isa<Argument>(Address)) 6180 // Check unused arguments map. 6181 N = UnusedArgNodeMap[Address]; 6182 SDDbgValue *SDV; 6183 if (N.getNode()) { 6184 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6185 Address = BCI->getOperand(0); 6186 // Parameters are handled specially. 6187 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6188 if (isParameter && FINode) { 6189 // Byval parameter. We have a frame index at this point. 6190 SDV = 6191 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6192 /*IsIndirect*/ true, dl, SDNodeOrder); 6193 } else if (isa<Argument>(Address)) { 6194 // Address is an argument, so try to emit its dbg value using 6195 // virtual register info from the FuncInfo.ValueMap. 6196 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6197 FuncArgumentDbgValueKind::Declare, N); 6198 return; 6199 } else { 6200 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6201 true, dl, SDNodeOrder); 6202 } 6203 DAG.AddDbgValue(SDV, isParameter); 6204 } else { 6205 // If Address is an argument then try to emit its dbg value using 6206 // virtual register info from the FuncInfo.ValueMap. 6207 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6208 FuncArgumentDbgValueKind::Declare, N)) { 6209 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6210 << " (could not emit func-arg dbg_value)\n"); 6211 } 6212 } 6213 return; 6214 } 6215 case Intrinsic::dbg_label: { 6216 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6217 DILabel *Label = DI.getLabel(); 6218 assert(Label && "Missing label"); 6219 6220 SDDbgLabel *SDV; 6221 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6222 DAG.AddDbgLabel(SDV); 6223 return; 6224 } 6225 case Intrinsic::dbg_assign: { 6226 // Debug intrinsics are handled seperately in assignment tracking mode. 6227 if (AssignmentTrackingEnabled) 6228 return; 6229 // If assignment tracking hasn't been enabled then fall through and treat 6230 // the dbg.assign as a dbg.value. 6231 [[fallthrough]]; 6232 } 6233 case Intrinsic::dbg_value: { 6234 // Debug intrinsics are handled seperately in assignment tracking mode. 6235 if (AssignmentTrackingEnabled) 6236 return; 6237 const DbgValueInst &DI = cast<DbgValueInst>(I); 6238 assert(DI.getVariable() && "Missing variable"); 6239 6240 DILocalVariable *Variable = DI.getVariable(); 6241 DIExpression *Expression = DI.getExpression(); 6242 dropDanglingDebugInfo(Variable, Expression); 6243 6244 if (DI.isKillLocation()) { 6245 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6246 return; 6247 } 6248 6249 SmallVector<Value *, 4> Values(DI.getValues()); 6250 if (Values.empty()) 6251 return; 6252 6253 bool IsVariadic = DI.hasArgList(); 6254 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6255 SDNodeOrder, IsVariadic)) 6256 addDanglingDebugInfo(&DI, SDNodeOrder); 6257 return; 6258 } 6259 6260 case Intrinsic::eh_typeid_for: { 6261 // Find the type id for the given typeinfo. 6262 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6263 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6264 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6265 setValue(&I, Res); 6266 return; 6267 } 6268 6269 case Intrinsic::eh_return_i32: 6270 case Intrinsic::eh_return_i64: 6271 DAG.getMachineFunction().setCallsEHReturn(true); 6272 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6273 MVT::Other, 6274 getControlRoot(), 6275 getValue(I.getArgOperand(0)), 6276 getValue(I.getArgOperand(1)))); 6277 return; 6278 case Intrinsic::eh_unwind_init: 6279 DAG.getMachineFunction().setCallsUnwindInit(true); 6280 return; 6281 case Intrinsic::eh_dwarf_cfa: 6282 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6283 TLI.getPointerTy(DAG.getDataLayout()), 6284 getValue(I.getArgOperand(0)))); 6285 return; 6286 case Intrinsic::eh_sjlj_callsite: { 6287 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6288 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6289 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6290 6291 MMI.setCurrentCallSite(CI->getZExtValue()); 6292 return; 6293 } 6294 case Intrinsic::eh_sjlj_functioncontext: { 6295 // Get and store the index of the function context. 6296 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6297 AllocaInst *FnCtx = 6298 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6299 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6300 MFI.setFunctionContextIndex(FI); 6301 return; 6302 } 6303 case Intrinsic::eh_sjlj_setjmp: { 6304 SDValue Ops[2]; 6305 Ops[0] = getRoot(); 6306 Ops[1] = getValue(I.getArgOperand(0)); 6307 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6308 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6309 setValue(&I, Op.getValue(0)); 6310 DAG.setRoot(Op.getValue(1)); 6311 return; 6312 } 6313 case Intrinsic::eh_sjlj_longjmp: 6314 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6315 getRoot(), getValue(I.getArgOperand(0)))); 6316 return; 6317 case Intrinsic::eh_sjlj_setup_dispatch: 6318 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6319 getRoot())); 6320 return; 6321 case Intrinsic::masked_gather: 6322 visitMaskedGather(I); 6323 return; 6324 case Intrinsic::masked_load: 6325 visitMaskedLoad(I); 6326 return; 6327 case Intrinsic::masked_scatter: 6328 visitMaskedScatter(I); 6329 return; 6330 case Intrinsic::masked_store: 6331 visitMaskedStore(I); 6332 return; 6333 case Intrinsic::masked_expandload: 6334 visitMaskedLoad(I, true /* IsExpanding */); 6335 return; 6336 case Intrinsic::masked_compressstore: 6337 visitMaskedStore(I, true /* IsCompressing */); 6338 return; 6339 case Intrinsic::powi: 6340 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6341 getValue(I.getArgOperand(1)), DAG)); 6342 return; 6343 case Intrinsic::log: 6344 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6345 return; 6346 case Intrinsic::log2: 6347 setValue(&I, 6348 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6349 return; 6350 case Intrinsic::log10: 6351 setValue(&I, 6352 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6353 return; 6354 case Intrinsic::exp: 6355 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6356 return; 6357 case Intrinsic::exp2: 6358 setValue(&I, 6359 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6360 return; 6361 case Intrinsic::pow: 6362 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6363 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6364 return; 6365 case Intrinsic::sqrt: 6366 case Intrinsic::fabs: 6367 case Intrinsic::sin: 6368 case Intrinsic::cos: 6369 case Intrinsic::floor: 6370 case Intrinsic::ceil: 6371 case Intrinsic::trunc: 6372 case Intrinsic::rint: 6373 case Intrinsic::nearbyint: 6374 case Intrinsic::round: 6375 case Intrinsic::roundeven: 6376 case Intrinsic::canonicalize: { 6377 unsigned Opcode; 6378 switch (Intrinsic) { 6379 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6380 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6381 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6382 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6383 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6384 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6385 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6386 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6387 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6388 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6389 case Intrinsic::round: Opcode = ISD::FROUND; break; 6390 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6391 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6392 } 6393 6394 setValue(&I, DAG.getNode(Opcode, sdl, 6395 getValue(I.getArgOperand(0)).getValueType(), 6396 getValue(I.getArgOperand(0)), Flags)); 6397 return; 6398 } 6399 case Intrinsic::lround: 6400 case Intrinsic::llround: 6401 case Intrinsic::lrint: 6402 case Intrinsic::llrint: { 6403 unsigned Opcode; 6404 switch (Intrinsic) { 6405 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6406 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6407 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6408 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6409 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6410 } 6411 6412 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6413 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6414 getValue(I.getArgOperand(0)))); 6415 return; 6416 } 6417 case Intrinsic::minnum: 6418 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6419 getValue(I.getArgOperand(0)).getValueType(), 6420 getValue(I.getArgOperand(0)), 6421 getValue(I.getArgOperand(1)), Flags)); 6422 return; 6423 case Intrinsic::maxnum: 6424 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6425 getValue(I.getArgOperand(0)).getValueType(), 6426 getValue(I.getArgOperand(0)), 6427 getValue(I.getArgOperand(1)), Flags)); 6428 return; 6429 case Intrinsic::minimum: 6430 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6431 getValue(I.getArgOperand(0)).getValueType(), 6432 getValue(I.getArgOperand(0)), 6433 getValue(I.getArgOperand(1)), Flags)); 6434 return; 6435 case Intrinsic::maximum: 6436 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6437 getValue(I.getArgOperand(0)).getValueType(), 6438 getValue(I.getArgOperand(0)), 6439 getValue(I.getArgOperand(1)), Flags)); 6440 return; 6441 case Intrinsic::copysign: 6442 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6443 getValue(I.getArgOperand(0)).getValueType(), 6444 getValue(I.getArgOperand(0)), 6445 getValue(I.getArgOperand(1)), Flags)); 6446 return; 6447 case Intrinsic::arithmetic_fence: { 6448 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6449 getValue(I.getArgOperand(0)).getValueType(), 6450 getValue(I.getArgOperand(0)), Flags)); 6451 return; 6452 } 6453 case Intrinsic::fma: 6454 setValue(&I, DAG.getNode( 6455 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6456 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6457 getValue(I.getArgOperand(2)), Flags)); 6458 return; 6459 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6460 case Intrinsic::INTRINSIC: 6461 #include "llvm/IR/ConstrainedOps.def" 6462 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6463 return; 6464 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6465 #include "llvm/IR/VPIntrinsics.def" 6466 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6467 return; 6468 case Intrinsic::fptrunc_round: { 6469 // Get the last argument, the metadata and convert it to an integer in the 6470 // call 6471 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6472 std::optional<RoundingMode> RoundMode = 6473 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6474 6475 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6476 6477 // Propagate fast-math-flags from IR to node(s). 6478 SDNodeFlags Flags; 6479 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6480 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6481 6482 SDValue Result; 6483 Result = DAG.getNode( 6484 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6485 DAG.getTargetConstant((int)*RoundMode, sdl, 6486 TLI.getPointerTy(DAG.getDataLayout()))); 6487 setValue(&I, Result); 6488 6489 return; 6490 } 6491 case Intrinsic::fmuladd: { 6492 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6493 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6494 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6495 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6496 getValue(I.getArgOperand(0)).getValueType(), 6497 getValue(I.getArgOperand(0)), 6498 getValue(I.getArgOperand(1)), 6499 getValue(I.getArgOperand(2)), Flags)); 6500 } else { 6501 // TODO: Intrinsic calls should have fast-math-flags. 6502 SDValue Mul = DAG.getNode( 6503 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6504 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6505 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6506 getValue(I.getArgOperand(0)).getValueType(), 6507 Mul, getValue(I.getArgOperand(2)), Flags); 6508 setValue(&I, Add); 6509 } 6510 return; 6511 } 6512 case Intrinsic::convert_to_fp16: 6513 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6514 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6515 getValue(I.getArgOperand(0)), 6516 DAG.getTargetConstant(0, sdl, 6517 MVT::i32)))); 6518 return; 6519 case Intrinsic::convert_from_fp16: 6520 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6521 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6522 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6523 getValue(I.getArgOperand(0))))); 6524 return; 6525 case Intrinsic::fptosi_sat: { 6526 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6527 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6528 getValue(I.getArgOperand(0)), 6529 DAG.getValueType(VT.getScalarType()))); 6530 return; 6531 } 6532 case Intrinsic::fptoui_sat: { 6533 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6534 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6535 getValue(I.getArgOperand(0)), 6536 DAG.getValueType(VT.getScalarType()))); 6537 return; 6538 } 6539 case Intrinsic::set_rounding: 6540 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6541 {getRoot(), getValue(I.getArgOperand(0))}); 6542 setValue(&I, Res); 6543 DAG.setRoot(Res.getValue(0)); 6544 return; 6545 case Intrinsic::is_fpclass: { 6546 const DataLayout DLayout = DAG.getDataLayout(); 6547 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6548 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6549 FPClassTest Test = static_cast<FPClassTest>( 6550 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6551 MachineFunction &MF = DAG.getMachineFunction(); 6552 const Function &F = MF.getFunction(); 6553 SDValue Op = getValue(I.getArgOperand(0)); 6554 SDNodeFlags Flags; 6555 Flags.setNoFPExcept( 6556 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6557 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6558 // expansion can use illegal types. Making expansion early allows 6559 // legalizing these types prior to selection. 6560 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6561 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6562 setValue(&I, Result); 6563 return; 6564 } 6565 6566 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6567 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6568 setValue(&I, V); 6569 return; 6570 } 6571 case Intrinsic::pcmarker: { 6572 SDValue Tmp = getValue(I.getArgOperand(0)); 6573 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6574 return; 6575 } 6576 case Intrinsic::readcyclecounter: { 6577 SDValue Op = getRoot(); 6578 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6579 DAG.getVTList(MVT::i64, MVT::Other), Op); 6580 setValue(&I, Res); 6581 DAG.setRoot(Res.getValue(1)); 6582 return; 6583 } 6584 case Intrinsic::bitreverse: 6585 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6586 getValue(I.getArgOperand(0)).getValueType(), 6587 getValue(I.getArgOperand(0)))); 6588 return; 6589 case Intrinsic::bswap: 6590 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6591 getValue(I.getArgOperand(0)).getValueType(), 6592 getValue(I.getArgOperand(0)))); 6593 return; 6594 case Intrinsic::cttz: { 6595 SDValue Arg = getValue(I.getArgOperand(0)); 6596 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6597 EVT Ty = Arg.getValueType(); 6598 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6599 sdl, Ty, Arg)); 6600 return; 6601 } 6602 case Intrinsic::ctlz: { 6603 SDValue Arg = getValue(I.getArgOperand(0)); 6604 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6605 EVT Ty = Arg.getValueType(); 6606 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6607 sdl, Ty, Arg)); 6608 return; 6609 } 6610 case Intrinsic::ctpop: { 6611 SDValue Arg = getValue(I.getArgOperand(0)); 6612 EVT Ty = Arg.getValueType(); 6613 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6614 return; 6615 } 6616 case Intrinsic::fshl: 6617 case Intrinsic::fshr: { 6618 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6619 SDValue X = getValue(I.getArgOperand(0)); 6620 SDValue Y = getValue(I.getArgOperand(1)); 6621 SDValue Z = getValue(I.getArgOperand(2)); 6622 EVT VT = X.getValueType(); 6623 6624 if (X == Y) { 6625 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6626 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6627 } else { 6628 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6629 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6630 } 6631 return; 6632 } 6633 case Intrinsic::sadd_sat: { 6634 SDValue Op1 = getValue(I.getArgOperand(0)); 6635 SDValue Op2 = getValue(I.getArgOperand(1)); 6636 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6637 return; 6638 } 6639 case Intrinsic::uadd_sat: { 6640 SDValue Op1 = getValue(I.getArgOperand(0)); 6641 SDValue Op2 = getValue(I.getArgOperand(1)); 6642 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6643 return; 6644 } 6645 case Intrinsic::ssub_sat: { 6646 SDValue Op1 = getValue(I.getArgOperand(0)); 6647 SDValue Op2 = getValue(I.getArgOperand(1)); 6648 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6649 return; 6650 } 6651 case Intrinsic::usub_sat: { 6652 SDValue Op1 = getValue(I.getArgOperand(0)); 6653 SDValue Op2 = getValue(I.getArgOperand(1)); 6654 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6655 return; 6656 } 6657 case Intrinsic::sshl_sat: { 6658 SDValue Op1 = getValue(I.getArgOperand(0)); 6659 SDValue Op2 = getValue(I.getArgOperand(1)); 6660 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6661 return; 6662 } 6663 case Intrinsic::ushl_sat: { 6664 SDValue Op1 = getValue(I.getArgOperand(0)); 6665 SDValue Op2 = getValue(I.getArgOperand(1)); 6666 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6667 return; 6668 } 6669 case Intrinsic::smul_fix: 6670 case Intrinsic::umul_fix: 6671 case Intrinsic::smul_fix_sat: 6672 case Intrinsic::umul_fix_sat: { 6673 SDValue Op1 = getValue(I.getArgOperand(0)); 6674 SDValue Op2 = getValue(I.getArgOperand(1)); 6675 SDValue Op3 = getValue(I.getArgOperand(2)); 6676 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6677 Op1.getValueType(), Op1, Op2, Op3)); 6678 return; 6679 } 6680 case Intrinsic::sdiv_fix: 6681 case Intrinsic::udiv_fix: 6682 case Intrinsic::sdiv_fix_sat: 6683 case Intrinsic::udiv_fix_sat: { 6684 SDValue Op1 = getValue(I.getArgOperand(0)); 6685 SDValue Op2 = getValue(I.getArgOperand(1)); 6686 SDValue Op3 = getValue(I.getArgOperand(2)); 6687 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6688 Op1, Op2, Op3, DAG, TLI)); 6689 return; 6690 } 6691 case Intrinsic::smax: { 6692 SDValue Op1 = getValue(I.getArgOperand(0)); 6693 SDValue Op2 = getValue(I.getArgOperand(1)); 6694 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6695 return; 6696 } 6697 case Intrinsic::smin: { 6698 SDValue Op1 = getValue(I.getArgOperand(0)); 6699 SDValue Op2 = getValue(I.getArgOperand(1)); 6700 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6701 return; 6702 } 6703 case Intrinsic::umax: { 6704 SDValue Op1 = getValue(I.getArgOperand(0)); 6705 SDValue Op2 = getValue(I.getArgOperand(1)); 6706 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6707 return; 6708 } 6709 case Intrinsic::umin: { 6710 SDValue Op1 = getValue(I.getArgOperand(0)); 6711 SDValue Op2 = getValue(I.getArgOperand(1)); 6712 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6713 return; 6714 } 6715 case Intrinsic::abs: { 6716 // TODO: Preserve "int min is poison" arg in SDAG? 6717 SDValue Op1 = getValue(I.getArgOperand(0)); 6718 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6719 return; 6720 } 6721 case Intrinsic::stacksave: { 6722 SDValue Op = getRoot(); 6723 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6724 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6725 setValue(&I, Res); 6726 DAG.setRoot(Res.getValue(1)); 6727 return; 6728 } 6729 case Intrinsic::stackrestore: 6730 Res = getValue(I.getArgOperand(0)); 6731 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6732 return; 6733 case Intrinsic::get_dynamic_area_offset: { 6734 SDValue Op = getRoot(); 6735 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6736 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6737 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6738 // target. 6739 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6740 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6741 " intrinsic!"); 6742 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6743 Op); 6744 DAG.setRoot(Op); 6745 setValue(&I, Res); 6746 return; 6747 } 6748 case Intrinsic::stackguard: { 6749 MachineFunction &MF = DAG.getMachineFunction(); 6750 const Module &M = *MF.getFunction().getParent(); 6751 SDValue Chain = getRoot(); 6752 if (TLI.useLoadStackGuardNode()) { 6753 Res = getLoadStackGuard(DAG, sdl, Chain); 6754 } else { 6755 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6756 const Value *Global = TLI.getSDagStackGuard(M); 6757 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6758 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6759 MachinePointerInfo(Global, 0), Align, 6760 MachineMemOperand::MOVolatile); 6761 } 6762 if (TLI.useStackGuardXorFP()) 6763 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6764 DAG.setRoot(Chain); 6765 setValue(&I, Res); 6766 return; 6767 } 6768 case Intrinsic::stackprotector: { 6769 // Emit code into the DAG to store the stack guard onto the stack. 6770 MachineFunction &MF = DAG.getMachineFunction(); 6771 MachineFrameInfo &MFI = MF.getFrameInfo(); 6772 SDValue Src, Chain = getRoot(); 6773 6774 if (TLI.useLoadStackGuardNode()) 6775 Src = getLoadStackGuard(DAG, sdl, Chain); 6776 else 6777 Src = getValue(I.getArgOperand(0)); // The guard's value. 6778 6779 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6780 6781 int FI = FuncInfo.StaticAllocaMap[Slot]; 6782 MFI.setStackProtectorIndex(FI); 6783 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6784 6785 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6786 6787 // Store the stack protector onto the stack. 6788 Res = DAG.getStore( 6789 Chain, sdl, Src, FIN, 6790 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6791 MaybeAlign(), MachineMemOperand::MOVolatile); 6792 setValue(&I, Res); 6793 DAG.setRoot(Res); 6794 return; 6795 } 6796 case Intrinsic::objectsize: 6797 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6798 6799 case Intrinsic::is_constant: 6800 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6801 6802 case Intrinsic::annotation: 6803 case Intrinsic::ptr_annotation: 6804 case Intrinsic::launder_invariant_group: 6805 case Intrinsic::strip_invariant_group: 6806 // Drop the intrinsic, but forward the value 6807 setValue(&I, getValue(I.getOperand(0))); 6808 return; 6809 6810 case Intrinsic::assume: 6811 case Intrinsic::experimental_noalias_scope_decl: 6812 case Intrinsic::var_annotation: 6813 case Intrinsic::sideeffect: 6814 // Discard annotate attributes, noalias scope declarations, assumptions, and 6815 // artificial side-effects. 6816 return; 6817 6818 case Intrinsic::codeview_annotation: { 6819 // Emit a label associated with this metadata. 6820 MachineFunction &MF = DAG.getMachineFunction(); 6821 MCSymbol *Label = 6822 MF.getMMI().getContext().createTempSymbol("annotation", true); 6823 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6824 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6825 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6826 DAG.setRoot(Res); 6827 return; 6828 } 6829 6830 case Intrinsic::init_trampoline: { 6831 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6832 6833 SDValue Ops[6]; 6834 Ops[0] = getRoot(); 6835 Ops[1] = getValue(I.getArgOperand(0)); 6836 Ops[2] = getValue(I.getArgOperand(1)); 6837 Ops[3] = getValue(I.getArgOperand(2)); 6838 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6839 Ops[5] = DAG.getSrcValue(F); 6840 6841 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6842 6843 DAG.setRoot(Res); 6844 return; 6845 } 6846 case Intrinsic::adjust_trampoline: 6847 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6848 TLI.getPointerTy(DAG.getDataLayout()), 6849 getValue(I.getArgOperand(0)))); 6850 return; 6851 case Intrinsic::gcroot: { 6852 assert(DAG.getMachineFunction().getFunction().hasGC() && 6853 "only valid in functions with gc specified, enforced by Verifier"); 6854 assert(GFI && "implied by previous"); 6855 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6856 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6857 6858 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6859 GFI->addStackRoot(FI->getIndex(), TypeMap); 6860 return; 6861 } 6862 case Intrinsic::gcread: 6863 case Intrinsic::gcwrite: 6864 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6865 case Intrinsic::get_rounding: 6866 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6867 setValue(&I, Res); 6868 DAG.setRoot(Res.getValue(1)); 6869 return; 6870 6871 case Intrinsic::expect: 6872 // Just replace __builtin_expect(exp, c) with EXP. 6873 setValue(&I, getValue(I.getArgOperand(0))); 6874 return; 6875 6876 case Intrinsic::ubsantrap: 6877 case Intrinsic::debugtrap: 6878 case Intrinsic::trap: { 6879 StringRef TrapFuncName = 6880 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6881 if (TrapFuncName.empty()) { 6882 switch (Intrinsic) { 6883 case Intrinsic::trap: 6884 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6885 break; 6886 case Intrinsic::debugtrap: 6887 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6888 break; 6889 case Intrinsic::ubsantrap: 6890 DAG.setRoot(DAG.getNode( 6891 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6892 DAG.getTargetConstant( 6893 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6894 MVT::i32))); 6895 break; 6896 default: llvm_unreachable("unknown trap intrinsic"); 6897 } 6898 return; 6899 } 6900 TargetLowering::ArgListTy Args; 6901 if (Intrinsic == Intrinsic::ubsantrap) { 6902 Args.push_back(TargetLoweringBase::ArgListEntry()); 6903 Args[0].Val = I.getArgOperand(0); 6904 Args[0].Node = getValue(Args[0].Val); 6905 Args[0].Ty = Args[0].Val->getType(); 6906 } 6907 6908 TargetLowering::CallLoweringInfo CLI(DAG); 6909 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6910 CallingConv::C, I.getType(), 6911 DAG.getExternalSymbol(TrapFuncName.data(), 6912 TLI.getPointerTy(DAG.getDataLayout())), 6913 std::move(Args)); 6914 6915 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6916 DAG.setRoot(Result.second); 6917 return; 6918 } 6919 6920 case Intrinsic::uadd_with_overflow: 6921 case Intrinsic::sadd_with_overflow: 6922 case Intrinsic::usub_with_overflow: 6923 case Intrinsic::ssub_with_overflow: 6924 case Intrinsic::umul_with_overflow: 6925 case Intrinsic::smul_with_overflow: { 6926 ISD::NodeType Op; 6927 switch (Intrinsic) { 6928 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6929 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6930 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6931 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6932 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6933 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6934 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6935 } 6936 SDValue Op1 = getValue(I.getArgOperand(0)); 6937 SDValue Op2 = getValue(I.getArgOperand(1)); 6938 6939 EVT ResultVT = Op1.getValueType(); 6940 EVT OverflowVT = MVT::i1; 6941 if (ResultVT.isVector()) 6942 OverflowVT = EVT::getVectorVT( 6943 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6944 6945 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6946 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6947 return; 6948 } 6949 case Intrinsic::prefetch: { 6950 SDValue Ops[5]; 6951 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6952 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6953 Ops[0] = DAG.getRoot(); 6954 Ops[1] = getValue(I.getArgOperand(0)); 6955 Ops[2] = getValue(I.getArgOperand(1)); 6956 Ops[3] = getValue(I.getArgOperand(2)); 6957 Ops[4] = getValue(I.getArgOperand(3)); 6958 SDValue Result = DAG.getMemIntrinsicNode( 6959 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6960 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6961 /* align */ std::nullopt, Flags); 6962 6963 // Chain the prefetch in parallell with any pending loads, to stay out of 6964 // the way of later optimizations. 6965 PendingLoads.push_back(Result); 6966 Result = getRoot(); 6967 DAG.setRoot(Result); 6968 return; 6969 } 6970 case Intrinsic::lifetime_start: 6971 case Intrinsic::lifetime_end: { 6972 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6973 // Stack coloring is not enabled in O0, discard region information. 6974 if (TM.getOptLevel() == CodeGenOpt::None) 6975 return; 6976 6977 const int64_t ObjectSize = 6978 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6979 Value *const ObjectPtr = I.getArgOperand(1); 6980 SmallVector<const Value *, 4> Allocas; 6981 getUnderlyingObjects(ObjectPtr, Allocas); 6982 6983 for (const Value *Alloca : Allocas) { 6984 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6985 6986 // Could not find an Alloca. 6987 if (!LifetimeObject) 6988 continue; 6989 6990 // First check that the Alloca is static, otherwise it won't have a 6991 // valid frame index. 6992 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6993 if (SI == FuncInfo.StaticAllocaMap.end()) 6994 return; 6995 6996 const int FrameIndex = SI->second; 6997 int64_t Offset; 6998 if (GetPointerBaseWithConstantOffset( 6999 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7000 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7001 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7002 Offset); 7003 DAG.setRoot(Res); 7004 } 7005 return; 7006 } 7007 case Intrinsic::pseudoprobe: { 7008 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7009 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7010 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7011 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7012 DAG.setRoot(Res); 7013 return; 7014 } 7015 case Intrinsic::invariant_start: 7016 // Discard region information. 7017 setValue(&I, 7018 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7019 return; 7020 case Intrinsic::invariant_end: 7021 // Discard region information. 7022 return; 7023 case Intrinsic::clear_cache: 7024 /// FunctionName may be null. 7025 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7026 lowerCallToExternalSymbol(I, FunctionName); 7027 return; 7028 case Intrinsic::donothing: 7029 case Intrinsic::seh_try_begin: 7030 case Intrinsic::seh_scope_begin: 7031 case Intrinsic::seh_try_end: 7032 case Intrinsic::seh_scope_end: 7033 // ignore 7034 return; 7035 case Intrinsic::experimental_stackmap: 7036 visitStackmap(I); 7037 return; 7038 case Intrinsic::experimental_patchpoint_void: 7039 case Intrinsic::experimental_patchpoint_i64: 7040 visitPatchpoint(I); 7041 return; 7042 case Intrinsic::experimental_gc_statepoint: 7043 LowerStatepoint(cast<GCStatepointInst>(I)); 7044 return; 7045 case Intrinsic::experimental_gc_result: 7046 visitGCResult(cast<GCResultInst>(I)); 7047 return; 7048 case Intrinsic::experimental_gc_relocate: 7049 visitGCRelocate(cast<GCRelocateInst>(I)); 7050 return; 7051 case Intrinsic::instrprof_cover: 7052 llvm_unreachable("instrprof failed to lower a cover"); 7053 case Intrinsic::instrprof_increment: 7054 llvm_unreachable("instrprof failed to lower an increment"); 7055 case Intrinsic::instrprof_timestamp: 7056 llvm_unreachable("instrprof failed to lower a timestamp"); 7057 case Intrinsic::instrprof_value_profile: 7058 llvm_unreachable("instrprof failed to lower a value profiling call"); 7059 case Intrinsic::localescape: { 7060 MachineFunction &MF = DAG.getMachineFunction(); 7061 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7062 7063 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7064 // is the same on all targets. 7065 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7066 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7067 if (isa<ConstantPointerNull>(Arg)) 7068 continue; // Skip null pointers. They represent a hole in index space. 7069 AllocaInst *Slot = cast<AllocaInst>(Arg); 7070 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7071 "can only escape static allocas"); 7072 int FI = FuncInfo.StaticAllocaMap[Slot]; 7073 MCSymbol *FrameAllocSym = 7074 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7075 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7076 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7077 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7078 .addSym(FrameAllocSym) 7079 .addFrameIndex(FI); 7080 } 7081 7082 return; 7083 } 7084 7085 case Intrinsic::localrecover: { 7086 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7087 MachineFunction &MF = DAG.getMachineFunction(); 7088 7089 // Get the symbol that defines the frame offset. 7090 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7091 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7092 unsigned IdxVal = 7093 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7094 MCSymbol *FrameAllocSym = 7095 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7096 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7097 7098 Value *FP = I.getArgOperand(1); 7099 SDValue FPVal = getValue(FP); 7100 EVT PtrVT = FPVal.getValueType(); 7101 7102 // Create a MCSymbol for the label to avoid any target lowering 7103 // that would make this PC relative. 7104 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7105 SDValue OffsetVal = 7106 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7107 7108 // Add the offset to the FP. 7109 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7110 setValue(&I, Add); 7111 7112 return; 7113 } 7114 7115 case Intrinsic::eh_exceptionpointer: 7116 case Intrinsic::eh_exceptioncode: { 7117 // Get the exception pointer vreg, copy from it, and resize it to fit. 7118 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7119 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7120 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7121 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7122 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7123 if (Intrinsic == Intrinsic::eh_exceptioncode) 7124 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7125 setValue(&I, N); 7126 return; 7127 } 7128 case Intrinsic::xray_customevent: { 7129 // Here we want to make sure that the intrinsic behaves as if it has a 7130 // specific calling convention, and only for x86_64. 7131 // FIXME: Support other platforms later. 7132 const auto &Triple = DAG.getTarget().getTargetTriple(); 7133 if (Triple.getArch() != Triple::x86_64) 7134 return; 7135 7136 SmallVector<SDValue, 8> Ops; 7137 7138 // We want to say that we always want the arguments in registers. 7139 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7140 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7141 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7142 SDValue Chain = getRoot(); 7143 Ops.push_back(LogEntryVal); 7144 Ops.push_back(StrSizeVal); 7145 Ops.push_back(Chain); 7146 7147 // We need to enforce the calling convention for the callsite, so that 7148 // argument ordering is enforced correctly, and that register allocation can 7149 // see that some registers may be assumed clobbered and have to preserve 7150 // them across calls to the intrinsic. 7151 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7152 sdl, NodeTys, Ops); 7153 SDValue patchableNode = SDValue(MN, 0); 7154 DAG.setRoot(patchableNode); 7155 setValue(&I, patchableNode); 7156 return; 7157 } 7158 case Intrinsic::xray_typedevent: { 7159 // Here we want to make sure that the intrinsic behaves as if it has a 7160 // specific calling convention, and only for x86_64. 7161 // FIXME: Support other platforms later. 7162 const auto &Triple = DAG.getTarget().getTargetTriple(); 7163 if (Triple.getArch() != Triple::x86_64) 7164 return; 7165 7166 SmallVector<SDValue, 8> Ops; 7167 7168 // We want to say that we always want the arguments in registers. 7169 // It's unclear to me how manipulating the selection DAG here forces callers 7170 // to provide arguments in registers instead of on the stack. 7171 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7172 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7173 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7174 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7175 SDValue Chain = getRoot(); 7176 Ops.push_back(LogTypeId); 7177 Ops.push_back(LogEntryVal); 7178 Ops.push_back(StrSizeVal); 7179 Ops.push_back(Chain); 7180 7181 // We need to enforce the calling convention for the callsite, so that 7182 // argument ordering is enforced correctly, and that register allocation can 7183 // see that some registers may be assumed clobbered and have to preserve 7184 // them across calls to the intrinsic. 7185 MachineSDNode *MN = DAG.getMachineNode( 7186 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7187 SDValue patchableNode = SDValue(MN, 0); 7188 DAG.setRoot(patchableNode); 7189 setValue(&I, patchableNode); 7190 return; 7191 } 7192 case Intrinsic::experimental_deoptimize: 7193 LowerDeoptimizeCall(&I); 7194 return; 7195 case Intrinsic::experimental_stepvector: 7196 visitStepVector(I); 7197 return; 7198 case Intrinsic::vector_reduce_fadd: 7199 case Intrinsic::vector_reduce_fmul: 7200 case Intrinsic::vector_reduce_add: 7201 case Intrinsic::vector_reduce_mul: 7202 case Intrinsic::vector_reduce_and: 7203 case Intrinsic::vector_reduce_or: 7204 case Intrinsic::vector_reduce_xor: 7205 case Intrinsic::vector_reduce_smax: 7206 case Intrinsic::vector_reduce_smin: 7207 case Intrinsic::vector_reduce_umax: 7208 case Intrinsic::vector_reduce_umin: 7209 case Intrinsic::vector_reduce_fmax: 7210 case Intrinsic::vector_reduce_fmin: 7211 visitVectorReduce(I, Intrinsic); 7212 return; 7213 7214 case Intrinsic::icall_branch_funnel: { 7215 SmallVector<SDValue, 16> Ops; 7216 Ops.push_back(getValue(I.getArgOperand(0))); 7217 7218 int64_t Offset; 7219 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7220 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7221 if (!Base) 7222 report_fatal_error( 7223 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7224 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7225 7226 struct BranchFunnelTarget { 7227 int64_t Offset; 7228 SDValue Target; 7229 }; 7230 SmallVector<BranchFunnelTarget, 8> Targets; 7231 7232 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7233 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7234 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7235 if (ElemBase != Base) 7236 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7237 "to the same GlobalValue"); 7238 7239 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7240 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7241 if (!GA) 7242 report_fatal_error( 7243 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7244 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7245 GA->getGlobal(), sdl, Val.getValueType(), 7246 GA->getOffset())}); 7247 } 7248 llvm::sort(Targets, 7249 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7250 return T1.Offset < T2.Offset; 7251 }); 7252 7253 for (auto &T : Targets) { 7254 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7255 Ops.push_back(T.Target); 7256 } 7257 7258 Ops.push_back(DAG.getRoot()); // Chain 7259 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7260 MVT::Other, Ops), 7261 0); 7262 DAG.setRoot(N); 7263 setValue(&I, N); 7264 HasTailCall = true; 7265 return; 7266 } 7267 7268 case Intrinsic::wasm_landingpad_index: 7269 // Information this intrinsic contained has been transferred to 7270 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7271 // delete it now. 7272 return; 7273 7274 case Intrinsic::aarch64_settag: 7275 case Intrinsic::aarch64_settag_zero: { 7276 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7277 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7278 SDValue Val = TSI.EmitTargetCodeForSetTag( 7279 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7280 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7281 ZeroMemory); 7282 DAG.setRoot(Val); 7283 setValue(&I, Val); 7284 return; 7285 } 7286 case Intrinsic::ptrmask: { 7287 SDValue Ptr = getValue(I.getOperand(0)); 7288 SDValue Const = getValue(I.getOperand(1)); 7289 7290 EVT PtrVT = Ptr.getValueType(); 7291 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7292 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7293 return; 7294 } 7295 case Intrinsic::threadlocal_address: { 7296 setValue(&I, getValue(I.getOperand(0))); 7297 return; 7298 } 7299 case Intrinsic::get_active_lane_mask: { 7300 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7301 SDValue Index = getValue(I.getOperand(0)); 7302 EVT ElementVT = Index.getValueType(); 7303 7304 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7305 visitTargetIntrinsic(I, Intrinsic); 7306 return; 7307 } 7308 7309 SDValue TripCount = getValue(I.getOperand(1)); 7310 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7311 7312 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7313 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7314 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7315 SDValue VectorInduction = DAG.getNode( 7316 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7317 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7318 VectorTripCount, ISD::CondCode::SETULT); 7319 setValue(&I, SetCC); 7320 return; 7321 } 7322 case Intrinsic::experimental_get_vector_length: { 7323 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7324 "Expected positive VF"); 7325 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7326 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7327 7328 SDValue Count = getValue(I.getOperand(0)); 7329 EVT CountVT = Count.getValueType(); 7330 7331 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7332 visitTargetIntrinsic(I, Intrinsic); 7333 return; 7334 } 7335 7336 // Expand to a umin between the trip count and the maximum elements the type 7337 // can hold. 7338 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7339 7340 // Extend the trip count to at least the result VT. 7341 if (CountVT.bitsLT(VT)) { 7342 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7343 CountVT = VT; 7344 } 7345 7346 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7347 ElementCount::get(VF, IsScalable)); 7348 7349 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7350 // Clip to the result type if needed. 7351 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7352 7353 setValue(&I, Trunc); 7354 return; 7355 } 7356 case Intrinsic::vector_insert: { 7357 SDValue Vec = getValue(I.getOperand(0)); 7358 SDValue SubVec = getValue(I.getOperand(1)); 7359 SDValue Index = getValue(I.getOperand(2)); 7360 7361 // The intrinsic's index type is i64, but the SDNode requires an index type 7362 // suitable for the target. Convert the index as required. 7363 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7364 if (Index.getValueType() != VectorIdxTy) 7365 Index = DAG.getVectorIdxConstant( 7366 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7367 7368 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7369 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7370 Index)); 7371 return; 7372 } 7373 case Intrinsic::vector_extract: { 7374 SDValue Vec = getValue(I.getOperand(0)); 7375 SDValue Index = getValue(I.getOperand(1)); 7376 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7377 7378 // The intrinsic's index type is i64, but the SDNode requires an index type 7379 // suitable for the target. Convert the index as required. 7380 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7381 if (Index.getValueType() != VectorIdxTy) 7382 Index = DAG.getVectorIdxConstant( 7383 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7384 7385 setValue(&I, 7386 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7387 return; 7388 } 7389 case Intrinsic::experimental_vector_reverse: 7390 visitVectorReverse(I); 7391 return; 7392 case Intrinsic::experimental_vector_splice: 7393 visitVectorSplice(I); 7394 return; 7395 case Intrinsic::callbr_landingpad: 7396 visitCallBrLandingPad(I); 7397 return; 7398 case Intrinsic::experimental_vector_interleave2: 7399 visitVectorInterleave(I); 7400 return; 7401 case Intrinsic::experimental_vector_deinterleave2: 7402 visitVectorDeinterleave(I); 7403 return; 7404 } 7405 } 7406 7407 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7408 const ConstrainedFPIntrinsic &FPI) { 7409 SDLoc sdl = getCurSDLoc(); 7410 7411 // We do not need to serialize constrained FP intrinsics against 7412 // each other or against (nonvolatile) loads, so they can be 7413 // chained like loads. 7414 SDValue Chain = DAG.getRoot(); 7415 SmallVector<SDValue, 4> Opers; 7416 Opers.push_back(Chain); 7417 if (FPI.isUnaryOp()) { 7418 Opers.push_back(getValue(FPI.getArgOperand(0))); 7419 } else if (FPI.isTernaryOp()) { 7420 Opers.push_back(getValue(FPI.getArgOperand(0))); 7421 Opers.push_back(getValue(FPI.getArgOperand(1))); 7422 Opers.push_back(getValue(FPI.getArgOperand(2))); 7423 } else { 7424 Opers.push_back(getValue(FPI.getArgOperand(0))); 7425 Opers.push_back(getValue(FPI.getArgOperand(1))); 7426 } 7427 7428 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7429 assert(Result.getNode()->getNumValues() == 2); 7430 7431 // Push node to the appropriate list so that future instructions can be 7432 // chained up correctly. 7433 SDValue OutChain = Result.getValue(1); 7434 switch (EB) { 7435 case fp::ExceptionBehavior::ebIgnore: 7436 // The only reason why ebIgnore nodes still need to be chained is that 7437 // they might depend on the current rounding mode, and therefore must 7438 // not be moved across instruction that may change that mode. 7439 [[fallthrough]]; 7440 case fp::ExceptionBehavior::ebMayTrap: 7441 // These must not be moved across calls or instructions that may change 7442 // floating-point exception masks. 7443 PendingConstrainedFP.push_back(OutChain); 7444 break; 7445 case fp::ExceptionBehavior::ebStrict: 7446 // These must not be moved across calls or instructions that may change 7447 // floating-point exception masks or read floating-point exception flags. 7448 // In addition, they cannot be optimized out even if unused. 7449 PendingConstrainedFPStrict.push_back(OutChain); 7450 break; 7451 } 7452 }; 7453 7454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7455 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7456 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7457 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7458 7459 SDNodeFlags Flags; 7460 if (EB == fp::ExceptionBehavior::ebIgnore) 7461 Flags.setNoFPExcept(true); 7462 7463 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7464 Flags.copyFMF(*FPOp); 7465 7466 unsigned Opcode; 7467 switch (FPI.getIntrinsicID()) { 7468 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7469 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7470 case Intrinsic::INTRINSIC: \ 7471 Opcode = ISD::STRICT_##DAGN; \ 7472 break; 7473 #include "llvm/IR/ConstrainedOps.def" 7474 case Intrinsic::experimental_constrained_fmuladd: { 7475 Opcode = ISD::STRICT_FMA; 7476 // Break fmuladd into fmul and fadd. 7477 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7478 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7479 Opers.pop_back(); 7480 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7481 pushOutChain(Mul, EB); 7482 Opcode = ISD::STRICT_FADD; 7483 Opers.clear(); 7484 Opers.push_back(Mul.getValue(1)); 7485 Opers.push_back(Mul.getValue(0)); 7486 Opers.push_back(getValue(FPI.getArgOperand(2))); 7487 } 7488 break; 7489 } 7490 } 7491 7492 // A few strict DAG nodes carry additional operands that are not 7493 // set up by the default code above. 7494 switch (Opcode) { 7495 default: break; 7496 case ISD::STRICT_FP_ROUND: 7497 Opers.push_back( 7498 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7499 break; 7500 case ISD::STRICT_FSETCC: 7501 case ISD::STRICT_FSETCCS: { 7502 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7503 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7504 if (TM.Options.NoNaNsFPMath) 7505 Condition = getFCmpCodeWithoutNaN(Condition); 7506 Opers.push_back(DAG.getCondCode(Condition)); 7507 break; 7508 } 7509 } 7510 7511 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7512 pushOutChain(Result, EB); 7513 7514 SDValue FPResult = Result.getValue(0); 7515 setValue(&FPI, FPResult); 7516 } 7517 7518 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7519 std::optional<unsigned> ResOPC; 7520 switch (VPIntrin.getIntrinsicID()) { 7521 case Intrinsic::vp_ctlz: { 7522 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7523 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7524 break; 7525 } 7526 case Intrinsic::vp_cttz: { 7527 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7528 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7529 break; 7530 } 7531 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7532 case Intrinsic::VPID: \ 7533 ResOPC = ISD::VPSD; \ 7534 break; 7535 #include "llvm/IR/VPIntrinsics.def" 7536 } 7537 7538 if (!ResOPC) 7539 llvm_unreachable( 7540 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7541 7542 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7543 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7544 if (VPIntrin.getFastMathFlags().allowReassoc()) 7545 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7546 : ISD::VP_REDUCE_FMUL; 7547 } 7548 7549 return *ResOPC; 7550 } 7551 7552 void SelectionDAGBuilder::visitVPLoad( 7553 const VPIntrinsic &VPIntrin, EVT VT, 7554 const SmallVectorImpl<SDValue> &OpValues) { 7555 SDLoc DL = getCurSDLoc(); 7556 Value *PtrOperand = VPIntrin.getArgOperand(0); 7557 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7558 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7559 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7560 SDValue LD; 7561 // Do not serialize variable-length loads of constant memory with 7562 // anything. 7563 if (!Alignment) 7564 Alignment = DAG.getEVTAlign(VT); 7565 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7566 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7567 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7568 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7569 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7570 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7571 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7572 MMO, false /*IsExpanding */); 7573 if (AddToChain) 7574 PendingLoads.push_back(LD.getValue(1)); 7575 setValue(&VPIntrin, LD); 7576 } 7577 7578 void SelectionDAGBuilder::visitVPGather( 7579 const VPIntrinsic &VPIntrin, EVT VT, 7580 const SmallVectorImpl<SDValue> &OpValues) { 7581 SDLoc DL = getCurSDLoc(); 7582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7583 Value *PtrOperand = VPIntrin.getArgOperand(0); 7584 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7585 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7586 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7587 SDValue LD; 7588 if (!Alignment) 7589 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7590 unsigned AS = 7591 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7592 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7593 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7594 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7595 SDValue Base, Index, Scale; 7596 ISD::MemIndexType IndexType; 7597 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7598 this, VPIntrin.getParent(), 7599 VT.getScalarStoreSize()); 7600 if (!UniformBase) { 7601 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7602 Index = getValue(PtrOperand); 7603 IndexType = ISD::SIGNED_SCALED; 7604 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7605 } 7606 EVT IdxVT = Index.getValueType(); 7607 EVT EltTy = IdxVT.getVectorElementType(); 7608 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7609 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7610 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7611 } 7612 LD = DAG.getGatherVP( 7613 DAG.getVTList(VT, MVT::Other), VT, DL, 7614 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7615 IndexType); 7616 PendingLoads.push_back(LD.getValue(1)); 7617 setValue(&VPIntrin, LD); 7618 } 7619 7620 void SelectionDAGBuilder::visitVPStore( 7621 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7622 SDLoc DL = getCurSDLoc(); 7623 Value *PtrOperand = VPIntrin.getArgOperand(1); 7624 EVT VT = OpValues[0].getValueType(); 7625 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7626 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7627 SDValue ST; 7628 if (!Alignment) 7629 Alignment = DAG.getEVTAlign(VT); 7630 SDValue Ptr = OpValues[1]; 7631 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7632 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7633 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7634 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7635 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7636 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7637 /* IsTruncating */ false, /*IsCompressing*/ false); 7638 DAG.setRoot(ST); 7639 setValue(&VPIntrin, ST); 7640 } 7641 7642 void SelectionDAGBuilder::visitVPScatter( 7643 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7644 SDLoc DL = getCurSDLoc(); 7645 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7646 Value *PtrOperand = VPIntrin.getArgOperand(1); 7647 EVT VT = OpValues[0].getValueType(); 7648 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7649 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7650 SDValue ST; 7651 if (!Alignment) 7652 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7653 unsigned AS = 7654 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7655 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7656 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7657 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7658 SDValue Base, Index, Scale; 7659 ISD::MemIndexType IndexType; 7660 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7661 this, VPIntrin.getParent(), 7662 VT.getScalarStoreSize()); 7663 if (!UniformBase) { 7664 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7665 Index = getValue(PtrOperand); 7666 IndexType = ISD::SIGNED_SCALED; 7667 Scale = 7668 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7669 } 7670 EVT IdxVT = Index.getValueType(); 7671 EVT EltTy = IdxVT.getVectorElementType(); 7672 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7673 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7674 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7675 } 7676 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7677 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7678 OpValues[2], OpValues[3]}, 7679 MMO, IndexType); 7680 DAG.setRoot(ST); 7681 setValue(&VPIntrin, ST); 7682 } 7683 7684 void SelectionDAGBuilder::visitVPStridedLoad( 7685 const VPIntrinsic &VPIntrin, EVT VT, 7686 const SmallVectorImpl<SDValue> &OpValues) { 7687 SDLoc DL = getCurSDLoc(); 7688 Value *PtrOperand = VPIntrin.getArgOperand(0); 7689 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7690 if (!Alignment) 7691 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7692 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7693 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7694 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7695 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7696 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7697 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7698 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7699 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7700 7701 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7702 OpValues[2], OpValues[3], MMO, 7703 false /*IsExpanding*/); 7704 7705 if (AddToChain) 7706 PendingLoads.push_back(LD.getValue(1)); 7707 setValue(&VPIntrin, LD); 7708 } 7709 7710 void SelectionDAGBuilder::visitVPStridedStore( 7711 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7712 SDLoc DL = getCurSDLoc(); 7713 Value *PtrOperand = VPIntrin.getArgOperand(1); 7714 EVT VT = OpValues[0].getValueType(); 7715 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7716 if (!Alignment) 7717 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7718 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7719 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7720 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7721 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7722 7723 SDValue ST = DAG.getStridedStoreVP( 7724 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7725 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7726 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7727 /*IsCompressing*/ false); 7728 7729 DAG.setRoot(ST); 7730 setValue(&VPIntrin, ST); 7731 } 7732 7733 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7735 SDLoc DL = getCurSDLoc(); 7736 7737 ISD::CondCode Condition; 7738 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7739 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7740 if (IsFP) { 7741 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7742 // flags, but calls that don't return floating-point types can't be 7743 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7744 Condition = getFCmpCondCode(CondCode); 7745 if (TM.Options.NoNaNsFPMath) 7746 Condition = getFCmpCodeWithoutNaN(Condition); 7747 } else { 7748 Condition = getICmpCondCode(CondCode); 7749 } 7750 7751 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7752 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7753 // #2 is the condition code 7754 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7755 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7756 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7757 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7758 "Unexpected target EVL type"); 7759 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7760 7761 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7762 VPIntrin.getType()); 7763 setValue(&VPIntrin, 7764 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7765 } 7766 7767 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7768 const VPIntrinsic &VPIntrin) { 7769 SDLoc DL = getCurSDLoc(); 7770 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7771 7772 auto IID = VPIntrin.getIntrinsicID(); 7773 7774 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7775 return visitVPCmp(*CmpI); 7776 7777 SmallVector<EVT, 4> ValueVTs; 7778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7779 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7780 SDVTList VTs = DAG.getVTList(ValueVTs); 7781 7782 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7783 7784 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7785 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7786 "Unexpected target EVL type"); 7787 7788 // Request operands. 7789 SmallVector<SDValue, 7> OpValues; 7790 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7791 auto Op = getValue(VPIntrin.getArgOperand(I)); 7792 if (I == EVLParamPos) 7793 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7794 OpValues.push_back(Op); 7795 } 7796 7797 switch (Opcode) { 7798 default: { 7799 SDNodeFlags SDFlags; 7800 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7801 SDFlags.copyFMF(*FPMO); 7802 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7803 setValue(&VPIntrin, Result); 7804 break; 7805 } 7806 case ISD::VP_LOAD: 7807 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7808 break; 7809 case ISD::VP_GATHER: 7810 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7811 break; 7812 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7813 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7814 break; 7815 case ISD::VP_STORE: 7816 visitVPStore(VPIntrin, OpValues); 7817 break; 7818 case ISD::VP_SCATTER: 7819 visitVPScatter(VPIntrin, OpValues); 7820 break; 7821 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7822 visitVPStridedStore(VPIntrin, OpValues); 7823 break; 7824 case ISD::VP_FMULADD: { 7825 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7826 SDNodeFlags SDFlags; 7827 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7828 SDFlags.copyFMF(*FPMO); 7829 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7830 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7831 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7832 } else { 7833 SDValue Mul = DAG.getNode( 7834 ISD::VP_FMUL, DL, VTs, 7835 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7836 SDValue Add = 7837 DAG.getNode(ISD::VP_FADD, DL, VTs, 7838 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7839 setValue(&VPIntrin, Add); 7840 } 7841 break; 7842 } 7843 case ISD::VP_INTTOPTR: { 7844 SDValue N = OpValues[0]; 7845 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7846 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7847 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7848 OpValues[2]); 7849 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7850 OpValues[2]); 7851 setValue(&VPIntrin, N); 7852 break; 7853 } 7854 case ISD::VP_PTRTOINT: { 7855 SDValue N = OpValues[0]; 7856 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7857 VPIntrin.getType()); 7858 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7859 VPIntrin.getOperand(0)->getType()); 7860 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7861 OpValues[2]); 7862 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7863 OpValues[2]); 7864 setValue(&VPIntrin, N); 7865 break; 7866 } 7867 case ISD::VP_ABS: 7868 case ISD::VP_CTLZ: 7869 case ISD::VP_CTLZ_ZERO_UNDEF: 7870 case ISD::VP_CTTZ: 7871 case ISD::VP_CTTZ_ZERO_UNDEF: { 7872 SDValue Result = 7873 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7874 setValue(&VPIntrin, Result); 7875 break; 7876 } 7877 } 7878 } 7879 7880 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7881 const BasicBlock *EHPadBB, 7882 MCSymbol *&BeginLabel) { 7883 MachineFunction &MF = DAG.getMachineFunction(); 7884 MachineModuleInfo &MMI = MF.getMMI(); 7885 7886 // Insert a label before the invoke call to mark the try range. This can be 7887 // used to detect deletion of the invoke via the MachineModuleInfo. 7888 BeginLabel = MMI.getContext().createTempSymbol(); 7889 7890 // For SjLj, keep track of which landing pads go with which invokes 7891 // so as to maintain the ordering of pads in the LSDA. 7892 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7893 if (CallSiteIndex) { 7894 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7895 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7896 7897 // Now that the call site is handled, stop tracking it. 7898 MMI.setCurrentCallSite(0); 7899 } 7900 7901 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7902 } 7903 7904 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7905 const BasicBlock *EHPadBB, 7906 MCSymbol *BeginLabel) { 7907 assert(BeginLabel && "BeginLabel should've been set"); 7908 7909 MachineFunction &MF = DAG.getMachineFunction(); 7910 MachineModuleInfo &MMI = MF.getMMI(); 7911 7912 // Insert a label at the end of the invoke call to mark the try range. This 7913 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7914 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7915 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7916 7917 // Inform MachineModuleInfo of range. 7918 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7919 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7920 // actually use outlined funclets and their LSDA info style. 7921 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7922 assert(II && "II should've been set"); 7923 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7924 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7925 } else if (!isScopedEHPersonality(Pers)) { 7926 assert(EHPadBB); 7927 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7928 } 7929 7930 return Chain; 7931 } 7932 7933 std::pair<SDValue, SDValue> 7934 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7935 const BasicBlock *EHPadBB) { 7936 MCSymbol *BeginLabel = nullptr; 7937 7938 if (EHPadBB) { 7939 // Both PendingLoads and PendingExports must be flushed here; 7940 // this call might not return. 7941 (void)getRoot(); 7942 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7943 CLI.setChain(getRoot()); 7944 } 7945 7946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7947 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7948 7949 assert((CLI.IsTailCall || Result.second.getNode()) && 7950 "Non-null chain expected with non-tail call!"); 7951 assert((Result.second.getNode() || !Result.first.getNode()) && 7952 "Null value expected with tail call!"); 7953 7954 if (!Result.second.getNode()) { 7955 // As a special case, a null chain means that a tail call has been emitted 7956 // and the DAG root is already updated. 7957 HasTailCall = true; 7958 7959 // Since there's no actual continuation from this block, nothing can be 7960 // relying on us setting vregs for them. 7961 PendingExports.clear(); 7962 } else { 7963 DAG.setRoot(Result.second); 7964 } 7965 7966 if (EHPadBB) { 7967 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7968 BeginLabel)); 7969 } 7970 7971 return Result; 7972 } 7973 7974 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7975 bool isTailCall, 7976 bool isMustTailCall, 7977 const BasicBlock *EHPadBB) { 7978 auto &DL = DAG.getDataLayout(); 7979 FunctionType *FTy = CB.getFunctionType(); 7980 Type *RetTy = CB.getType(); 7981 7982 TargetLowering::ArgListTy Args; 7983 Args.reserve(CB.arg_size()); 7984 7985 const Value *SwiftErrorVal = nullptr; 7986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7987 7988 if (isTailCall) { 7989 // Avoid emitting tail calls in functions with the disable-tail-calls 7990 // attribute. 7991 auto *Caller = CB.getParent()->getParent(); 7992 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7993 "true" && !isMustTailCall) 7994 isTailCall = false; 7995 7996 // We can't tail call inside a function with a swifterror argument. Lowering 7997 // does not support this yet. It would have to move into the swifterror 7998 // register before the call. 7999 if (TLI.supportSwiftError() && 8000 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8001 isTailCall = false; 8002 } 8003 8004 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8005 TargetLowering::ArgListEntry Entry; 8006 const Value *V = *I; 8007 8008 // Skip empty types 8009 if (V->getType()->isEmptyTy()) 8010 continue; 8011 8012 SDValue ArgNode = getValue(V); 8013 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8014 8015 Entry.setAttributes(&CB, I - CB.arg_begin()); 8016 8017 // Use swifterror virtual register as input to the call. 8018 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8019 SwiftErrorVal = V; 8020 // We find the virtual register for the actual swifterror argument. 8021 // Instead of using the Value, we use the virtual register instead. 8022 Entry.Node = 8023 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8024 EVT(TLI.getPointerTy(DL))); 8025 } 8026 8027 Args.push_back(Entry); 8028 8029 // If we have an explicit sret argument that is an Instruction, (i.e., it 8030 // might point to function-local memory), we can't meaningfully tail-call. 8031 if (Entry.IsSRet && isa<Instruction>(V)) 8032 isTailCall = false; 8033 } 8034 8035 // If call site has a cfguardtarget operand bundle, create and add an 8036 // additional ArgListEntry. 8037 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8038 TargetLowering::ArgListEntry Entry; 8039 Value *V = Bundle->Inputs[0]; 8040 SDValue ArgNode = getValue(V); 8041 Entry.Node = ArgNode; 8042 Entry.Ty = V->getType(); 8043 Entry.IsCFGuardTarget = true; 8044 Args.push_back(Entry); 8045 } 8046 8047 // Check if target-independent constraints permit a tail call here. 8048 // Target-dependent constraints are checked within TLI->LowerCallTo. 8049 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8050 isTailCall = false; 8051 8052 // Disable tail calls if there is an swifterror argument. Targets have not 8053 // been updated to support tail calls. 8054 if (TLI.supportSwiftError() && SwiftErrorVal) 8055 isTailCall = false; 8056 8057 ConstantInt *CFIType = nullptr; 8058 if (CB.isIndirectCall()) { 8059 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8060 if (!TLI.supportKCFIBundles()) 8061 report_fatal_error( 8062 "Target doesn't support calls with kcfi operand bundles."); 8063 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8064 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8065 } 8066 } 8067 8068 TargetLowering::CallLoweringInfo CLI(DAG); 8069 CLI.setDebugLoc(getCurSDLoc()) 8070 .setChain(getRoot()) 8071 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8072 .setTailCall(isTailCall) 8073 .setConvergent(CB.isConvergent()) 8074 .setIsPreallocated( 8075 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8076 .setCFIType(CFIType); 8077 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8078 8079 if (Result.first.getNode()) { 8080 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8081 setValue(&CB, Result.first); 8082 } 8083 8084 // The last element of CLI.InVals has the SDValue for swifterror return. 8085 // Here we copy it to a virtual register and update SwiftErrorMap for 8086 // book-keeping. 8087 if (SwiftErrorVal && TLI.supportSwiftError()) { 8088 // Get the last element of InVals. 8089 SDValue Src = CLI.InVals.back(); 8090 Register VReg = 8091 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8092 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8093 DAG.setRoot(CopyNode); 8094 } 8095 } 8096 8097 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8098 SelectionDAGBuilder &Builder) { 8099 // Check to see if this load can be trivially constant folded, e.g. if the 8100 // input is from a string literal. 8101 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8102 // Cast pointer to the type we really want to load. 8103 Type *LoadTy = 8104 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8105 if (LoadVT.isVector()) 8106 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8107 8108 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8109 PointerType::getUnqual(LoadTy)); 8110 8111 if (const Constant *LoadCst = 8112 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8113 LoadTy, Builder.DAG.getDataLayout())) 8114 return Builder.getValue(LoadCst); 8115 } 8116 8117 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8118 // still constant memory, the input chain can be the entry node. 8119 SDValue Root; 8120 bool ConstantMemory = false; 8121 8122 // Do not serialize (non-volatile) loads of constant memory with anything. 8123 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8124 Root = Builder.DAG.getEntryNode(); 8125 ConstantMemory = true; 8126 } else { 8127 // Do not serialize non-volatile loads against each other. 8128 Root = Builder.DAG.getRoot(); 8129 } 8130 8131 SDValue Ptr = Builder.getValue(PtrVal); 8132 SDValue LoadVal = 8133 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8134 MachinePointerInfo(PtrVal), Align(1)); 8135 8136 if (!ConstantMemory) 8137 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8138 return LoadVal; 8139 } 8140 8141 /// Record the value for an instruction that produces an integer result, 8142 /// converting the type where necessary. 8143 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8144 SDValue Value, 8145 bool IsSigned) { 8146 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8147 I.getType(), true); 8148 if (IsSigned) 8149 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8150 else 8151 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8152 setValue(&I, Value); 8153 } 8154 8155 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8156 /// true and lower it. Otherwise return false, and it will be lowered like a 8157 /// normal call. 8158 /// The caller already checked that \p I calls the appropriate LibFunc with a 8159 /// correct prototype. 8160 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8161 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8162 const Value *Size = I.getArgOperand(2); 8163 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8164 if (CSize && CSize->getZExtValue() == 0) { 8165 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8166 I.getType(), true); 8167 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8168 return true; 8169 } 8170 8171 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8172 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8173 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8174 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8175 if (Res.first.getNode()) { 8176 processIntegerCallValue(I, Res.first, true); 8177 PendingLoads.push_back(Res.second); 8178 return true; 8179 } 8180 8181 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8182 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8183 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8184 return false; 8185 8186 // If the target has a fast compare for the given size, it will return a 8187 // preferred load type for that size. Require that the load VT is legal and 8188 // that the target supports unaligned loads of that type. Otherwise, return 8189 // INVALID. 8190 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8191 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8192 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8193 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8194 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8195 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8196 // TODO: Check alignment of src and dest ptrs. 8197 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8198 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8199 if (!TLI.isTypeLegal(LVT) || 8200 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8201 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8202 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8203 } 8204 8205 return LVT; 8206 }; 8207 8208 // This turns into unaligned loads. We only do this if the target natively 8209 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8210 // we'll only produce a small number of byte loads. 8211 MVT LoadVT; 8212 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8213 switch (NumBitsToCompare) { 8214 default: 8215 return false; 8216 case 16: 8217 LoadVT = MVT::i16; 8218 break; 8219 case 32: 8220 LoadVT = MVT::i32; 8221 break; 8222 case 64: 8223 case 128: 8224 case 256: 8225 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8226 break; 8227 } 8228 8229 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8230 return false; 8231 8232 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8233 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8234 8235 // Bitcast to a wide integer type if the loads are vectors. 8236 if (LoadVT.isVector()) { 8237 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8238 LoadL = DAG.getBitcast(CmpVT, LoadL); 8239 LoadR = DAG.getBitcast(CmpVT, LoadR); 8240 } 8241 8242 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8243 processIntegerCallValue(I, Cmp, false); 8244 return true; 8245 } 8246 8247 /// See if we can lower a memchr call into an optimized form. If so, return 8248 /// true and lower it. Otherwise return false, and it will be lowered like a 8249 /// normal call. 8250 /// The caller already checked that \p I calls the appropriate LibFunc with a 8251 /// correct prototype. 8252 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8253 const Value *Src = I.getArgOperand(0); 8254 const Value *Char = I.getArgOperand(1); 8255 const Value *Length = I.getArgOperand(2); 8256 8257 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8258 std::pair<SDValue, SDValue> Res = 8259 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8260 getValue(Src), getValue(Char), getValue(Length), 8261 MachinePointerInfo(Src)); 8262 if (Res.first.getNode()) { 8263 setValue(&I, Res.first); 8264 PendingLoads.push_back(Res.second); 8265 return true; 8266 } 8267 8268 return false; 8269 } 8270 8271 /// See if we can lower a mempcpy call into an optimized form. If so, return 8272 /// true and lower it. Otherwise return false, and it will be lowered like a 8273 /// normal call. 8274 /// The caller already checked that \p I calls the appropriate LibFunc with a 8275 /// correct prototype. 8276 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8277 SDValue Dst = getValue(I.getArgOperand(0)); 8278 SDValue Src = getValue(I.getArgOperand(1)); 8279 SDValue Size = getValue(I.getArgOperand(2)); 8280 8281 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8282 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8283 // DAG::getMemcpy needs Alignment to be defined. 8284 Align Alignment = std::min(DstAlign, SrcAlign); 8285 8286 SDLoc sdl = getCurSDLoc(); 8287 8288 // In the mempcpy context we need to pass in a false value for isTailCall 8289 // because the return pointer needs to be adjusted by the size of 8290 // the copied memory. 8291 SDValue Root = getMemoryRoot(); 8292 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8293 /*isTailCall=*/false, 8294 MachinePointerInfo(I.getArgOperand(0)), 8295 MachinePointerInfo(I.getArgOperand(1)), 8296 I.getAAMetadata()); 8297 assert(MC.getNode() != nullptr && 8298 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8299 DAG.setRoot(MC); 8300 8301 // Check if Size needs to be truncated or extended. 8302 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8303 8304 // Adjust return pointer to point just past the last dst byte. 8305 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8306 Dst, Size); 8307 setValue(&I, DstPlusSize); 8308 return true; 8309 } 8310 8311 /// See if we can lower a strcpy call into an optimized form. If so, return 8312 /// true and lower it, otherwise return false and it will be lowered like a 8313 /// normal call. 8314 /// The caller already checked that \p I calls the appropriate LibFunc with a 8315 /// correct prototype. 8316 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8317 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8318 8319 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8320 std::pair<SDValue, SDValue> Res = 8321 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8322 getValue(Arg0), getValue(Arg1), 8323 MachinePointerInfo(Arg0), 8324 MachinePointerInfo(Arg1), isStpcpy); 8325 if (Res.first.getNode()) { 8326 setValue(&I, Res.first); 8327 DAG.setRoot(Res.second); 8328 return true; 8329 } 8330 8331 return false; 8332 } 8333 8334 /// See if we can lower a strcmp call into an optimized form. If so, return 8335 /// true and lower it, otherwise return false and it will be lowered like a 8336 /// normal call. 8337 /// The caller already checked that \p I calls the appropriate LibFunc with a 8338 /// correct prototype. 8339 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8340 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8341 8342 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8343 std::pair<SDValue, SDValue> Res = 8344 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8345 getValue(Arg0), getValue(Arg1), 8346 MachinePointerInfo(Arg0), 8347 MachinePointerInfo(Arg1)); 8348 if (Res.first.getNode()) { 8349 processIntegerCallValue(I, Res.first, true); 8350 PendingLoads.push_back(Res.second); 8351 return true; 8352 } 8353 8354 return false; 8355 } 8356 8357 /// See if we can lower a strlen call into an optimized form. If so, return 8358 /// true and lower it, otherwise return false and it will be lowered like a 8359 /// normal call. 8360 /// The caller already checked that \p I calls the appropriate LibFunc with a 8361 /// correct prototype. 8362 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8363 const Value *Arg0 = I.getArgOperand(0); 8364 8365 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8366 std::pair<SDValue, SDValue> Res = 8367 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8368 getValue(Arg0), MachinePointerInfo(Arg0)); 8369 if (Res.first.getNode()) { 8370 processIntegerCallValue(I, Res.first, false); 8371 PendingLoads.push_back(Res.second); 8372 return true; 8373 } 8374 8375 return false; 8376 } 8377 8378 /// See if we can lower a strnlen call into an optimized form. If so, return 8379 /// true and lower it, otherwise return false and it will be lowered like a 8380 /// normal call. 8381 /// The caller already checked that \p I calls the appropriate LibFunc with a 8382 /// correct prototype. 8383 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8384 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8385 8386 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8387 std::pair<SDValue, SDValue> Res = 8388 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8389 getValue(Arg0), getValue(Arg1), 8390 MachinePointerInfo(Arg0)); 8391 if (Res.first.getNode()) { 8392 processIntegerCallValue(I, Res.first, false); 8393 PendingLoads.push_back(Res.second); 8394 return true; 8395 } 8396 8397 return false; 8398 } 8399 8400 /// See if we can lower a unary floating-point operation into an SDNode with 8401 /// the specified Opcode. If so, return true and lower it, otherwise return 8402 /// false and it will be lowered like a normal call. 8403 /// The caller already checked that \p I calls the appropriate LibFunc with a 8404 /// correct prototype. 8405 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8406 unsigned Opcode) { 8407 // We already checked this call's prototype; verify it doesn't modify errno. 8408 if (!I.onlyReadsMemory()) 8409 return false; 8410 8411 SDNodeFlags Flags; 8412 Flags.copyFMF(cast<FPMathOperator>(I)); 8413 8414 SDValue Tmp = getValue(I.getArgOperand(0)); 8415 setValue(&I, 8416 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8417 return true; 8418 } 8419 8420 /// See if we can lower a binary floating-point operation into an SDNode with 8421 /// the specified Opcode. If so, return true and lower it. Otherwise return 8422 /// false, and it will be lowered like a normal call. 8423 /// The caller already checked that \p I calls the appropriate LibFunc with a 8424 /// correct prototype. 8425 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8426 unsigned Opcode) { 8427 // We already checked this call's prototype; verify it doesn't modify errno. 8428 if (!I.onlyReadsMemory()) 8429 return false; 8430 8431 SDNodeFlags Flags; 8432 Flags.copyFMF(cast<FPMathOperator>(I)); 8433 8434 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8435 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8436 EVT VT = Tmp0.getValueType(); 8437 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8438 return true; 8439 } 8440 8441 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8442 // Handle inline assembly differently. 8443 if (I.isInlineAsm()) { 8444 visitInlineAsm(I); 8445 return; 8446 } 8447 8448 diagnoseDontCall(I); 8449 8450 if (Function *F = I.getCalledFunction()) { 8451 if (F->isDeclaration()) { 8452 // Is this an LLVM intrinsic or a target-specific intrinsic? 8453 unsigned IID = F->getIntrinsicID(); 8454 if (!IID) 8455 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8456 IID = II->getIntrinsicID(F); 8457 8458 if (IID) { 8459 visitIntrinsicCall(I, IID); 8460 return; 8461 } 8462 } 8463 8464 // Check for well-known libc/libm calls. If the function is internal, it 8465 // can't be a library call. Don't do the check if marked as nobuiltin for 8466 // some reason or the call site requires strict floating point semantics. 8467 LibFunc Func; 8468 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8469 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8470 LibInfo->hasOptimizedCodeGen(Func)) { 8471 switch (Func) { 8472 default: break; 8473 case LibFunc_bcmp: 8474 if (visitMemCmpBCmpCall(I)) 8475 return; 8476 break; 8477 case LibFunc_copysign: 8478 case LibFunc_copysignf: 8479 case LibFunc_copysignl: 8480 // We already checked this call's prototype; verify it doesn't modify 8481 // errno. 8482 if (I.onlyReadsMemory()) { 8483 SDValue LHS = getValue(I.getArgOperand(0)); 8484 SDValue RHS = getValue(I.getArgOperand(1)); 8485 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8486 LHS.getValueType(), LHS, RHS)); 8487 return; 8488 } 8489 break; 8490 case LibFunc_fabs: 8491 case LibFunc_fabsf: 8492 case LibFunc_fabsl: 8493 if (visitUnaryFloatCall(I, ISD::FABS)) 8494 return; 8495 break; 8496 case LibFunc_fmin: 8497 case LibFunc_fminf: 8498 case LibFunc_fminl: 8499 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8500 return; 8501 break; 8502 case LibFunc_fmax: 8503 case LibFunc_fmaxf: 8504 case LibFunc_fmaxl: 8505 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8506 return; 8507 break; 8508 case LibFunc_sin: 8509 case LibFunc_sinf: 8510 case LibFunc_sinl: 8511 if (visitUnaryFloatCall(I, ISD::FSIN)) 8512 return; 8513 break; 8514 case LibFunc_cos: 8515 case LibFunc_cosf: 8516 case LibFunc_cosl: 8517 if (visitUnaryFloatCall(I, ISD::FCOS)) 8518 return; 8519 break; 8520 case LibFunc_sqrt: 8521 case LibFunc_sqrtf: 8522 case LibFunc_sqrtl: 8523 case LibFunc_sqrt_finite: 8524 case LibFunc_sqrtf_finite: 8525 case LibFunc_sqrtl_finite: 8526 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8527 return; 8528 break; 8529 case LibFunc_floor: 8530 case LibFunc_floorf: 8531 case LibFunc_floorl: 8532 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8533 return; 8534 break; 8535 case LibFunc_nearbyint: 8536 case LibFunc_nearbyintf: 8537 case LibFunc_nearbyintl: 8538 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8539 return; 8540 break; 8541 case LibFunc_ceil: 8542 case LibFunc_ceilf: 8543 case LibFunc_ceill: 8544 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8545 return; 8546 break; 8547 case LibFunc_rint: 8548 case LibFunc_rintf: 8549 case LibFunc_rintl: 8550 if (visitUnaryFloatCall(I, ISD::FRINT)) 8551 return; 8552 break; 8553 case LibFunc_round: 8554 case LibFunc_roundf: 8555 case LibFunc_roundl: 8556 if (visitUnaryFloatCall(I, ISD::FROUND)) 8557 return; 8558 break; 8559 case LibFunc_trunc: 8560 case LibFunc_truncf: 8561 case LibFunc_truncl: 8562 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8563 return; 8564 break; 8565 case LibFunc_log2: 8566 case LibFunc_log2f: 8567 case LibFunc_log2l: 8568 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8569 return; 8570 break; 8571 case LibFunc_exp2: 8572 case LibFunc_exp2f: 8573 case LibFunc_exp2l: 8574 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8575 return; 8576 break; 8577 case LibFunc_memcmp: 8578 if (visitMemCmpBCmpCall(I)) 8579 return; 8580 break; 8581 case LibFunc_mempcpy: 8582 if (visitMemPCpyCall(I)) 8583 return; 8584 break; 8585 case LibFunc_memchr: 8586 if (visitMemChrCall(I)) 8587 return; 8588 break; 8589 case LibFunc_strcpy: 8590 if (visitStrCpyCall(I, false)) 8591 return; 8592 break; 8593 case LibFunc_stpcpy: 8594 if (visitStrCpyCall(I, true)) 8595 return; 8596 break; 8597 case LibFunc_strcmp: 8598 if (visitStrCmpCall(I)) 8599 return; 8600 break; 8601 case LibFunc_strlen: 8602 if (visitStrLenCall(I)) 8603 return; 8604 break; 8605 case LibFunc_strnlen: 8606 if (visitStrNLenCall(I)) 8607 return; 8608 break; 8609 } 8610 } 8611 } 8612 8613 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8614 // have to do anything here to lower funclet bundles. 8615 // CFGuardTarget bundles are lowered in LowerCallTo. 8616 assert(!I.hasOperandBundlesOtherThan( 8617 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8618 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8619 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8620 "Cannot lower calls with arbitrary operand bundles!"); 8621 8622 SDValue Callee = getValue(I.getCalledOperand()); 8623 8624 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8625 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8626 else 8627 // Check if we can potentially perform a tail call. More detailed checking 8628 // is be done within LowerCallTo, after more information about the call is 8629 // known. 8630 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8631 } 8632 8633 namespace { 8634 8635 /// AsmOperandInfo - This contains information for each constraint that we are 8636 /// lowering. 8637 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8638 public: 8639 /// CallOperand - If this is the result output operand or a clobber 8640 /// this is null, otherwise it is the incoming operand to the CallInst. 8641 /// This gets modified as the asm is processed. 8642 SDValue CallOperand; 8643 8644 /// AssignedRegs - If this is a register or register class operand, this 8645 /// contains the set of register corresponding to the operand. 8646 RegsForValue AssignedRegs; 8647 8648 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8649 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8650 } 8651 8652 /// Whether or not this operand accesses memory 8653 bool hasMemory(const TargetLowering &TLI) const { 8654 // Indirect operand accesses access memory. 8655 if (isIndirect) 8656 return true; 8657 8658 for (const auto &Code : Codes) 8659 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8660 return true; 8661 8662 return false; 8663 } 8664 }; 8665 8666 8667 } // end anonymous namespace 8668 8669 /// Make sure that the output operand \p OpInfo and its corresponding input 8670 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8671 /// out). 8672 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8673 SDISelAsmOperandInfo &MatchingOpInfo, 8674 SelectionDAG &DAG) { 8675 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8676 return; 8677 8678 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8679 const auto &TLI = DAG.getTargetLoweringInfo(); 8680 8681 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8682 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8683 OpInfo.ConstraintVT); 8684 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8685 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8686 MatchingOpInfo.ConstraintVT); 8687 if ((OpInfo.ConstraintVT.isInteger() != 8688 MatchingOpInfo.ConstraintVT.isInteger()) || 8689 (MatchRC.second != InputRC.second)) { 8690 // FIXME: error out in a more elegant fashion 8691 report_fatal_error("Unsupported asm: input constraint" 8692 " with a matching output constraint of" 8693 " incompatible type!"); 8694 } 8695 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8696 } 8697 8698 /// Get a direct memory input to behave well as an indirect operand. 8699 /// This may introduce stores, hence the need for a \p Chain. 8700 /// \return The (possibly updated) chain. 8701 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8702 SDISelAsmOperandInfo &OpInfo, 8703 SelectionDAG &DAG) { 8704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8705 8706 // If we don't have an indirect input, put it in the constpool if we can, 8707 // otherwise spill it to a stack slot. 8708 // TODO: This isn't quite right. We need to handle these according to 8709 // the addressing mode that the constraint wants. Also, this may take 8710 // an additional register for the computation and we don't want that 8711 // either. 8712 8713 // If the operand is a float, integer, or vector constant, spill to a 8714 // constant pool entry to get its address. 8715 const Value *OpVal = OpInfo.CallOperandVal; 8716 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8717 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8718 OpInfo.CallOperand = DAG.getConstantPool( 8719 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8720 return Chain; 8721 } 8722 8723 // Otherwise, create a stack slot and emit a store to it before the asm. 8724 Type *Ty = OpVal->getType(); 8725 auto &DL = DAG.getDataLayout(); 8726 uint64_t TySize = DL.getTypeAllocSize(Ty); 8727 MachineFunction &MF = DAG.getMachineFunction(); 8728 int SSFI = MF.getFrameInfo().CreateStackObject( 8729 TySize, DL.getPrefTypeAlign(Ty), false); 8730 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8731 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8732 MachinePointerInfo::getFixedStack(MF, SSFI), 8733 TLI.getMemValueType(DL, Ty)); 8734 OpInfo.CallOperand = StackSlot; 8735 8736 return Chain; 8737 } 8738 8739 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8740 /// specified operand. We prefer to assign virtual registers, to allow the 8741 /// register allocator to handle the assignment process. However, if the asm 8742 /// uses features that we can't model on machineinstrs, we have SDISel do the 8743 /// allocation. This produces generally horrible, but correct, code. 8744 /// 8745 /// OpInfo describes the operand 8746 /// RefOpInfo describes the matching operand if any, the operand otherwise 8747 static std::optional<unsigned> 8748 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8749 SDISelAsmOperandInfo &OpInfo, 8750 SDISelAsmOperandInfo &RefOpInfo) { 8751 LLVMContext &Context = *DAG.getContext(); 8752 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8753 8754 MachineFunction &MF = DAG.getMachineFunction(); 8755 SmallVector<unsigned, 4> Regs; 8756 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8757 8758 // No work to do for memory/address operands. 8759 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8760 OpInfo.ConstraintType == TargetLowering::C_Address) 8761 return std::nullopt; 8762 8763 // If this is a constraint for a single physreg, or a constraint for a 8764 // register class, find it. 8765 unsigned AssignedReg; 8766 const TargetRegisterClass *RC; 8767 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8768 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8769 // RC is unset only on failure. Return immediately. 8770 if (!RC) 8771 return std::nullopt; 8772 8773 // Get the actual register value type. This is important, because the user 8774 // may have asked for (e.g.) the AX register in i32 type. We need to 8775 // remember that AX is actually i16 to get the right extension. 8776 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8777 8778 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8779 // If this is an FP operand in an integer register (or visa versa), or more 8780 // generally if the operand value disagrees with the register class we plan 8781 // to stick it in, fix the operand type. 8782 // 8783 // If this is an input value, the bitcast to the new type is done now. 8784 // Bitcast for output value is done at the end of visitInlineAsm(). 8785 if ((OpInfo.Type == InlineAsm::isOutput || 8786 OpInfo.Type == InlineAsm::isInput) && 8787 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8788 // Try to convert to the first EVT that the reg class contains. If the 8789 // types are identical size, use a bitcast to convert (e.g. two differing 8790 // vector types). Note: output bitcast is done at the end of 8791 // visitInlineAsm(). 8792 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8793 // Exclude indirect inputs while they are unsupported because the code 8794 // to perform the load is missing and thus OpInfo.CallOperand still 8795 // refers to the input address rather than the pointed-to value. 8796 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8797 OpInfo.CallOperand = 8798 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8799 OpInfo.ConstraintVT = RegVT; 8800 // If the operand is an FP value and we want it in integer registers, 8801 // use the corresponding integer type. This turns an f64 value into 8802 // i64, which can be passed with two i32 values on a 32-bit machine. 8803 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8804 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8805 if (OpInfo.Type == InlineAsm::isInput) 8806 OpInfo.CallOperand = 8807 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8808 OpInfo.ConstraintVT = VT; 8809 } 8810 } 8811 } 8812 8813 // No need to allocate a matching input constraint since the constraint it's 8814 // matching to has already been allocated. 8815 if (OpInfo.isMatchingInputConstraint()) 8816 return std::nullopt; 8817 8818 EVT ValueVT = OpInfo.ConstraintVT; 8819 if (OpInfo.ConstraintVT == MVT::Other) 8820 ValueVT = RegVT; 8821 8822 // Initialize NumRegs. 8823 unsigned NumRegs = 1; 8824 if (OpInfo.ConstraintVT != MVT::Other) 8825 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8826 8827 // If this is a constraint for a specific physical register, like {r17}, 8828 // assign it now. 8829 8830 // If this associated to a specific register, initialize iterator to correct 8831 // place. If virtual, make sure we have enough registers 8832 8833 // Initialize iterator if necessary 8834 TargetRegisterClass::iterator I = RC->begin(); 8835 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8836 8837 // Do not check for single registers. 8838 if (AssignedReg) { 8839 I = std::find(I, RC->end(), AssignedReg); 8840 if (I == RC->end()) { 8841 // RC does not contain the selected register, which indicates a 8842 // mismatch between the register and the required type/bitwidth. 8843 return {AssignedReg}; 8844 } 8845 } 8846 8847 for (; NumRegs; --NumRegs, ++I) { 8848 assert(I != RC->end() && "Ran out of registers to allocate!"); 8849 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8850 Regs.push_back(R); 8851 } 8852 8853 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8854 return std::nullopt; 8855 } 8856 8857 static unsigned 8858 findMatchingInlineAsmOperand(unsigned OperandNo, 8859 const std::vector<SDValue> &AsmNodeOperands) { 8860 // Scan until we find the definition we already emitted of this operand. 8861 unsigned CurOp = InlineAsm::Op_FirstOperand; 8862 for (; OperandNo; --OperandNo) { 8863 // Advance to the next operand. 8864 unsigned OpFlag = 8865 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8866 assert((InlineAsm::isRegDefKind(OpFlag) || 8867 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8868 InlineAsm::isMemKind(OpFlag)) && 8869 "Skipped past definitions?"); 8870 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8871 } 8872 return CurOp; 8873 } 8874 8875 namespace { 8876 8877 class ExtraFlags { 8878 unsigned Flags = 0; 8879 8880 public: 8881 explicit ExtraFlags(const CallBase &Call) { 8882 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8883 if (IA->hasSideEffects()) 8884 Flags |= InlineAsm::Extra_HasSideEffects; 8885 if (IA->isAlignStack()) 8886 Flags |= InlineAsm::Extra_IsAlignStack; 8887 if (Call.isConvergent()) 8888 Flags |= InlineAsm::Extra_IsConvergent; 8889 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8890 } 8891 8892 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8893 // Ideally, we would only check against memory constraints. However, the 8894 // meaning of an Other constraint can be target-specific and we can't easily 8895 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8896 // for Other constraints as well. 8897 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8898 OpInfo.ConstraintType == TargetLowering::C_Other) { 8899 if (OpInfo.Type == InlineAsm::isInput) 8900 Flags |= InlineAsm::Extra_MayLoad; 8901 else if (OpInfo.Type == InlineAsm::isOutput) 8902 Flags |= InlineAsm::Extra_MayStore; 8903 else if (OpInfo.Type == InlineAsm::isClobber) 8904 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8905 } 8906 } 8907 8908 unsigned get() const { return Flags; } 8909 }; 8910 8911 } // end anonymous namespace 8912 8913 static bool isFunction(SDValue Op) { 8914 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8915 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8916 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8917 8918 // In normal "call dllimport func" instruction (non-inlineasm) it force 8919 // indirect access by specifing call opcode. And usually specially print 8920 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8921 // not do in this way now. (In fact, this is similar with "Data Access" 8922 // action). So here we ignore dllimport function. 8923 if (Fn && !Fn->hasDLLImportStorageClass()) 8924 return true; 8925 } 8926 } 8927 return false; 8928 } 8929 8930 /// visitInlineAsm - Handle a call to an InlineAsm object. 8931 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8932 const BasicBlock *EHPadBB) { 8933 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8934 8935 /// ConstraintOperands - Information about all of the constraints. 8936 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8937 8938 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8939 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8940 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8941 8942 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8943 // AsmDialect, MayLoad, MayStore). 8944 bool HasSideEffect = IA->hasSideEffects(); 8945 ExtraFlags ExtraInfo(Call); 8946 8947 for (auto &T : TargetConstraints) { 8948 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8949 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8950 8951 if (OpInfo.CallOperandVal) 8952 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8953 8954 if (!HasSideEffect) 8955 HasSideEffect = OpInfo.hasMemory(TLI); 8956 8957 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8958 // FIXME: Could we compute this on OpInfo rather than T? 8959 8960 // Compute the constraint code and ConstraintType to use. 8961 TLI.ComputeConstraintToUse(T, SDValue()); 8962 8963 if (T.ConstraintType == TargetLowering::C_Immediate && 8964 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8965 // We've delayed emitting a diagnostic like the "n" constraint because 8966 // inlining could cause an integer showing up. 8967 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8968 "' expects an integer constant " 8969 "expression"); 8970 8971 ExtraInfo.update(T); 8972 } 8973 8974 // We won't need to flush pending loads if this asm doesn't touch 8975 // memory and is nonvolatile. 8976 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8977 8978 bool EmitEHLabels = isa<InvokeInst>(Call); 8979 if (EmitEHLabels) { 8980 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8981 } 8982 bool IsCallBr = isa<CallBrInst>(Call); 8983 8984 if (IsCallBr || EmitEHLabels) { 8985 // If this is a callbr or invoke we need to flush pending exports since 8986 // inlineasm_br and invoke are terminators. 8987 // We need to do this before nodes are glued to the inlineasm_br node. 8988 Chain = getControlRoot(); 8989 } 8990 8991 MCSymbol *BeginLabel = nullptr; 8992 if (EmitEHLabels) { 8993 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8994 } 8995 8996 int OpNo = -1; 8997 SmallVector<StringRef> AsmStrs; 8998 IA->collectAsmStrs(AsmStrs); 8999 9000 // Second pass over the constraints: compute which constraint option to use. 9001 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9002 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9003 OpNo++; 9004 9005 // If this is an output operand with a matching input operand, look up the 9006 // matching input. If their types mismatch, e.g. one is an integer, the 9007 // other is floating point, or their sizes are different, flag it as an 9008 // error. 9009 if (OpInfo.hasMatchingInput()) { 9010 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9011 patchMatchingInput(OpInfo, Input, DAG); 9012 } 9013 9014 // Compute the constraint code and ConstraintType to use. 9015 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9016 9017 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9018 OpInfo.Type == InlineAsm::isClobber) || 9019 OpInfo.ConstraintType == TargetLowering::C_Address) 9020 continue; 9021 9022 // In Linux PIC model, there are 4 cases about value/label addressing: 9023 // 9024 // 1: Function call or Label jmp inside the module. 9025 // 2: Data access (such as global variable, static variable) inside module. 9026 // 3: Function call or Label jmp outside the module. 9027 // 4: Data access (such as global variable) outside the module. 9028 // 9029 // Due to current llvm inline asm architecture designed to not "recognize" 9030 // the asm code, there are quite troubles for us to treat mem addressing 9031 // differently for same value/adress used in different instuctions. 9032 // For example, in pic model, call a func may in plt way or direclty 9033 // pc-related, but lea/mov a function adress may use got. 9034 // 9035 // Here we try to "recognize" function call for the case 1 and case 3 in 9036 // inline asm. And try to adjust the constraint for them. 9037 // 9038 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9039 // label, so here we don't handle jmp function label now, but we need to 9040 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9041 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9042 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9043 TM.getCodeModel() != CodeModel::Large) { 9044 OpInfo.isIndirect = false; 9045 OpInfo.ConstraintType = TargetLowering::C_Address; 9046 } 9047 9048 // If this is a memory input, and if the operand is not indirect, do what we 9049 // need to provide an address for the memory input. 9050 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9051 !OpInfo.isIndirect) { 9052 assert((OpInfo.isMultipleAlternative || 9053 (OpInfo.Type == InlineAsm::isInput)) && 9054 "Can only indirectify direct input operands!"); 9055 9056 // Memory operands really want the address of the value. 9057 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9058 9059 // There is no longer a Value* corresponding to this operand. 9060 OpInfo.CallOperandVal = nullptr; 9061 9062 // It is now an indirect operand. 9063 OpInfo.isIndirect = true; 9064 } 9065 9066 } 9067 9068 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9069 std::vector<SDValue> AsmNodeOperands; 9070 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9071 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9072 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9073 9074 // If we have a !srcloc metadata node associated with it, we want to attach 9075 // this to the ultimately generated inline asm machineinstr. To do this, we 9076 // pass in the third operand as this (potentially null) inline asm MDNode. 9077 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9078 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9079 9080 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9081 // bits as operand 3. 9082 AsmNodeOperands.push_back(DAG.getTargetConstant( 9083 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9084 9085 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9086 // this, assign virtual and physical registers for inputs and otput. 9087 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9088 // Assign Registers. 9089 SDISelAsmOperandInfo &RefOpInfo = 9090 OpInfo.isMatchingInputConstraint() 9091 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9092 : OpInfo; 9093 const auto RegError = 9094 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9095 if (RegError) { 9096 const MachineFunction &MF = DAG.getMachineFunction(); 9097 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9098 const char *RegName = TRI.getName(*RegError); 9099 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9100 "' allocated for constraint '" + 9101 Twine(OpInfo.ConstraintCode) + 9102 "' does not match required type"); 9103 return; 9104 } 9105 9106 auto DetectWriteToReservedRegister = [&]() { 9107 const MachineFunction &MF = DAG.getMachineFunction(); 9108 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9109 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9110 if (Register::isPhysicalRegister(Reg) && 9111 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9112 const char *RegName = TRI.getName(Reg); 9113 emitInlineAsmError(Call, "write to reserved register '" + 9114 Twine(RegName) + "'"); 9115 return true; 9116 } 9117 } 9118 return false; 9119 }; 9120 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9121 (OpInfo.Type == InlineAsm::isInput && 9122 !OpInfo.isMatchingInputConstraint())) && 9123 "Only address as input operand is allowed."); 9124 9125 switch (OpInfo.Type) { 9126 case InlineAsm::isOutput: 9127 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9128 unsigned ConstraintID = 9129 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9130 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9131 "Failed to convert memory constraint code to constraint id."); 9132 9133 // Add information to the INLINEASM node to know about this output. 9134 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9135 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9136 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9137 MVT::i32)); 9138 AsmNodeOperands.push_back(OpInfo.CallOperand); 9139 } else { 9140 // Otherwise, this outputs to a register (directly for C_Register / 9141 // C_RegisterClass, and a target-defined fashion for 9142 // C_Immediate/C_Other). Find a register that we can use. 9143 if (OpInfo.AssignedRegs.Regs.empty()) { 9144 emitInlineAsmError( 9145 Call, "couldn't allocate output register for constraint '" + 9146 Twine(OpInfo.ConstraintCode) + "'"); 9147 return; 9148 } 9149 9150 if (DetectWriteToReservedRegister()) 9151 return; 9152 9153 // Add information to the INLINEASM node to know that this register is 9154 // set. 9155 OpInfo.AssignedRegs.AddInlineAsmOperands( 9156 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9157 : InlineAsm::Kind_RegDef, 9158 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9159 } 9160 break; 9161 9162 case InlineAsm::isInput: 9163 case InlineAsm::isLabel: { 9164 SDValue InOperandVal = OpInfo.CallOperand; 9165 9166 if (OpInfo.isMatchingInputConstraint()) { 9167 // If this is required to match an output register we have already set, 9168 // just use its register. 9169 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9170 AsmNodeOperands); 9171 unsigned OpFlag = 9172 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9173 if (InlineAsm::isRegDefKind(OpFlag) || 9174 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9175 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9176 if (OpInfo.isIndirect) { 9177 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9178 emitInlineAsmError(Call, "inline asm not supported yet: " 9179 "don't know how to handle tied " 9180 "indirect register inputs"); 9181 return; 9182 } 9183 9184 SmallVector<unsigned, 4> Regs; 9185 MachineFunction &MF = DAG.getMachineFunction(); 9186 MachineRegisterInfo &MRI = MF.getRegInfo(); 9187 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9188 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9189 Register TiedReg = R->getReg(); 9190 MVT RegVT = R->getSimpleValueType(0); 9191 const TargetRegisterClass *RC = 9192 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9193 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9194 : TRI.getMinimalPhysRegClass(TiedReg); 9195 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9196 for (unsigned i = 0; i != NumRegs; ++i) 9197 Regs.push_back(MRI.createVirtualRegister(RC)); 9198 9199 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9200 9201 SDLoc dl = getCurSDLoc(); 9202 // Use the produced MatchedRegs object to 9203 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9204 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9205 true, OpInfo.getMatchedOperand(), dl, 9206 DAG, AsmNodeOperands); 9207 break; 9208 } 9209 9210 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9211 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9212 "Unexpected number of operands"); 9213 // Add information to the INLINEASM node to know about this input. 9214 // See InlineAsm.h isUseOperandTiedToDef. 9215 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9216 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9217 OpInfo.getMatchedOperand()); 9218 AsmNodeOperands.push_back(DAG.getTargetConstant( 9219 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9220 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9221 break; 9222 } 9223 9224 // Treat indirect 'X' constraint as memory. 9225 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9226 OpInfo.isIndirect) 9227 OpInfo.ConstraintType = TargetLowering::C_Memory; 9228 9229 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9230 OpInfo.ConstraintType == TargetLowering::C_Other) { 9231 std::vector<SDValue> Ops; 9232 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9233 Ops, DAG); 9234 if (Ops.empty()) { 9235 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9236 if (isa<ConstantSDNode>(InOperandVal)) { 9237 emitInlineAsmError(Call, "value out of range for constraint '" + 9238 Twine(OpInfo.ConstraintCode) + "'"); 9239 return; 9240 } 9241 9242 emitInlineAsmError(Call, 9243 "invalid operand for inline asm constraint '" + 9244 Twine(OpInfo.ConstraintCode) + "'"); 9245 return; 9246 } 9247 9248 // Add information to the INLINEASM node to know about this input. 9249 unsigned ResOpType = 9250 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9251 AsmNodeOperands.push_back(DAG.getTargetConstant( 9252 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9253 llvm::append_range(AsmNodeOperands, Ops); 9254 break; 9255 } 9256 9257 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9258 assert((OpInfo.isIndirect || 9259 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9260 "Operand must be indirect to be a mem!"); 9261 assert(InOperandVal.getValueType() == 9262 TLI.getPointerTy(DAG.getDataLayout()) && 9263 "Memory operands expect pointer values"); 9264 9265 unsigned ConstraintID = 9266 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9267 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9268 "Failed to convert memory constraint code to constraint id."); 9269 9270 // Add information to the INLINEASM node to know about this input. 9271 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9272 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9273 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9274 getCurSDLoc(), 9275 MVT::i32)); 9276 AsmNodeOperands.push_back(InOperandVal); 9277 break; 9278 } 9279 9280 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9281 assert(InOperandVal.getValueType() == 9282 TLI.getPointerTy(DAG.getDataLayout()) && 9283 "Address operands expect pointer values"); 9284 9285 unsigned ConstraintID = 9286 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9287 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9288 "Failed to convert memory constraint code to constraint id."); 9289 9290 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9291 9292 SDValue AsmOp = InOperandVal; 9293 if (isFunction(InOperandVal)) { 9294 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9295 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9296 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9297 InOperandVal.getValueType(), 9298 GA->getOffset()); 9299 } 9300 9301 // Add information to the INLINEASM node to know about this input. 9302 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9303 9304 AsmNodeOperands.push_back( 9305 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9306 9307 AsmNodeOperands.push_back(AsmOp); 9308 break; 9309 } 9310 9311 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9312 OpInfo.ConstraintType == TargetLowering::C_Register) && 9313 "Unknown constraint type!"); 9314 9315 // TODO: Support this. 9316 if (OpInfo.isIndirect) { 9317 emitInlineAsmError( 9318 Call, "Don't know how to handle indirect register inputs yet " 9319 "for constraint '" + 9320 Twine(OpInfo.ConstraintCode) + "'"); 9321 return; 9322 } 9323 9324 // Copy the input into the appropriate registers. 9325 if (OpInfo.AssignedRegs.Regs.empty()) { 9326 emitInlineAsmError(Call, 9327 "couldn't allocate input reg for constraint '" + 9328 Twine(OpInfo.ConstraintCode) + "'"); 9329 return; 9330 } 9331 9332 if (DetectWriteToReservedRegister()) 9333 return; 9334 9335 SDLoc dl = getCurSDLoc(); 9336 9337 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9338 &Call); 9339 9340 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9341 dl, DAG, AsmNodeOperands); 9342 break; 9343 } 9344 case InlineAsm::isClobber: 9345 // Add the clobbered value to the operand list, so that the register 9346 // allocator is aware that the physreg got clobbered. 9347 if (!OpInfo.AssignedRegs.Regs.empty()) 9348 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9349 false, 0, getCurSDLoc(), DAG, 9350 AsmNodeOperands); 9351 break; 9352 } 9353 } 9354 9355 // Finish up input operands. Set the input chain and add the flag last. 9356 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9357 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9358 9359 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9360 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9361 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9362 Glue = Chain.getValue(1); 9363 9364 // Do additional work to generate outputs. 9365 9366 SmallVector<EVT, 1> ResultVTs; 9367 SmallVector<SDValue, 1> ResultValues; 9368 SmallVector<SDValue, 8> OutChains; 9369 9370 llvm::Type *CallResultType = Call.getType(); 9371 ArrayRef<Type *> ResultTypes; 9372 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9373 ResultTypes = StructResult->elements(); 9374 else if (!CallResultType->isVoidTy()) 9375 ResultTypes = ArrayRef(CallResultType); 9376 9377 auto CurResultType = ResultTypes.begin(); 9378 auto handleRegAssign = [&](SDValue V) { 9379 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9380 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9381 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9382 ++CurResultType; 9383 // If the type of the inline asm call site return value is different but has 9384 // same size as the type of the asm output bitcast it. One example of this 9385 // is for vectors with different width / number of elements. This can 9386 // happen for register classes that can contain multiple different value 9387 // types. The preg or vreg allocated may not have the same VT as was 9388 // expected. 9389 // 9390 // This can also happen for a return value that disagrees with the register 9391 // class it is put in, eg. a double in a general-purpose register on a 9392 // 32-bit machine. 9393 if (ResultVT != V.getValueType() && 9394 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9395 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9396 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9397 V.getValueType().isInteger()) { 9398 // If a result value was tied to an input value, the computed result 9399 // may have a wider width than the expected result. Extract the 9400 // relevant portion. 9401 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9402 } 9403 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9404 ResultVTs.push_back(ResultVT); 9405 ResultValues.push_back(V); 9406 }; 9407 9408 // Deal with output operands. 9409 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9410 if (OpInfo.Type == InlineAsm::isOutput) { 9411 SDValue Val; 9412 // Skip trivial output operands. 9413 if (OpInfo.AssignedRegs.Regs.empty()) 9414 continue; 9415 9416 switch (OpInfo.ConstraintType) { 9417 case TargetLowering::C_Register: 9418 case TargetLowering::C_RegisterClass: 9419 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9420 Chain, &Glue, &Call); 9421 break; 9422 case TargetLowering::C_Immediate: 9423 case TargetLowering::C_Other: 9424 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9425 OpInfo, DAG); 9426 break; 9427 case TargetLowering::C_Memory: 9428 break; // Already handled. 9429 case TargetLowering::C_Address: 9430 break; // Silence warning. 9431 case TargetLowering::C_Unknown: 9432 assert(false && "Unexpected unknown constraint"); 9433 } 9434 9435 // Indirect output manifest as stores. Record output chains. 9436 if (OpInfo.isIndirect) { 9437 const Value *Ptr = OpInfo.CallOperandVal; 9438 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9439 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9440 MachinePointerInfo(Ptr)); 9441 OutChains.push_back(Store); 9442 } else { 9443 // generate CopyFromRegs to associated registers. 9444 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9445 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9446 for (const SDValue &V : Val->op_values()) 9447 handleRegAssign(V); 9448 } else 9449 handleRegAssign(Val); 9450 } 9451 } 9452 } 9453 9454 // Set results. 9455 if (!ResultValues.empty()) { 9456 assert(CurResultType == ResultTypes.end() && 9457 "Mismatch in number of ResultTypes"); 9458 assert(ResultValues.size() == ResultTypes.size() && 9459 "Mismatch in number of output operands in asm result"); 9460 9461 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9462 DAG.getVTList(ResultVTs), ResultValues); 9463 setValue(&Call, V); 9464 } 9465 9466 // Collect store chains. 9467 if (!OutChains.empty()) 9468 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9469 9470 if (EmitEHLabels) { 9471 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9472 } 9473 9474 // Only Update Root if inline assembly has a memory effect. 9475 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9476 EmitEHLabels) 9477 DAG.setRoot(Chain); 9478 } 9479 9480 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9481 const Twine &Message) { 9482 LLVMContext &Ctx = *DAG.getContext(); 9483 Ctx.emitError(&Call, Message); 9484 9485 // Make sure we leave the DAG in a valid state 9486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9487 SmallVector<EVT, 1> ValueVTs; 9488 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9489 9490 if (ValueVTs.empty()) 9491 return; 9492 9493 SmallVector<SDValue, 1> Ops; 9494 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9495 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9496 9497 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9498 } 9499 9500 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9501 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9502 MVT::Other, getRoot(), 9503 getValue(I.getArgOperand(0)), 9504 DAG.getSrcValue(I.getArgOperand(0)))); 9505 } 9506 9507 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9509 const DataLayout &DL = DAG.getDataLayout(); 9510 SDValue V = DAG.getVAArg( 9511 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9512 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9513 DL.getABITypeAlign(I.getType()).value()); 9514 DAG.setRoot(V.getValue(1)); 9515 9516 if (I.getType()->isPointerTy()) 9517 V = DAG.getPtrExtOrTrunc( 9518 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9519 setValue(&I, V); 9520 } 9521 9522 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9523 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9524 MVT::Other, getRoot(), 9525 getValue(I.getArgOperand(0)), 9526 DAG.getSrcValue(I.getArgOperand(0)))); 9527 } 9528 9529 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9530 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9531 MVT::Other, getRoot(), 9532 getValue(I.getArgOperand(0)), 9533 getValue(I.getArgOperand(1)), 9534 DAG.getSrcValue(I.getArgOperand(0)), 9535 DAG.getSrcValue(I.getArgOperand(1)))); 9536 } 9537 9538 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9539 const Instruction &I, 9540 SDValue Op) { 9541 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9542 if (!Range) 9543 return Op; 9544 9545 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9546 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9547 return Op; 9548 9549 APInt Lo = CR.getUnsignedMin(); 9550 if (!Lo.isMinValue()) 9551 return Op; 9552 9553 APInt Hi = CR.getUnsignedMax(); 9554 unsigned Bits = std::max(Hi.getActiveBits(), 9555 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9556 9557 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9558 9559 SDLoc SL = getCurSDLoc(); 9560 9561 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9562 DAG.getValueType(SmallVT)); 9563 unsigned NumVals = Op.getNode()->getNumValues(); 9564 if (NumVals == 1) 9565 return ZExt; 9566 9567 SmallVector<SDValue, 4> Ops; 9568 9569 Ops.push_back(ZExt); 9570 for (unsigned I = 1; I != NumVals; ++I) 9571 Ops.push_back(Op.getValue(I)); 9572 9573 return DAG.getMergeValues(Ops, SL); 9574 } 9575 9576 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9577 /// the call being lowered. 9578 /// 9579 /// This is a helper for lowering intrinsics that follow a target calling 9580 /// convention or require stack pointer adjustment. Only a subset of the 9581 /// intrinsic's operands need to participate in the calling convention. 9582 void SelectionDAGBuilder::populateCallLoweringInfo( 9583 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9584 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9585 bool IsPatchPoint) { 9586 TargetLowering::ArgListTy Args; 9587 Args.reserve(NumArgs); 9588 9589 // Populate the argument list. 9590 // Attributes for args start at offset 1, after the return attribute. 9591 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9592 ArgI != ArgE; ++ArgI) { 9593 const Value *V = Call->getOperand(ArgI); 9594 9595 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9596 9597 TargetLowering::ArgListEntry Entry; 9598 Entry.Node = getValue(V); 9599 Entry.Ty = V->getType(); 9600 Entry.setAttributes(Call, ArgI); 9601 Args.push_back(Entry); 9602 } 9603 9604 CLI.setDebugLoc(getCurSDLoc()) 9605 .setChain(getRoot()) 9606 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9607 .setDiscardResult(Call->use_empty()) 9608 .setIsPatchPoint(IsPatchPoint) 9609 .setIsPreallocated( 9610 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9611 } 9612 9613 /// Add a stack map intrinsic call's live variable operands to a stackmap 9614 /// or patchpoint target node's operand list. 9615 /// 9616 /// Constants are converted to TargetConstants purely as an optimization to 9617 /// avoid constant materialization and register allocation. 9618 /// 9619 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9620 /// generate addess computation nodes, and so FinalizeISel can convert the 9621 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9622 /// address materialization and register allocation, but may also be required 9623 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9624 /// alloca in the entry block, then the runtime may assume that the alloca's 9625 /// StackMap location can be read immediately after compilation and that the 9626 /// location is valid at any point during execution (this is similar to the 9627 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9628 /// only available in a register, then the runtime would need to trap when 9629 /// execution reaches the StackMap in order to read the alloca's location. 9630 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9631 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9632 SelectionDAGBuilder &Builder) { 9633 SelectionDAG &DAG = Builder.DAG; 9634 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9635 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9636 9637 // Things on the stack are pointer-typed, meaning that they are already 9638 // legal and can be emitted directly to target nodes. 9639 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9640 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9641 } else { 9642 // Otherwise emit a target independent node to be legalised. 9643 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9644 } 9645 } 9646 } 9647 9648 /// Lower llvm.experimental.stackmap. 9649 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9650 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9651 // [live variables...]) 9652 9653 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9654 9655 SDValue Chain, InGlue, Callee; 9656 SmallVector<SDValue, 32> Ops; 9657 9658 SDLoc DL = getCurSDLoc(); 9659 Callee = getValue(CI.getCalledOperand()); 9660 9661 // The stackmap intrinsic only records the live variables (the arguments 9662 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9663 // intrinsic, this won't be lowered to a function call. This means we don't 9664 // have to worry about calling conventions and target specific lowering code. 9665 // Instead we perform the call lowering right here. 9666 // 9667 // chain, flag = CALLSEQ_START(chain, 0, 0) 9668 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9669 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9670 // 9671 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9672 InGlue = Chain.getValue(1); 9673 9674 // Add the STACKMAP operands, starting with DAG house-keeping. 9675 Ops.push_back(Chain); 9676 Ops.push_back(InGlue); 9677 9678 // Add the <id>, <numShadowBytes> operands. 9679 // 9680 // These do not require legalisation, and can be emitted directly to target 9681 // constant nodes. 9682 SDValue ID = getValue(CI.getArgOperand(0)); 9683 assert(ID.getValueType() == MVT::i64); 9684 SDValue IDConst = DAG.getTargetConstant( 9685 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9686 Ops.push_back(IDConst); 9687 9688 SDValue Shad = getValue(CI.getArgOperand(1)); 9689 assert(Shad.getValueType() == MVT::i32); 9690 SDValue ShadConst = DAG.getTargetConstant( 9691 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9692 Ops.push_back(ShadConst); 9693 9694 // Add the live variables. 9695 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9696 9697 // Create the STACKMAP node. 9698 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9699 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9700 InGlue = Chain.getValue(1); 9701 9702 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9703 9704 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9705 9706 // Set the root to the target-lowered call chain. 9707 DAG.setRoot(Chain); 9708 9709 // Inform the Frame Information that we have a stackmap in this function. 9710 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9711 } 9712 9713 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9714 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9715 const BasicBlock *EHPadBB) { 9716 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9717 // i32 <numBytes>, 9718 // i8* <target>, 9719 // i32 <numArgs>, 9720 // [Args...], 9721 // [live variables...]) 9722 9723 CallingConv::ID CC = CB.getCallingConv(); 9724 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9725 bool HasDef = !CB.getType()->isVoidTy(); 9726 SDLoc dl = getCurSDLoc(); 9727 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9728 9729 // Handle immediate and symbolic callees. 9730 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9731 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9732 /*isTarget=*/true); 9733 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9734 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9735 SDLoc(SymbolicCallee), 9736 SymbolicCallee->getValueType(0)); 9737 9738 // Get the real number of arguments participating in the call <numArgs> 9739 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9740 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9741 9742 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9743 // Intrinsics include all meta-operands up to but not including CC. 9744 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9745 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9746 "Not enough arguments provided to the patchpoint intrinsic"); 9747 9748 // For AnyRegCC the arguments are lowered later on manually. 9749 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9750 Type *ReturnTy = 9751 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9752 9753 TargetLowering::CallLoweringInfo CLI(DAG); 9754 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9755 ReturnTy, true); 9756 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9757 9758 SDNode *CallEnd = Result.second.getNode(); 9759 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9760 CallEnd = CallEnd->getOperand(0).getNode(); 9761 9762 /// Get a call instruction from the call sequence chain. 9763 /// Tail calls are not allowed. 9764 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9765 "Expected a callseq node."); 9766 SDNode *Call = CallEnd->getOperand(0).getNode(); 9767 bool HasGlue = Call->getGluedNode(); 9768 9769 // Replace the target specific call node with the patchable intrinsic. 9770 SmallVector<SDValue, 8> Ops; 9771 9772 // Push the chain. 9773 Ops.push_back(*(Call->op_begin())); 9774 9775 // Optionally, push the glue (if any). 9776 if (HasGlue) 9777 Ops.push_back(*(Call->op_end() - 1)); 9778 9779 // Push the register mask info. 9780 if (HasGlue) 9781 Ops.push_back(*(Call->op_end() - 2)); 9782 else 9783 Ops.push_back(*(Call->op_end() - 1)); 9784 9785 // Add the <id> and <numBytes> constants. 9786 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9787 Ops.push_back(DAG.getTargetConstant( 9788 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9789 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9790 Ops.push_back(DAG.getTargetConstant( 9791 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9792 MVT::i32)); 9793 9794 // Add the callee. 9795 Ops.push_back(Callee); 9796 9797 // Adjust <numArgs> to account for any arguments that have been passed on the 9798 // stack instead. 9799 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9800 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9801 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9802 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9803 9804 // Add the calling convention 9805 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9806 9807 // Add the arguments we omitted previously. The register allocator should 9808 // place these in any free register. 9809 if (IsAnyRegCC) 9810 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9811 Ops.push_back(getValue(CB.getArgOperand(i))); 9812 9813 // Push the arguments from the call instruction. 9814 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9815 Ops.append(Call->op_begin() + 2, e); 9816 9817 // Push live variables for the stack map. 9818 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9819 9820 SDVTList NodeTys; 9821 if (IsAnyRegCC && HasDef) { 9822 // Create the return types based on the intrinsic definition 9823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9824 SmallVector<EVT, 3> ValueVTs; 9825 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9826 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9827 9828 // There is always a chain and a glue type at the end 9829 ValueVTs.push_back(MVT::Other); 9830 ValueVTs.push_back(MVT::Glue); 9831 NodeTys = DAG.getVTList(ValueVTs); 9832 } else 9833 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9834 9835 // Replace the target specific call node with a PATCHPOINT node. 9836 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9837 9838 // Update the NodeMap. 9839 if (HasDef) { 9840 if (IsAnyRegCC) 9841 setValue(&CB, SDValue(PPV.getNode(), 0)); 9842 else 9843 setValue(&CB, Result.first); 9844 } 9845 9846 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9847 // call sequence. Furthermore the location of the chain and glue can change 9848 // when the AnyReg calling convention is used and the intrinsic returns a 9849 // value. 9850 if (IsAnyRegCC && HasDef) { 9851 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9852 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9853 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9854 } else 9855 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9856 DAG.DeleteNode(Call); 9857 9858 // Inform the Frame Information that we have a patchpoint in this function. 9859 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9860 } 9861 9862 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9863 unsigned Intrinsic) { 9864 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9865 SDValue Op1 = getValue(I.getArgOperand(0)); 9866 SDValue Op2; 9867 if (I.arg_size() > 1) 9868 Op2 = getValue(I.getArgOperand(1)); 9869 SDLoc dl = getCurSDLoc(); 9870 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9871 SDValue Res; 9872 SDNodeFlags SDFlags; 9873 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9874 SDFlags.copyFMF(*FPMO); 9875 9876 switch (Intrinsic) { 9877 case Intrinsic::vector_reduce_fadd: 9878 if (SDFlags.hasAllowReassociation()) 9879 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9880 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9881 SDFlags); 9882 else 9883 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9884 break; 9885 case Intrinsic::vector_reduce_fmul: 9886 if (SDFlags.hasAllowReassociation()) 9887 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9888 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9889 SDFlags); 9890 else 9891 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9892 break; 9893 case Intrinsic::vector_reduce_add: 9894 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9895 break; 9896 case Intrinsic::vector_reduce_mul: 9897 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9898 break; 9899 case Intrinsic::vector_reduce_and: 9900 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9901 break; 9902 case Intrinsic::vector_reduce_or: 9903 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9904 break; 9905 case Intrinsic::vector_reduce_xor: 9906 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9907 break; 9908 case Intrinsic::vector_reduce_smax: 9909 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9910 break; 9911 case Intrinsic::vector_reduce_smin: 9912 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9913 break; 9914 case Intrinsic::vector_reduce_umax: 9915 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9916 break; 9917 case Intrinsic::vector_reduce_umin: 9918 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9919 break; 9920 case Intrinsic::vector_reduce_fmax: 9921 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9922 break; 9923 case Intrinsic::vector_reduce_fmin: 9924 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9925 break; 9926 default: 9927 llvm_unreachable("Unhandled vector reduce intrinsic"); 9928 } 9929 setValue(&I, Res); 9930 } 9931 9932 /// Returns an AttributeList representing the attributes applied to the return 9933 /// value of the given call. 9934 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9935 SmallVector<Attribute::AttrKind, 2> Attrs; 9936 if (CLI.RetSExt) 9937 Attrs.push_back(Attribute::SExt); 9938 if (CLI.RetZExt) 9939 Attrs.push_back(Attribute::ZExt); 9940 if (CLI.IsInReg) 9941 Attrs.push_back(Attribute::InReg); 9942 9943 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9944 Attrs); 9945 } 9946 9947 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9948 /// implementation, which just calls LowerCall. 9949 /// FIXME: When all targets are 9950 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9951 std::pair<SDValue, SDValue> 9952 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9953 // Handle the incoming return values from the call. 9954 CLI.Ins.clear(); 9955 Type *OrigRetTy = CLI.RetTy; 9956 SmallVector<EVT, 4> RetTys; 9957 SmallVector<uint64_t, 4> Offsets; 9958 auto &DL = CLI.DAG.getDataLayout(); 9959 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 9960 9961 if (CLI.IsPostTypeLegalization) { 9962 // If we are lowering a libcall after legalization, split the return type. 9963 SmallVector<EVT, 4> OldRetTys; 9964 SmallVector<uint64_t, 4> OldOffsets; 9965 RetTys.swap(OldRetTys); 9966 Offsets.swap(OldOffsets); 9967 9968 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9969 EVT RetVT = OldRetTys[i]; 9970 uint64_t Offset = OldOffsets[i]; 9971 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9972 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9973 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9974 RetTys.append(NumRegs, RegisterVT); 9975 for (unsigned j = 0; j != NumRegs; ++j) 9976 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9977 } 9978 } 9979 9980 SmallVector<ISD::OutputArg, 4> Outs; 9981 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9982 9983 bool CanLowerReturn = 9984 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9985 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9986 9987 SDValue DemoteStackSlot; 9988 int DemoteStackIdx = -100; 9989 if (!CanLowerReturn) { 9990 // FIXME: equivalent assert? 9991 // assert(!CS.hasInAllocaArgument() && 9992 // "sret demotion is incompatible with inalloca"); 9993 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9994 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9995 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9996 DemoteStackIdx = 9997 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9998 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9999 DL.getAllocaAddrSpace()); 10000 10001 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10002 ArgListEntry Entry; 10003 Entry.Node = DemoteStackSlot; 10004 Entry.Ty = StackSlotPtrType; 10005 Entry.IsSExt = false; 10006 Entry.IsZExt = false; 10007 Entry.IsInReg = false; 10008 Entry.IsSRet = true; 10009 Entry.IsNest = false; 10010 Entry.IsByVal = false; 10011 Entry.IsByRef = false; 10012 Entry.IsReturned = false; 10013 Entry.IsSwiftSelf = false; 10014 Entry.IsSwiftAsync = false; 10015 Entry.IsSwiftError = false; 10016 Entry.IsCFGuardTarget = false; 10017 Entry.Alignment = Alignment; 10018 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10019 CLI.NumFixedArgs += 1; 10020 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10021 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10022 10023 // sret demotion isn't compatible with tail-calls, since the sret argument 10024 // points into the callers stack frame. 10025 CLI.IsTailCall = false; 10026 } else { 10027 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10028 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10029 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10030 ISD::ArgFlagsTy Flags; 10031 if (NeedsRegBlock) { 10032 Flags.setInConsecutiveRegs(); 10033 if (I == RetTys.size() - 1) 10034 Flags.setInConsecutiveRegsLast(); 10035 } 10036 EVT VT = RetTys[I]; 10037 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10038 CLI.CallConv, VT); 10039 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10040 CLI.CallConv, VT); 10041 for (unsigned i = 0; i != NumRegs; ++i) { 10042 ISD::InputArg MyFlags; 10043 MyFlags.Flags = Flags; 10044 MyFlags.VT = RegisterVT; 10045 MyFlags.ArgVT = VT; 10046 MyFlags.Used = CLI.IsReturnValueUsed; 10047 if (CLI.RetTy->isPointerTy()) { 10048 MyFlags.Flags.setPointer(); 10049 MyFlags.Flags.setPointerAddrSpace( 10050 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10051 } 10052 if (CLI.RetSExt) 10053 MyFlags.Flags.setSExt(); 10054 if (CLI.RetZExt) 10055 MyFlags.Flags.setZExt(); 10056 if (CLI.IsInReg) 10057 MyFlags.Flags.setInReg(); 10058 CLI.Ins.push_back(MyFlags); 10059 } 10060 } 10061 } 10062 10063 // We push in swifterror return as the last element of CLI.Ins. 10064 ArgListTy &Args = CLI.getArgs(); 10065 if (supportSwiftError()) { 10066 for (const ArgListEntry &Arg : Args) { 10067 if (Arg.IsSwiftError) { 10068 ISD::InputArg MyFlags; 10069 MyFlags.VT = getPointerTy(DL); 10070 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10071 MyFlags.Flags.setSwiftError(); 10072 CLI.Ins.push_back(MyFlags); 10073 } 10074 } 10075 } 10076 10077 // Handle all of the outgoing arguments. 10078 CLI.Outs.clear(); 10079 CLI.OutVals.clear(); 10080 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10081 SmallVector<EVT, 4> ValueVTs; 10082 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10083 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10084 Type *FinalType = Args[i].Ty; 10085 if (Args[i].IsByVal) 10086 FinalType = Args[i].IndirectType; 10087 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10088 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10089 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10090 ++Value) { 10091 EVT VT = ValueVTs[Value]; 10092 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10093 SDValue Op = SDValue(Args[i].Node.getNode(), 10094 Args[i].Node.getResNo() + Value); 10095 ISD::ArgFlagsTy Flags; 10096 10097 // Certain targets (such as MIPS), may have a different ABI alignment 10098 // for a type depending on the context. Give the target a chance to 10099 // specify the alignment it wants. 10100 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10101 Flags.setOrigAlign(OriginalAlignment); 10102 10103 if (Args[i].Ty->isPointerTy()) { 10104 Flags.setPointer(); 10105 Flags.setPointerAddrSpace( 10106 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10107 } 10108 if (Args[i].IsZExt) 10109 Flags.setZExt(); 10110 if (Args[i].IsSExt) 10111 Flags.setSExt(); 10112 if (Args[i].IsInReg) { 10113 // If we are using vectorcall calling convention, a structure that is 10114 // passed InReg - is surely an HVA 10115 if (CLI.CallConv == CallingConv::X86_VectorCall && 10116 isa<StructType>(FinalType)) { 10117 // The first value of a structure is marked 10118 if (0 == Value) 10119 Flags.setHvaStart(); 10120 Flags.setHva(); 10121 } 10122 // Set InReg Flag 10123 Flags.setInReg(); 10124 } 10125 if (Args[i].IsSRet) 10126 Flags.setSRet(); 10127 if (Args[i].IsSwiftSelf) 10128 Flags.setSwiftSelf(); 10129 if (Args[i].IsSwiftAsync) 10130 Flags.setSwiftAsync(); 10131 if (Args[i].IsSwiftError) 10132 Flags.setSwiftError(); 10133 if (Args[i].IsCFGuardTarget) 10134 Flags.setCFGuardTarget(); 10135 if (Args[i].IsByVal) 10136 Flags.setByVal(); 10137 if (Args[i].IsByRef) 10138 Flags.setByRef(); 10139 if (Args[i].IsPreallocated) { 10140 Flags.setPreallocated(); 10141 // Set the byval flag for CCAssignFn callbacks that don't know about 10142 // preallocated. This way we can know how many bytes we should've 10143 // allocated and how many bytes a callee cleanup function will pop. If 10144 // we port preallocated to more targets, we'll have to add custom 10145 // preallocated handling in the various CC lowering callbacks. 10146 Flags.setByVal(); 10147 } 10148 if (Args[i].IsInAlloca) { 10149 Flags.setInAlloca(); 10150 // Set the byval flag for CCAssignFn callbacks that don't know about 10151 // inalloca. This way we can know how many bytes we should've allocated 10152 // and how many bytes a callee cleanup function will pop. If we port 10153 // inalloca to more targets, we'll have to add custom inalloca handling 10154 // in the various CC lowering callbacks. 10155 Flags.setByVal(); 10156 } 10157 Align MemAlign; 10158 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10159 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10160 Flags.setByValSize(FrameSize); 10161 10162 // info is not there but there are cases it cannot get right. 10163 if (auto MA = Args[i].Alignment) 10164 MemAlign = *MA; 10165 else 10166 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10167 } else if (auto MA = Args[i].Alignment) { 10168 MemAlign = *MA; 10169 } else { 10170 MemAlign = OriginalAlignment; 10171 } 10172 Flags.setMemAlign(MemAlign); 10173 if (Args[i].IsNest) 10174 Flags.setNest(); 10175 if (NeedsRegBlock) 10176 Flags.setInConsecutiveRegs(); 10177 10178 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10179 CLI.CallConv, VT); 10180 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10181 CLI.CallConv, VT); 10182 SmallVector<SDValue, 4> Parts(NumParts); 10183 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10184 10185 if (Args[i].IsSExt) 10186 ExtendKind = ISD::SIGN_EXTEND; 10187 else if (Args[i].IsZExt) 10188 ExtendKind = ISD::ZERO_EXTEND; 10189 10190 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10191 // for now. 10192 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10193 CanLowerReturn) { 10194 assert((CLI.RetTy == Args[i].Ty || 10195 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10196 CLI.RetTy->getPointerAddressSpace() == 10197 Args[i].Ty->getPointerAddressSpace())) && 10198 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10199 // Before passing 'returned' to the target lowering code, ensure that 10200 // either the register MVT and the actual EVT are the same size or that 10201 // the return value and argument are extended in the same way; in these 10202 // cases it's safe to pass the argument register value unchanged as the 10203 // return register value (although it's at the target's option whether 10204 // to do so) 10205 // TODO: allow code generation to take advantage of partially preserved 10206 // registers rather than clobbering the entire register when the 10207 // parameter extension method is not compatible with the return 10208 // extension method 10209 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10210 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10211 CLI.RetZExt == Args[i].IsZExt)) 10212 Flags.setReturned(); 10213 } 10214 10215 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10216 CLI.CallConv, ExtendKind); 10217 10218 for (unsigned j = 0; j != NumParts; ++j) { 10219 // if it isn't first piece, alignment must be 1 10220 // For scalable vectors the scalable part is currently handled 10221 // by individual targets, so we just use the known minimum size here. 10222 ISD::OutputArg MyFlags( 10223 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10224 i < CLI.NumFixedArgs, i, 10225 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10226 if (NumParts > 1 && j == 0) 10227 MyFlags.Flags.setSplit(); 10228 else if (j != 0) { 10229 MyFlags.Flags.setOrigAlign(Align(1)); 10230 if (j == NumParts - 1) 10231 MyFlags.Flags.setSplitEnd(); 10232 } 10233 10234 CLI.Outs.push_back(MyFlags); 10235 CLI.OutVals.push_back(Parts[j]); 10236 } 10237 10238 if (NeedsRegBlock && Value == NumValues - 1) 10239 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10240 } 10241 } 10242 10243 SmallVector<SDValue, 4> InVals; 10244 CLI.Chain = LowerCall(CLI, InVals); 10245 10246 // Update CLI.InVals to use outside of this function. 10247 CLI.InVals = InVals; 10248 10249 // Verify that the target's LowerCall behaved as expected. 10250 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10251 "LowerCall didn't return a valid chain!"); 10252 assert((!CLI.IsTailCall || InVals.empty()) && 10253 "LowerCall emitted a return value for a tail call!"); 10254 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10255 "LowerCall didn't emit the correct number of values!"); 10256 10257 // For a tail call, the return value is merely live-out and there aren't 10258 // any nodes in the DAG representing it. Return a special value to 10259 // indicate that a tail call has been emitted and no more Instructions 10260 // should be processed in the current block. 10261 if (CLI.IsTailCall) { 10262 CLI.DAG.setRoot(CLI.Chain); 10263 return std::make_pair(SDValue(), SDValue()); 10264 } 10265 10266 #ifndef NDEBUG 10267 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10268 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10269 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10270 "LowerCall emitted a value with the wrong type!"); 10271 } 10272 #endif 10273 10274 SmallVector<SDValue, 4> ReturnValues; 10275 if (!CanLowerReturn) { 10276 // The instruction result is the result of loading from the 10277 // hidden sret parameter. 10278 SmallVector<EVT, 1> PVTs; 10279 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10280 10281 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10282 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10283 EVT PtrVT = PVTs[0]; 10284 10285 unsigned NumValues = RetTys.size(); 10286 ReturnValues.resize(NumValues); 10287 SmallVector<SDValue, 4> Chains(NumValues); 10288 10289 // An aggregate return value cannot wrap around the address space, so 10290 // offsets to its parts don't wrap either. 10291 SDNodeFlags Flags; 10292 Flags.setNoUnsignedWrap(true); 10293 10294 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10295 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10296 for (unsigned i = 0; i < NumValues; ++i) { 10297 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10298 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10299 PtrVT), Flags); 10300 SDValue L = CLI.DAG.getLoad( 10301 RetTys[i], CLI.DL, CLI.Chain, Add, 10302 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10303 DemoteStackIdx, Offsets[i]), 10304 HiddenSRetAlign); 10305 ReturnValues[i] = L; 10306 Chains[i] = L.getValue(1); 10307 } 10308 10309 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10310 } else { 10311 // Collect the legal value parts into potentially illegal values 10312 // that correspond to the original function's return values. 10313 std::optional<ISD::NodeType> AssertOp; 10314 if (CLI.RetSExt) 10315 AssertOp = ISD::AssertSext; 10316 else if (CLI.RetZExt) 10317 AssertOp = ISD::AssertZext; 10318 unsigned CurReg = 0; 10319 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10320 EVT VT = RetTys[I]; 10321 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10322 CLI.CallConv, VT); 10323 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10324 CLI.CallConv, VT); 10325 10326 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10327 NumRegs, RegisterVT, VT, nullptr, 10328 CLI.CallConv, AssertOp)); 10329 CurReg += NumRegs; 10330 } 10331 10332 // For a function returning void, there is no return value. We can't create 10333 // such a node, so we just return a null return value in that case. In 10334 // that case, nothing will actually look at the value. 10335 if (ReturnValues.empty()) 10336 return std::make_pair(SDValue(), CLI.Chain); 10337 } 10338 10339 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10340 CLI.DAG.getVTList(RetTys), ReturnValues); 10341 return std::make_pair(Res, CLI.Chain); 10342 } 10343 10344 /// Places new result values for the node in Results (their number 10345 /// and types must exactly match those of the original return values of 10346 /// the node), or leaves Results empty, which indicates that the node is not 10347 /// to be custom lowered after all. 10348 void TargetLowering::LowerOperationWrapper(SDNode *N, 10349 SmallVectorImpl<SDValue> &Results, 10350 SelectionDAG &DAG) const { 10351 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10352 10353 if (!Res.getNode()) 10354 return; 10355 10356 // If the original node has one result, take the return value from 10357 // LowerOperation as is. It might not be result number 0. 10358 if (N->getNumValues() == 1) { 10359 Results.push_back(Res); 10360 return; 10361 } 10362 10363 // If the original node has multiple results, then the return node should 10364 // have the same number of results. 10365 assert((N->getNumValues() == Res->getNumValues()) && 10366 "Lowering returned the wrong number of results!"); 10367 10368 // Places new result values base on N result number. 10369 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10370 Results.push_back(Res.getValue(I)); 10371 } 10372 10373 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10374 llvm_unreachable("LowerOperation not implemented for this target!"); 10375 } 10376 10377 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10378 unsigned Reg, 10379 ISD::NodeType ExtendType) { 10380 SDValue Op = getNonRegisterValue(V); 10381 assert((Op.getOpcode() != ISD::CopyFromReg || 10382 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10383 "Copy from a reg to the same reg!"); 10384 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10385 10386 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10387 // If this is an InlineAsm we have to match the registers required, not the 10388 // notional registers required by the type. 10389 10390 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10391 std::nullopt); // This is not an ABI copy. 10392 SDValue Chain = DAG.getEntryNode(); 10393 10394 if (ExtendType == ISD::ANY_EXTEND) { 10395 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10396 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10397 ExtendType = PreferredExtendIt->second; 10398 } 10399 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10400 PendingExports.push_back(Chain); 10401 } 10402 10403 #include "llvm/CodeGen/SelectionDAGISel.h" 10404 10405 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10406 /// entry block, return true. This includes arguments used by switches, since 10407 /// the switch may expand into multiple basic blocks. 10408 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10409 // With FastISel active, we may be splitting blocks, so force creation 10410 // of virtual registers for all non-dead arguments. 10411 if (FastISel) 10412 return A->use_empty(); 10413 10414 const BasicBlock &Entry = A->getParent()->front(); 10415 for (const User *U : A->users()) 10416 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10417 return false; // Use not in entry block. 10418 10419 return true; 10420 } 10421 10422 using ArgCopyElisionMapTy = 10423 DenseMap<const Argument *, 10424 std::pair<const AllocaInst *, const StoreInst *>>; 10425 10426 /// Scan the entry block of the function in FuncInfo for arguments that look 10427 /// like copies into a local alloca. Record any copied arguments in 10428 /// ArgCopyElisionCandidates. 10429 static void 10430 findArgumentCopyElisionCandidates(const DataLayout &DL, 10431 FunctionLoweringInfo *FuncInfo, 10432 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10433 // Record the state of every static alloca used in the entry block. Argument 10434 // allocas are all used in the entry block, so we need approximately as many 10435 // entries as we have arguments. 10436 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10437 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10438 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10439 StaticAllocas.reserve(NumArgs * 2); 10440 10441 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10442 if (!V) 10443 return nullptr; 10444 V = V->stripPointerCasts(); 10445 const auto *AI = dyn_cast<AllocaInst>(V); 10446 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10447 return nullptr; 10448 auto Iter = StaticAllocas.insert({AI, Unknown}); 10449 return &Iter.first->second; 10450 }; 10451 10452 // Look for stores of arguments to static allocas. Look through bitcasts and 10453 // GEPs to handle type coercions, as long as the alloca is fully initialized 10454 // by the store. Any non-store use of an alloca escapes it and any subsequent 10455 // unanalyzed store might write it. 10456 // FIXME: Handle structs initialized with multiple stores. 10457 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10458 // Look for stores, and handle non-store uses conservatively. 10459 const auto *SI = dyn_cast<StoreInst>(&I); 10460 if (!SI) { 10461 // We will look through cast uses, so ignore them completely. 10462 if (I.isCast()) 10463 continue; 10464 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10465 // to allocas. 10466 if (I.isDebugOrPseudoInst()) 10467 continue; 10468 // This is an unknown instruction. Assume it escapes or writes to all 10469 // static alloca operands. 10470 for (const Use &U : I.operands()) { 10471 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10472 *Info = StaticAllocaInfo::Clobbered; 10473 } 10474 continue; 10475 } 10476 10477 // If the stored value is a static alloca, mark it as escaped. 10478 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10479 *Info = StaticAllocaInfo::Clobbered; 10480 10481 // Check if the destination is a static alloca. 10482 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10483 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10484 if (!Info) 10485 continue; 10486 const AllocaInst *AI = cast<AllocaInst>(Dst); 10487 10488 // Skip allocas that have been initialized or clobbered. 10489 if (*Info != StaticAllocaInfo::Unknown) 10490 continue; 10491 10492 // Check if the stored value is an argument, and that this store fully 10493 // initializes the alloca. 10494 // If the argument type has padding bits we can't directly forward a pointer 10495 // as the upper bits may contain garbage. 10496 // Don't elide copies from the same argument twice. 10497 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10498 const auto *Arg = dyn_cast<Argument>(Val); 10499 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10500 Arg->getType()->isEmptyTy() || 10501 DL.getTypeStoreSize(Arg->getType()) != 10502 DL.getTypeAllocSize(AI->getAllocatedType()) || 10503 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10504 ArgCopyElisionCandidates.count(Arg)) { 10505 *Info = StaticAllocaInfo::Clobbered; 10506 continue; 10507 } 10508 10509 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10510 << '\n'); 10511 10512 // Mark this alloca and store for argument copy elision. 10513 *Info = StaticAllocaInfo::Elidable; 10514 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10515 10516 // Stop scanning if we've seen all arguments. This will happen early in -O0 10517 // builds, which is useful, because -O0 builds have large entry blocks and 10518 // many allocas. 10519 if (ArgCopyElisionCandidates.size() == NumArgs) 10520 break; 10521 } 10522 } 10523 10524 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10525 /// ArgVal is a load from a suitable fixed stack object. 10526 static void tryToElideArgumentCopy( 10527 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10528 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10529 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10530 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10531 SDValue ArgVal, bool &ArgHasUses) { 10532 // Check if this is a load from a fixed stack object. 10533 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10534 if (!LNode) 10535 return; 10536 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10537 if (!FINode) 10538 return; 10539 10540 // Check that the fixed stack object is the right size and alignment. 10541 // Look at the alignment that the user wrote on the alloca instead of looking 10542 // at the stack object. 10543 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10544 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10545 const AllocaInst *AI = ArgCopyIter->second.first; 10546 int FixedIndex = FINode->getIndex(); 10547 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10548 int OldIndex = AllocaIndex; 10549 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10550 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10551 LLVM_DEBUG( 10552 dbgs() << " argument copy elision failed due to bad fixed stack " 10553 "object size\n"); 10554 return; 10555 } 10556 Align RequiredAlignment = AI->getAlign(); 10557 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10558 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10559 "greater than stack argument alignment (" 10560 << DebugStr(RequiredAlignment) << " vs " 10561 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10562 return; 10563 } 10564 10565 // Perform the elision. Delete the old stack object and replace its only use 10566 // in the variable info map. Mark the stack object as mutable. 10567 LLVM_DEBUG({ 10568 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10569 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10570 << '\n'; 10571 }); 10572 MFI.RemoveStackObject(OldIndex); 10573 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10574 AllocaIndex = FixedIndex; 10575 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10576 Chains.push_back(ArgVal.getValue(1)); 10577 10578 // Avoid emitting code for the store implementing the copy. 10579 const StoreInst *SI = ArgCopyIter->second.second; 10580 ElidedArgCopyInstrs.insert(SI); 10581 10582 // Check for uses of the argument again so that we can avoid exporting ArgVal 10583 // if it is't used by anything other than the store. 10584 for (const Value *U : Arg.users()) { 10585 if (U != SI) { 10586 ArgHasUses = true; 10587 break; 10588 } 10589 } 10590 } 10591 10592 void SelectionDAGISel::LowerArguments(const Function &F) { 10593 SelectionDAG &DAG = SDB->DAG; 10594 SDLoc dl = SDB->getCurSDLoc(); 10595 const DataLayout &DL = DAG.getDataLayout(); 10596 SmallVector<ISD::InputArg, 16> Ins; 10597 10598 // In Naked functions we aren't going to save any registers. 10599 if (F.hasFnAttribute(Attribute::Naked)) 10600 return; 10601 10602 if (!FuncInfo->CanLowerReturn) { 10603 // Put in an sret pointer parameter before all the other parameters. 10604 SmallVector<EVT, 1> ValueVTs; 10605 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10606 F.getReturnType()->getPointerTo( 10607 DAG.getDataLayout().getAllocaAddrSpace()), 10608 ValueVTs); 10609 10610 // NOTE: Assuming that a pointer will never break down to more than one VT 10611 // or one register. 10612 ISD::ArgFlagsTy Flags; 10613 Flags.setSRet(); 10614 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10615 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10616 ISD::InputArg::NoArgIndex, 0); 10617 Ins.push_back(RetArg); 10618 } 10619 10620 // Look for stores of arguments to static allocas. Mark such arguments with a 10621 // flag to ask the target to give us the memory location of that argument if 10622 // available. 10623 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10624 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10625 ArgCopyElisionCandidates); 10626 10627 // Set up the incoming argument description vector. 10628 for (const Argument &Arg : F.args()) { 10629 unsigned ArgNo = Arg.getArgNo(); 10630 SmallVector<EVT, 4> ValueVTs; 10631 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10632 bool isArgValueUsed = !Arg.use_empty(); 10633 unsigned PartBase = 0; 10634 Type *FinalType = Arg.getType(); 10635 if (Arg.hasAttribute(Attribute::ByVal)) 10636 FinalType = Arg.getParamByValType(); 10637 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10638 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10639 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10640 Value != NumValues; ++Value) { 10641 EVT VT = ValueVTs[Value]; 10642 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10643 ISD::ArgFlagsTy Flags; 10644 10645 10646 if (Arg.getType()->isPointerTy()) { 10647 Flags.setPointer(); 10648 Flags.setPointerAddrSpace( 10649 cast<PointerType>(Arg.getType())->getAddressSpace()); 10650 } 10651 if (Arg.hasAttribute(Attribute::ZExt)) 10652 Flags.setZExt(); 10653 if (Arg.hasAttribute(Attribute::SExt)) 10654 Flags.setSExt(); 10655 if (Arg.hasAttribute(Attribute::InReg)) { 10656 // If we are using vectorcall calling convention, a structure that is 10657 // passed InReg - is surely an HVA 10658 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10659 isa<StructType>(Arg.getType())) { 10660 // The first value of a structure is marked 10661 if (0 == Value) 10662 Flags.setHvaStart(); 10663 Flags.setHva(); 10664 } 10665 // Set InReg Flag 10666 Flags.setInReg(); 10667 } 10668 if (Arg.hasAttribute(Attribute::StructRet)) 10669 Flags.setSRet(); 10670 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10671 Flags.setSwiftSelf(); 10672 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10673 Flags.setSwiftAsync(); 10674 if (Arg.hasAttribute(Attribute::SwiftError)) 10675 Flags.setSwiftError(); 10676 if (Arg.hasAttribute(Attribute::ByVal)) 10677 Flags.setByVal(); 10678 if (Arg.hasAttribute(Attribute::ByRef)) 10679 Flags.setByRef(); 10680 if (Arg.hasAttribute(Attribute::InAlloca)) { 10681 Flags.setInAlloca(); 10682 // Set the byval flag for CCAssignFn callbacks that don't know about 10683 // inalloca. This way we can know how many bytes we should've allocated 10684 // and how many bytes a callee cleanup function will pop. If we port 10685 // inalloca to more targets, we'll have to add custom inalloca handling 10686 // in the various CC lowering callbacks. 10687 Flags.setByVal(); 10688 } 10689 if (Arg.hasAttribute(Attribute::Preallocated)) { 10690 Flags.setPreallocated(); 10691 // Set the byval flag for CCAssignFn callbacks that don't know about 10692 // preallocated. This way we can know how many bytes we should've 10693 // allocated and how many bytes a callee cleanup function will pop. If 10694 // we port preallocated to more targets, we'll have to add custom 10695 // preallocated handling in the various CC lowering callbacks. 10696 Flags.setByVal(); 10697 } 10698 10699 // Certain targets (such as MIPS), may have a different ABI alignment 10700 // for a type depending on the context. Give the target a chance to 10701 // specify the alignment it wants. 10702 const Align OriginalAlignment( 10703 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10704 Flags.setOrigAlign(OriginalAlignment); 10705 10706 Align MemAlign; 10707 Type *ArgMemTy = nullptr; 10708 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10709 Flags.isByRef()) { 10710 if (!ArgMemTy) 10711 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10712 10713 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10714 10715 // For in-memory arguments, size and alignment should be passed from FE. 10716 // BE will guess if this info is not there but there are cases it cannot 10717 // get right. 10718 if (auto ParamAlign = Arg.getParamStackAlign()) 10719 MemAlign = *ParamAlign; 10720 else if ((ParamAlign = Arg.getParamAlign())) 10721 MemAlign = *ParamAlign; 10722 else 10723 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10724 if (Flags.isByRef()) 10725 Flags.setByRefSize(MemSize); 10726 else 10727 Flags.setByValSize(MemSize); 10728 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10729 MemAlign = *ParamAlign; 10730 } else { 10731 MemAlign = OriginalAlignment; 10732 } 10733 Flags.setMemAlign(MemAlign); 10734 10735 if (Arg.hasAttribute(Attribute::Nest)) 10736 Flags.setNest(); 10737 if (NeedsRegBlock) 10738 Flags.setInConsecutiveRegs(); 10739 if (ArgCopyElisionCandidates.count(&Arg)) 10740 Flags.setCopyElisionCandidate(); 10741 if (Arg.hasAttribute(Attribute::Returned)) 10742 Flags.setReturned(); 10743 10744 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10745 *CurDAG->getContext(), F.getCallingConv(), VT); 10746 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10747 *CurDAG->getContext(), F.getCallingConv(), VT); 10748 for (unsigned i = 0; i != NumRegs; ++i) { 10749 // For scalable vectors, use the minimum size; individual targets 10750 // are responsible for handling scalable vector arguments and 10751 // return values. 10752 ISD::InputArg MyFlags( 10753 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10754 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10755 if (NumRegs > 1 && i == 0) 10756 MyFlags.Flags.setSplit(); 10757 // if it isn't first piece, alignment must be 1 10758 else if (i > 0) { 10759 MyFlags.Flags.setOrigAlign(Align(1)); 10760 if (i == NumRegs - 1) 10761 MyFlags.Flags.setSplitEnd(); 10762 } 10763 Ins.push_back(MyFlags); 10764 } 10765 if (NeedsRegBlock && Value == NumValues - 1) 10766 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10767 PartBase += VT.getStoreSize().getKnownMinValue(); 10768 } 10769 } 10770 10771 // Call the target to set up the argument values. 10772 SmallVector<SDValue, 8> InVals; 10773 SDValue NewRoot = TLI->LowerFormalArguments( 10774 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10775 10776 // Verify that the target's LowerFormalArguments behaved as expected. 10777 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10778 "LowerFormalArguments didn't return a valid chain!"); 10779 assert(InVals.size() == Ins.size() && 10780 "LowerFormalArguments didn't emit the correct number of values!"); 10781 LLVM_DEBUG({ 10782 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10783 assert(InVals[i].getNode() && 10784 "LowerFormalArguments emitted a null value!"); 10785 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10786 "LowerFormalArguments emitted a value with the wrong type!"); 10787 } 10788 }); 10789 10790 // Update the DAG with the new chain value resulting from argument lowering. 10791 DAG.setRoot(NewRoot); 10792 10793 // Set up the argument values. 10794 unsigned i = 0; 10795 if (!FuncInfo->CanLowerReturn) { 10796 // Create a virtual register for the sret pointer, and put in a copy 10797 // from the sret argument into it. 10798 SmallVector<EVT, 1> ValueVTs; 10799 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10800 F.getReturnType()->getPointerTo( 10801 DAG.getDataLayout().getAllocaAddrSpace()), 10802 ValueVTs); 10803 MVT VT = ValueVTs[0].getSimpleVT(); 10804 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10805 std::optional<ISD::NodeType> AssertOp; 10806 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10807 nullptr, F.getCallingConv(), AssertOp); 10808 10809 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10810 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10811 Register SRetReg = 10812 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10813 FuncInfo->DemoteRegister = SRetReg; 10814 NewRoot = 10815 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10816 DAG.setRoot(NewRoot); 10817 10818 // i indexes lowered arguments. Bump it past the hidden sret argument. 10819 ++i; 10820 } 10821 10822 SmallVector<SDValue, 4> Chains; 10823 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10824 for (const Argument &Arg : F.args()) { 10825 SmallVector<SDValue, 4> ArgValues; 10826 SmallVector<EVT, 4> ValueVTs; 10827 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10828 unsigned NumValues = ValueVTs.size(); 10829 if (NumValues == 0) 10830 continue; 10831 10832 bool ArgHasUses = !Arg.use_empty(); 10833 10834 // Elide the copying store if the target loaded this argument from a 10835 // suitable fixed stack object. 10836 if (Ins[i].Flags.isCopyElisionCandidate()) { 10837 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10838 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10839 InVals[i], ArgHasUses); 10840 } 10841 10842 // If this argument is unused then remember its value. It is used to generate 10843 // debugging information. 10844 bool isSwiftErrorArg = 10845 TLI->supportSwiftError() && 10846 Arg.hasAttribute(Attribute::SwiftError); 10847 if (!ArgHasUses && !isSwiftErrorArg) { 10848 SDB->setUnusedArgValue(&Arg, InVals[i]); 10849 10850 // Also remember any frame index for use in FastISel. 10851 if (FrameIndexSDNode *FI = 10852 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10853 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10854 } 10855 10856 for (unsigned Val = 0; Val != NumValues; ++Val) { 10857 EVT VT = ValueVTs[Val]; 10858 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10859 F.getCallingConv(), VT); 10860 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10861 *CurDAG->getContext(), F.getCallingConv(), VT); 10862 10863 // Even an apparent 'unused' swifterror argument needs to be returned. So 10864 // we do generate a copy for it that can be used on return from the 10865 // function. 10866 if (ArgHasUses || isSwiftErrorArg) { 10867 std::optional<ISD::NodeType> AssertOp; 10868 if (Arg.hasAttribute(Attribute::SExt)) 10869 AssertOp = ISD::AssertSext; 10870 else if (Arg.hasAttribute(Attribute::ZExt)) 10871 AssertOp = ISD::AssertZext; 10872 10873 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10874 PartVT, VT, nullptr, 10875 F.getCallingConv(), AssertOp)); 10876 } 10877 10878 i += NumParts; 10879 } 10880 10881 // We don't need to do anything else for unused arguments. 10882 if (ArgValues.empty()) 10883 continue; 10884 10885 // Note down frame index. 10886 if (FrameIndexSDNode *FI = 10887 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10888 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10889 10890 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10891 SDB->getCurSDLoc()); 10892 10893 SDB->setValue(&Arg, Res); 10894 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10895 // We want to associate the argument with the frame index, among 10896 // involved operands, that correspond to the lowest address. The 10897 // getCopyFromParts function, called earlier, is swapping the order of 10898 // the operands to BUILD_PAIR depending on endianness. The result of 10899 // that swapping is that the least significant bits of the argument will 10900 // be in the first operand of the BUILD_PAIR node, and the most 10901 // significant bits will be in the second operand. 10902 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10903 if (LoadSDNode *LNode = 10904 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10905 if (FrameIndexSDNode *FI = 10906 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10907 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10908 } 10909 10910 // Analyses past this point are naive and don't expect an assertion. 10911 if (Res.getOpcode() == ISD::AssertZext) 10912 Res = Res.getOperand(0); 10913 10914 // Update the SwiftErrorVRegDefMap. 10915 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10916 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10917 if (Register::isVirtualRegister(Reg)) 10918 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10919 Reg); 10920 } 10921 10922 // If this argument is live outside of the entry block, insert a copy from 10923 // wherever we got it to the vreg that other BB's will reference it as. 10924 if (Res.getOpcode() == ISD::CopyFromReg) { 10925 // If we can, though, try to skip creating an unnecessary vreg. 10926 // FIXME: This isn't very clean... it would be nice to make this more 10927 // general. 10928 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10929 if (Register::isVirtualRegister(Reg)) { 10930 FuncInfo->ValueMap[&Arg] = Reg; 10931 continue; 10932 } 10933 } 10934 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10935 FuncInfo->InitializeRegForValue(&Arg); 10936 SDB->CopyToExportRegsIfNeeded(&Arg); 10937 } 10938 } 10939 10940 if (!Chains.empty()) { 10941 Chains.push_back(NewRoot); 10942 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10943 } 10944 10945 DAG.setRoot(NewRoot); 10946 10947 assert(i == InVals.size() && "Argument register count mismatch!"); 10948 10949 // If any argument copy elisions occurred and we have debug info, update the 10950 // stale frame indices used in the dbg.declare variable info table. 10951 if (!ArgCopyElisionFrameIndexMap.empty()) { 10952 for (MachineFunction::VariableDbgInfo &VI : 10953 MF->getInStackSlotVariableDbgInfo()) { 10954 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 10955 if (I != ArgCopyElisionFrameIndexMap.end()) 10956 VI.updateStackSlot(I->second); 10957 } 10958 } 10959 10960 // Finally, if the target has anything special to do, allow it to do so. 10961 emitFunctionEntryCode(); 10962 } 10963 10964 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10965 /// ensure constants are generated when needed. Remember the virtual registers 10966 /// that need to be added to the Machine PHI nodes as input. We cannot just 10967 /// directly add them, because expansion might result in multiple MBB's for one 10968 /// BB. As such, the start of the BB might correspond to a different MBB than 10969 /// the end. 10970 void 10971 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10972 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10973 10974 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10975 10976 // Check PHI nodes in successors that expect a value to be available from this 10977 // block. 10978 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10979 if (!isa<PHINode>(SuccBB->begin())) continue; 10980 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10981 10982 // If this terminator has multiple identical successors (common for 10983 // switches), only handle each succ once. 10984 if (!SuccsHandled.insert(SuccMBB).second) 10985 continue; 10986 10987 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10988 10989 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10990 // nodes and Machine PHI nodes, but the incoming operands have not been 10991 // emitted yet. 10992 for (const PHINode &PN : SuccBB->phis()) { 10993 // Ignore dead phi's. 10994 if (PN.use_empty()) 10995 continue; 10996 10997 // Skip empty types 10998 if (PN.getType()->isEmptyTy()) 10999 continue; 11000 11001 unsigned Reg; 11002 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11003 11004 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11005 unsigned &RegOut = ConstantsOut[C]; 11006 if (RegOut == 0) { 11007 RegOut = FuncInfo.CreateRegs(C); 11008 // We need to zero/sign extend ConstantInt phi operands to match 11009 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11010 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11011 if (auto *CI = dyn_cast<ConstantInt>(C)) 11012 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11013 : ISD::ZERO_EXTEND; 11014 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11015 } 11016 Reg = RegOut; 11017 } else { 11018 DenseMap<const Value *, Register>::iterator I = 11019 FuncInfo.ValueMap.find(PHIOp); 11020 if (I != FuncInfo.ValueMap.end()) 11021 Reg = I->second; 11022 else { 11023 assert(isa<AllocaInst>(PHIOp) && 11024 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11025 "Didn't codegen value into a register!??"); 11026 Reg = FuncInfo.CreateRegs(PHIOp); 11027 CopyValueToVirtualRegister(PHIOp, Reg); 11028 } 11029 } 11030 11031 // Remember that this register needs to added to the machine PHI node as 11032 // the input for this MBB. 11033 SmallVector<EVT, 4> ValueVTs; 11034 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11035 for (EVT VT : ValueVTs) { 11036 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11037 for (unsigned i = 0; i != NumRegisters; ++i) 11038 FuncInfo.PHINodesToUpdate.push_back( 11039 std::make_pair(&*MBBI++, Reg + i)); 11040 Reg += NumRegisters; 11041 } 11042 } 11043 } 11044 11045 ConstantsOut.clear(); 11046 } 11047 11048 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11049 MachineFunction::iterator I(MBB); 11050 if (++I == FuncInfo.MF->end()) 11051 return nullptr; 11052 return &*I; 11053 } 11054 11055 /// During lowering new call nodes can be created (such as memset, etc.). 11056 /// Those will become new roots of the current DAG, but complications arise 11057 /// when they are tail calls. In such cases, the call lowering will update 11058 /// the root, but the builder still needs to know that a tail call has been 11059 /// lowered in order to avoid generating an additional return. 11060 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11061 // If the node is null, we do have a tail call. 11062 if (MaybeTC.getNode() != nullptr) 11063 DAG.setRoot(MaybeTC); 11064 else 11065 HasTailCall = true; 11066 } 11067 11068 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11069 MachineBasicBlock *SwitchMBB, 11070 MachineBasicBlock *DefaultMBB) { 11071 MachineFunction *CurMF = FuncInfo.MF; 11072 MachineBasicBlock *NextMBB = nullptr; 11073 MachineFunction::iterator BBI(W.MBB); 11074 if (++BBI != FuncInfo.MF->end()) 11075 NextMBB = &*BBI; 11076 11077 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11078 11079 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11080 11081 if (Size == 2 && W.MBB == SwitchMBB) { 11082 // If any two of the cases has the same destination, and if one value 11083 // is the same as the other, but has one bit unset that the other has set, 11084 // use bit manipulation to do two compares at once. For example: 11085 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11086 // TODO: This could be extended to merge any 2 cases in switches with 3 11087 // cases. 11088 // TODO: Handle cases where W.CaseBB != SwitchBB. 11089 CaseCluster &Small = *W.FirstCluster; 11090 CaseCluster &Big = *W.LastCluster; 11091 11092 if (Small.Low == Small.High && Big.Low == Big.High && 11093 Small.MBB == Big.MBB) { 11094 const APInt &SmallValue = Small.Low->getValue(); 11095 const APInt &BigValue = Big.Low->getValue(); 11096 11097 // Check that there is only one bit different. 11098 APInt CommonBit = BigValue ^ SmallValue; 11099 if (CommonBit.isPowerOf2()) { 11100 SDValue CondLHS = getValue(Cond); 11101 EVT VT = CondLHS.getValueType(); 11102 SDLoc DL = getCurSDLoc(); 11103 11104 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11105 DAG.getConstant(CommonBit, DL, VT)); 11106 SDValue Cond = DAG.getSetCC( 11107 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11108 ISD::SETEQ); 11109 11110 // Update successor info. 11111 // Both Small and Big will jump to Small.BB, so we sum up the 11112 // probabilities. 11113 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11114 if (BPI) 11115 addSuccessorWithProb( 11116 SwitchMBB, DefaultMBB, 11117 // The default destination is the first successor in IR. 11118 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11119 else 11120 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11121 11122 // Insert the true branch. 11123 SDValue BrCond = 11124 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11125 DAG.getBasicBlock(Small.MBB)); 11126 // Insert the false branch. 11127 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11128 DAG.getBasicBlock(DefaultMBB)); 11129 11130 DAG.setRoot(BrCond); 11131 return; 11132 } 11133 } 11134 } 11135 11136 if (TM.getOptLevel() != CodeGenOpt::None) { 11137 // Here, we order cases by probability so the most likely case will be 11138 // checked first. However, two clusters can have the same probability in 11139 // which case their relative ordering is non-deterministic. So we use Low 11140 // as a tie-breaker as clusters are guaranteed to never overlap. 11141 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11142 [](const CaseCluster &a, const CaseCluster &b) { 11143 return a.Prob != b.Prob ? 11144 a.Prob > b.Prob : 11145 a.Low->getValue().slt(b.Low->getValue()); 11146 }); 11147 11148 // Rearrange the case blocks so that the last one falls through if possible 11149 // without changing the order of probabilities. 11150 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11151 --I; 11152 if (I->Prob > W.LastCluster->Prob) 11153 break; 11154 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11155 std::swap(*I, *W.LastCluster); 11156 break; 11157 } 11158 } 11159 } 11160 11161 // Compute total probability. 11162 BranchProbability DefaultProb = W.DefaultProb; 11163 BranchProbability UnhandledProbs = DefaultProb; 11164 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11165 UnhandledProbs += I->Prob; 11166 11167 MachineBasicBlock *CurMBB = W.MBB; 11168 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11169 bool FallthroughUnreachable = false; 11170 MachineBasicBlock *Fallthrough; 11171 if (I == W.LastCluster) { 11172 // For the last cluster, fall through to the default destination. 11173 Fallthrough = DefaultMBB; 11174 FallthroughUnreachable = isa<UnreachableInst>( 11175 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11176 } else { 11177 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11178 CurMF->insert(BBI, Fallthrough); 11179 // Put Cond in a virtual register to make it available from the new blocks. 11180 ExportFromCurrentBlock(Cond); 11181 } 11182 UnhandledProbs -= I->Prob; 11183 11184 switch (I->Kind) { 11185 case CC_JumpTable: { 11186 // FIXME: Optimize away range check based on pivot comparisons. 11187 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11188 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11189 11190 // The jump block hasn't been inserted yet; insert it here. 11191 MachineBasicBlock *JumpMBB = JT->MBB; 11192 CurMF->insert(BBI, JumpMBB); 11193 11194 auto JumpProb = I->Prob; 11195 auto FallthroughProb = UnhandledProbs; 11196 11197 // If the default statement is a target of the jump table, we evenly 11198 // distribute the default probability to successors of CurMBB. Also 11199 // update the probability on the edge from JumpMBB to Fallthrough. 11200 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11201 SE = JumpMBB->succ_end(); 11202 SI != SE; ++SI) { 11203 if (*SI == DefaultMBB) { 11204 JumpProb += DefaultProb / 2; 11205 FallthroughProb -= DefaultProb / 2; 11206 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11207 JumpMBB->normalizeSuccProbs(); 11208 break; 11209 } 11210 } 11211 11212 if (FallthroughUnreachable) 11213 JTH->FallthroughUnreachable = true; 11214 11215 if (!JTH->FallthroughUnreachable) 11216 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11217 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11218 CurMBB->normalizeSuccProbs(); 11219 11220 // The jump table header will be inserted in our current block, do the 11221 // range check, and fall through to our fallthrough block. 11222 JTH->HeaderBB = CurMBB; 11223 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11224 11225 // If we're in the right place, emit the jump table header right now. 11226 if (CurMBB == SwitchMBB) { 11227 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11228 JTH->Emitted = true; 11229 } 11230 break; 11231 } 11232 case CC_BitTests: { 11233 // FIXME: Optimize away range check based on pivot comparisons. 11234 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11235 11236 // The bit test blocks haven't been inserted yet; insert them here. 11237 for (BitTestCase &BTC : BTB->Cases) 11238 CurMF->insert(BBI, BTC.ThisBB); 11239 11240 // Fill in fields of the BitTestBlock. 11241 BTB->Parent = CurMBB; 11242 BTB->Default = Fallthrough; 11243 11244 BTB->DefaultProb = UnhandledProbs; 11245 // If the cases in bit test don't form a contiguous range, we evenly 11246 // distribute the probability on the edge to Fallthrough to two 11247 // successors of CurMBB. 11248 if (!BTB->ContiguousRange) { 11249 BTB->Prob += DefaultProb / 2; 11250 BTB->DefaultProb -= DefaultProb / 2; 11251 } 11252 11253 if (FallthroughUnreachable) 11254 BTB->FallthroughUnreachable = true; 11255 11256 // If we're in the right place, emit the bit test header right now. 11257 if (CurMBB == SwitchMBB) { 11258 visitBitTestHeader(*BTB, SwitchMBB); 11259 BTB->Emitted = true; 11260 } 11261 break; 11262 } 11263 case CC_Range: { 11264 const Value *RHS, *LHS, *MHS; 11265 ISD::CondCode CC; 11266 if (I->Low == I->High) { 11267 // Check Cond == I->Low. 11268 CC = ISD::SETEQ; 11269 LHS = Cond; 11270 RHS=I->Low; 11271 MHS = nullptr; 11272 } else { 11273 // Check I->Low <= Cond <= I->High. 11274 CC = ISD::SETLE; 11275 LHS = I->Low; 11276 MHS = Cond; 11277 RHS = I->High; 11278 } 11279 11280 // If Fallthrough is unreachable, fold away the comparison. 11281 if (FallthroughUnreachable) 11282 CC = ISD::SETTRUE; 11283 11284 // The false probability is the sum of all unhandled cases. 11285 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11286 getCurSDLoc(), I->Prob, UnhandledProbs); 11287 11288 if (CurMBB == SwitchMBB) 11289 visitSwitchCase(CB, SwitchMBB); 11290 else 11291 SL->SwitchCases.push_back(CB); 11292 11293 break; 11294 } 11295 } 11296 CurMBB = Fallthrough; 11297 } 11298 } 11299 11300 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11301 CaseClusterIt First, 11302 CaseClusterIt Last) { 11303 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11304 if (X.Prob != CC.Prob) 11305 return X.Prob > CC.Prob; 11306 11307 // Ties are broken by comparing the case value. 11308 return X.Low->getValue().slt(CC.Low->getValue()); 11309 }); 11310 } 11311 11312 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11313 const SwitchWorkListItem &W, 11314 Value *Cond, 11315 MachineBasicBlock *SwitchMBB) { 11316 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11317 "Clusters not sorted?"); 11318 11319 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11320 11321 // Balance the tree based on branch probabilities to create a near-optimal (in 11322 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11323 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11324 CaseClusterIt LastLeft = W.FirstCluster; 11325 CaseClusterIt FirstRight = W.LastCluster; 11326 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11327 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11328 11329 // Move LastLeft and FirstRight towards each other from opposite directions to 11330 // find a partitioning of the clusters which balances the probability on both 11331 // sides. If LeftProb and RightProb are equal, alternate which side is 11332 // taken to ensure 0-probability nodes are distributed evenly. 11333 unsigned I = 0; 11334 while (LastLeft + 1 < FirstRight) { 11335 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11336 LeftProb += (++LastLeft)->Prob; 11337 else 11338 RightProb += (--FirstRight)->Prob; 11339 I++; 11340 } 11341 11342 while (true) { 11343 // Our binary search tree differs from a typical BST in that ours can have up 11344 // to three values in each leaf. The pivot selection above doesn't take that 11345 // into account, which means the tree might require more nodes and be less 11346 // efficient. We compensate for this here. 11347 11348 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11349 unsigned NumRight = W.LastCluster - FirstRight + 1; 11350 11351 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11352 // If one side has less than 3 clusters, and the other has more than 3, 11353 // consider taking a cluster from the other side. 11354 11355 if (NumLeft < NumRight) { 11356 // Consider moving the first cluster on the right to the left side. 11357 CaseCluster &CC = *FirstRight; 11358 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11359 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11360 if (LeftSideRank <= RightSideRank) { 11361 // Moving the cluster to the left does not demote it. 11362 ++LastLeft; 11363 ++FirstRight; 11364 continue; 11365 } 11366 } else { 11367 assert(NumRight < NumLeft); 11368 // Consider moving the last element on the left to the right side. 11369 CaseCluster &CC = *LastLeft; 11370 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11371 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11372 if (RightSideRank <= LeftSideRank) { 11373 // Moving the cluster to the right does not demot it. 11374 --LastLeft; 11375 --FirstRight; 11376 continue; 11377 } 11378 } 11379 } 11380 break; 11381 } 11382 11383 assert(LastLeft + 1 == FirstRight); 11384 assert(LastLeft >= W.FirstCluster); 11385 assert(FirstRight <= W.LastCluster); 11386 11387 // Use the first element on the right as pivot since we will make less-than 11388 // comparisons against it. 11389 CaseClusterIt PivotCluster = FirstRight; 11390 assert(PivotCluster > W.FirstCluster); 11391 assert(PivotCluster <= W.LastCluster); 11392 11393 CaseClusterIt FirstLeft = W.FirstCluster; 11394 CaseClusterIt LastRight = W.LastCluster; 11395 11396 const ConstantInt *Pivot = PivotCluster->Low; 11397 11398 // New blocks will be inserted immediately after the current one. 11399 MachineFunction::iterator BBI(W.MBB); 11400 ++BBI; 11401 11402 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11403 // we can branch to its destination directly if it's squeezed exactly in 11404 // between the known lower bound and Pivot - 1. 11405 MachineBasicBlock *LeftMBB; 11406 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11407 FirstLeft->Low == W.GE && 11408 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11409 LeftMBB = FirstLeft->MBB; 11410 } else { 11411 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11412 FuncInfo.MF->insert(BBI, LeftMBB); 11413 WorkList.push_back( 11414 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11415 // Put Cond in a virtual register to make it available from the new blocks. 11416 ExportFromCurrentBlock(Cond); 11417 } 11418 11419 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11420 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11421 // directly if RHS.High equals the current upper bound. 11422 MachineBasicBlock *RightMBB; 11423 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11424 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11425 RightMBB = FirstRight->MBB; 11426 } else { 11427 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11428 FuncInfo.MF->insert(BBI, RightMBB); 11429 WorkList.push_back( 11430 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11431 // Put Cond in a virtual register to make it available from the new blocks. 11432 ExportFromCurrentBlock(Cond); 11433 } 11434 11435 // Create the CaseBlock record that will be used to lower the branch. 11436 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11437 getCurSDLoc(), LeftProb, RightProb); 11438 11439 if (W.MBB == SwitchMBB) 11440 visitSwitchCase(CB, SwitchMBB); 11441 else 11442 SL->SwitchCases.push_back(CB); 11443 } 11444 11445 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11446 // from the swith statement. 11447 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11448 BranchProbability PeeledCaseProb) { 11449 if (PeeledCaseProb == BranchProbability::getOne()) 11450 return BranchProbability::getZero(); 11451 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11452 11453 uint32_t Numerator = CaseProb.getNumerator(); 11454 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11455 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11456 } 11457 11458 // Try to peel the top probability case if it exceeds the threshold. 11459 // Return current MachineBasicBlock for the switch statement if the peeling 11460 // does not occur. 11461 // If the peeling is performed, return the newly created MachineBasicBlock 11462 // for the peeled switch statement. Also update Clusters to remove the peeled 11463 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11464 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11465 const SwitchInst &SI, CaseClusterVector &Clusters, 11466 BranchProbability &PeeledCaseProb) { 11467 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11468 // Don't perform if there is only one cluster or optimizing for size. 11469 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11470 TM.getOptLevel() == CodeGenOpt::None || 11471 SwitchMBB->getParent()->getFunction().hasMinSize()) 11472 return SwitchMBB; 11473 11474 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11475 unsigned PeeledCaseIndex = 0; 11476 bool SwitchPeeled = false; 11477 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11478 CaseCluster &CC = Clusters[Index]; 11479 if (CC.Prob < TopCaseProb) 11480 continue; 11481 TopCaseProb = CC.Prob; 11482 PeeledCaseIndex = Index; 11483 SwitchPeeled = true; 11484 } 11485 if (!SwitchPeeled) 11486 return SwitchMBB; 11487 11488 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11489 << TopCaseProb << "\n"); 11490 11491 // Record the MBB for the peeled switch statement. 11492 MachineFunction::iterator BBI(SwitchMBB); 11493 ++BBI; 11494 MachineBasicBlock *PeeledSwitchMBB = 11495 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11496 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11497 11498 ExportFromCurrentBlock(SI.getCondition()); 11499 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11500 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11501 nullptr, nullptr, TopCaseProb.getCompl()}; 11502 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11503 11504 Clusters.erase(PeeledCaseIt); 11505 for (CaseCluster &CC : Clusters) { 11506 LLVM_DEBUG( 11507 dbgs() << "Scale the probablity for one cluster, before scaling: " 11508 << CC.Prob << "\n"); 11509 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11510 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11511 } 11512 PeeledCaseProb = TopCaseProb; 11513 return PeeledSwitchMBB; 11514 } 11515 11516 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11517 // Extract cases from the switch. 11518 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11519 CaseClusterVector Clusters; 11520 Clusters.reserve(SI.getNumCases()); 11521 for (auto I : SI.cases()) { 11522 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11523 const ConstantInt *CaseVal = I.getCaseValue(); 11524 BranchProbability Prob = 11525 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11526 : BranchProbability(1, SI.getNumCases() + 1); 11527 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11528 } 11529 11530 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11531 11532 // Cluster adjacent cases with the same destination. We do this at all 11533 // optimization levels because it's cheap to do and will make codegen faster 11534 // if there are many clusters. 11535 sortAndRangeify(Clusters); 11536 11537 // The branch probablity of the peeled case. 11538 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11539 MachineBasicBlock *PeeledSwitchMBB = 11540 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11541 11542 // If there is only the default destination, jump there directly. 11543 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11544 if (Clusters.empty()) { 11545 assert(PeeledSwitchMBB == SwitchMBB); 11546 SwitchMBB->addSuccessor(DefaultMBB); 11547 if (DefaultMBB != NextBlock(SwitchMBB)) { 11548 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11549 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11550 } 11551 return; 11552 } 11553 11554 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11555 SL->findBitTestClusters(Clusters, &SI); 11556 11557 LLVM_DEBUG({ 11558 dbgs() << "Case clusters: "; 11559 for (const CaseCluster &C : Clusters) { 11560 if (C.Kind == CC_JumpTable) 11561 dbgs() << "JT:"; 11562 if (C.Kind == CC_BitTests) 11563 dbgs() << "BT:"; 11564 11565 C.Low->getValue().print(dbgs(), true); 11566 if (C.Low != C.High) { 11567 dbgs() << '-'; 11568 C.High->getValue().print(dbgs(), true); 11569 } 11570 dbgs() << ' '; 11571 } 11572 dbgs() << '\n'; 11573 }); 11574 11575 assert(!Clusters.empty()); 11576 SwitchWorkList WorkList; 11577 CaseClusterIt First = Clusters.begin(); 11578 CaseClusterIt Last = Clusters.end() - 1; 11579 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11580 // Scale the branchprobability for DefaultMBB if the peel occurs and 11581 // DefaultMBB is not replaced. 11582 if (PeeledCaseProb != BranchProbability::getZero() && 11583 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11584 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11585 WorkList.push_back( 11586 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11587 11588 while (!WorkList.empty()) { 11589 SwitchWorkListItem W = WorkList.pop_back_val(); 11590 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11591 11592 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11593 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11594 // For optimized builds, lower large range as a balanced binary tree. 11595 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11596 continue; 11597 } 11598 11599 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11600 } 11601 } 11602 11603 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11605 auto DL = getCurSDLoc(); 11606 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11607 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11608 } 11609 11610 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11612 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11613 11614 SDLoc DL = getCurSDLoc(); 11615 SDValue V = getValue(I.getOperand(0)); 11616 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11617 11618 if (VT.isScalableVector()) { 11619 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11620 return; 11621 } 11622 11623 // Use VECTOR_SHUFFLE for the fixed-length vector 11624 // to maintain existing behavior. 11625 SmallVector<int, 8> Mask; 11626 unsigned NumElts = VT.getVectorMinNumElements(); 11627 for (unsigned i = 0; i != NumElts; ++i) 11628 Mask.push_back(NumElts - 1 - i); 11629 11630 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11631 } 11632 11633 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11634 auto DL = getCurSDLoc(); 11635 SDValue InVec = getValue(I.getOperand(0)); 11636 EVT OutVT = 11637 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11638 11639 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11640 11641 // ISD Node needs the input vectors split into two equal parts 11642 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11643 DAG.getVectorIdxConstant(0, DL)); 11644 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11645 DAG.getVectorIdxConstant(OutNumElts, DL)); 11646 11647 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11648 // legalisation and combines. 11649 if (OutVT.isFixedLengthVector()) { 11650 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11651 createStrideMask(0, 2, OutNumElts)); 11652 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11653 createStrideMask(1, 2, OutNumElts)); 11654 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11655 setValue(&I, Res); 11656 return; 11657 } 11658 11659 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11660 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11661 setValue(&I, Res); 11662 } 11663 11664 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11665 auto DL = getCurSDLoc(); 11666 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11667 SDValue InVec0 = getValue(I.getOperand(0)); 11668 SDValue InVec1 = getValue(I.getOperand(1)); 11669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11670 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11671 11672 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11673 // legalisation and combines. 11674 if (OutVT.isFixedLengthVector()) { 11675 unsigned NumElts = InVT.getVectorMinNumElements(); 11676 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11677 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11678 createInterleaveMask(NumElts, 2))); 11679 return; 11680 } 11681 11682 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11683 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11684 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11685 Res.getValue(1)); 11686 setValue(&I, Res); 11687 } 11688 11689 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11690 SmallVector<EVT, 4> ValueVTs; 11691 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11692 ValueVTs); 11693 unsigned NumValues = ValueVTs.size(); 11694 if (NumValues == 0) return; 11695 11696 SmallVector<SDValue, 4> Values(NumValues); 11697 SDValue Op = getValue(I.getOperand(0)); 11698 11699 for (unsigned i = 0; i != NumValues; ++i) 11700 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11701 SDValue(Op.getNode(), Op.getResNo() + i)); 11702 11703 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11704 DAG.getVTList(ValueVTs), Values)); 11705 } 11706 11707 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11708 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11709 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11710 11711 SDLoc DL = getCurSDLoc(); 11712 SDValue V1 = getValue(I.getOperand(0)); 11713 SDValue V2 = getValue(I.getOperand(1)); 11714 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11715 11716 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11717 if (VT.isScalableVector()) { 11718 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11719 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11720 DAG.getConstant(Imm, DL, IdxVT))); 11721 return; 11722 } 11723 11724 unsigned NumElts = VT.getVectorNumElements(); 11725 11726 uint64_t Idx = (NumElts + Imm) % NumElts; 11727 11728 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11729 SmallVector<int, 8> Mask; 11730 for (unsigned i = 0; i < NumElts; ++i) 11731 Mask.push_back(Idx + i); 11732 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11733 } 11734 11735 // Consider the following MIR after SelectionDAG, which produces output in 11736 // phyregs in the first case or virtregs in the second case. 11737 // 11738 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11739 // %5:gr32 = COPY $ebx 11740 // %6:gr32 = COPY $edx 11741 // %1:gr32 = COPY %6:gr32 11742 // %0:gr32 = COPY %5:gr32 11743 // 11744 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11745 // %1:gr32 = COPY %6:gr32 11746 // %0:gr32 = COPY %5:gr32 11747 // 11748 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11749 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11750 // 11751 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11752 // to a single virtreg (such as %0). The remaining outputs monotonically 11753 // increase in virtreg number from there. If a callbr has no outputs, then it 11754 // should not have a corresponding callbr landingpad; in fact, the callbr 11755 // landingpad would not even be able to refer to such a callbr. 11756 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11757 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11758 // There is definitely at least one copy. 11759 assert(MI->getOpcode() == TargetOpcode::COPY && 11760 "start of copy chain MUST be COPY"); 11761 Reg = MI->getOperand(1).getReg(); 11762 MI = MRI.def_begin(Reg)->getParent(); 11763 // There may be an optional second copy. 11764 if (MI->getOpcode() == TargetOpcode::COPY) { 11765 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11766 Reg = MI->getOperand(1).getReg(); 11767 assert(Reg.isPhysical() && "expected COPY of physical register"); 11768 MI = MRI.def_begin(Reg)->getParent(); 11769 } 11770 // The start of the chain must be an INLINEASM_BR. 11771 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11772 "end of copy chain MUST be INLINEASM_BR"); 11773 return Reg; 11774 } 11775 11776 // We must do this walk rather than the simpler 11777 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11778 // otherwise we will end up with copies of virtregs only valid along direct 11779 // edges. 11780 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11781 SmallVector<EVT, 8> ResultVTs; 11782 SmallVector<SDValue, 8> ResultValues; 11783 const auto *CBR = 11784 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11785 11786 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11787 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11788 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11789 11790 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11791 SDValue Chain = DAG.getRoot(); 11792 11793 // Re-parse the asm constraints string. 11794 TargetLowering::AsmOperandInfoVector TargetConstraints = 11795 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11796 for (auto &T : TargetConstraints) { 11797 SDISelAsmOperandInfo OpInfo(T); 11798 if (OpInfo.Type != InlineAsm::isOutput) 11799 continue; 11800 11801 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11802 // individual constraint. 11803 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11804 11805 switch (OpInfo.ConstraintType) { 11806 case TargetLowering::C_Register: 11807 case TargetLowering::C_RegisterClass: { 11808 // Fill in OpInfo.AssignedRegs.Regs. 11809 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11810 11811 // getRegistersForValue may produce 1 to many registers based on whether 11812 // the OpInfo.ConstraintVT is legal on the target or not. 11813 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11814 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11815 if (Register::isPhysicalRegister(OriginalDef)) 11816 FuncInfo.MBB->addLiveIn(OriginalDef); 11817 // Update the assigned registers to use the original defs. 11818 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11819 } 11820 11821 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11822 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11823 ResultValues.push_back(V); 11824 ResultVTs.push_back(OpInfo.ConstraintVT); 11825 break; 11826 } 11827 case TargetLowering::C_Other: { 11828 SDValue Flag; 11829 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11830 OpInfo, DAG); 11831 ++InitialDef; 11832 ResultValues.push_back(V); 11833 ResultVTs.push_back(OpInfo.ConstraintVT); 11834 break; 11835 } 11836 default: 11837 break; 11838 } 11839 } 11840 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11841 DAG.getVTList(ResultVTs), ResultValues); 11842 setValue(&I, V); 11843 } 11844