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 *Flag, 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 (!Flag) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 863 *Flag = 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 *Flag, 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 (!Flag) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 955 *Flag = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Flag) 962 // If NumRegs > 1 && Flag 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 } 1055 1056 void SelectionDAGBuilder::clear() { 1057 NodeMap.clear(); 1058 UnusedArgNodeMap.clear(); 1059 PendingLoads.clear(); 1060 PendingExports.clear(); 1061 PendingConstrainedFP.clear(); 1062 PendingConstrainedFPStrict.clear(); 1063 CurInst = nullptr; 1064 HasTailCall = false; 1065 SDNodeOrder = LowestSDNodeOrder; 1066 StatepointLowering.clear(); 1067 } 1068 1069 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1070 DanglingDebugInfoMap.clear(); 1071 } 1072 1073 // Update DAG root to include dependencies on Pending chains. 1074 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1075 SDValue Root = DAG.getRoot(); 1076 1077 if (Pending.empty()) 1078 return Root; 1079 1080 // Add current root to PendingChains, unless we already indirectly 1081 // depend on it. 1082 if (Root.getOpcode() != ISD::EntryToken) { 1083 unsigned i = 0, e = Pending.size(); 1084 for (; i != e; ++i) { 1085 assert(Pending[i].getNode()->getNumOperands() > 1); 1086 if (Pending[i].getNode()->getOperand(0) == Root) 1087 break; // Don't add the root if we already indirectly depend on it. 1088 } 1089 1090 if (i == e) 1091 Pending.push_back(Root); 1092 } 1093 1094 if (Pending.size() == 1) 1095 Root = Pending[0]; 1096 else 1097 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1098 1099 DAG.setRoot(Root); 1100 Pending.clear(); 1101 return Root; 1102 } 1103 1104 SDValue SelectionDAGBuilder::getMemoryRoot() { 1105 return updateRoot(PendingLoads); 1106 } 1107 1108 SDValue SelectionDAGBuilder::getRoot() { 1109 // Chain up all pending constrained intrinsics together with all 1110 // pending loads, by simply appending them to PendingLoads and 1111 // then calling getMemoryRoot(). 1112 PendingLoads.reserve(PendingLoads.size() + 1113 PendingConstrainedFP.size() + 1114 PendingConstrainedFPStrict.size()); 1115 PendingLoads.append(PendingConstrainedFP.begin(), 1116 PendingConstrainedFP.end()); 1117 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1118 PendingConstrainedFPStrict.end()); 1119 PendingConstrainedFP.clear(); 1120 PendingConstrainedFPStrict.clear(); 1121 return getMemoryRoot(); 1122 } 1123 1124 SDValue SelectionDAGBuilder::getControlRoot() { 1125 // We need to emit pending fpexcept.strict constrained intrinsics, 1126 // so append them to the PendingExports list. 1127 PendingExports.append(PendingConstrainedFPStrict.begin(), 1128 PendingConstrainedFPStrict.end()); 1129 PendingConstrainedFPStrict.clear(); 1130 return updateRoot(PendingExports); 1131 } 1132 1133 void SelectionDAGBuilder::visit(const Instruction &I) { 1134 // Set up outgoing PHI node register values before emitting the terminator. 1135 if (I.isTerminator()) { 1136 HandlePHINodesInSuccessorBlocks(I.getParent()); 1137 } 1138 1139 // Add SDDbgValue nodes for any var locs here. Do so before updating 1140 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1141 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1142 // Add SDDbgValue nodes for any var locs here. Do so before updating 1143 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1144 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1145 It != End; ++It) { 1146 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1147 dropDanglingDebugInfo(Var, It->Expr); 1148 SmallVector<Value *> Values(It->Values.location_ops()); 1149 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1150 It->Values.hasArgList())) 1151 addDanglingDebugInfo(It, SDNodeOrder); 1152 } 1153 } 1154 1155 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1156 if (!isa<DbgInfoIntrinsic>(I)) 1157 ++SDNodeOrder; 1158 1159 CurInst = &I; 1160 1161 // Set inserted listener only if required. 1162 bool NodeInserted = false; 1163 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1164 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1165 if (PCSectionsMD) { 1166 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1167 DAG, [&](SDNode *) { NodeInserted = true; }); 1168 } 1169 1170 visit(I.getOpcode(), I); 1171 1172 if (!I.isTerminator() && !HasTailCall && 1173 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1174 CopyToExportRegsIfNeeded(&I); 1175 1176 // Handle metadata. 1177 if (PCSectionsMD) { 1178 auto It = NodeMap.find(&I); 1179 if (It != NodeMap.end()) { 1180 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1181 } else if (NodeInserted) { 1182 // This should not happen; if it does, don't let it go unnoticed so we can 1183 // fix it. Relevant visit*() function is probably missing a setValue(). 1184 errs() << "warning: loosing !pcsections metadata [" 1185 << I.getModule()->getName() << "]\n"; 1186 LLVM_DEBUG(I.dump()); 1187 assert(false); 1188 } 1189 } 1190 1191 CurInst = nullptr; 1192 } 1193 1194 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1195 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1196 } 1197 1198 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1199 // Note: this doesn't use InstVisitor, because it has to work with 1200 // ConstantExpr's in addition to instructions. 1201 switch (Opcode) { 1202 default: llvm_unreachable("Unknown instruction type encountered!"); 1203 // Build the switch statement using the Instruction.def file. 1204 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1205 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1206 #include "llvm/IR/Instruction.def" 1207 } 1208 } 1209 1210 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1211 DILocalVariable *Variable, 1212 DebugLoc DL, unsigned Order, 1213 RawLocationWrapper Values, 1214 DIExpression *Expression) { 1215 if (!Values.hasArgList()) 1216 return false; 1217 // For variadic dbg_values we will now insert an undef. 1218 // FIXME: We can potentially recover these! 1219 SmallVector<SDDbgOperand, 2> Locs; 1220 for (const Value *V : Values.location_ops()) { 1221 auto *Undef = UndefValue::get(V->getType()); 1222 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1223 } 1224 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1225 /*IsIndirect=*/false, DL, Order, 1226 /*IsVariadic=*/true); 1227 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1228 return true; 1229 } 1230 1231 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1232 unsigned Order) { 1233 if (!handleDanglingVariadicDebugInfo( 1234 DAG, 1235 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1236 ->getVariable(VarLoc->VariableID) 1237 .getVariable()), 1238 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1239 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1240 VarLoc, Order); 1241 } 1242 } 1243 1244 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1245 unsigned Order) { 1246 // We treat variadic dbg_values differently at this stage. 1247 if (!handleDanglingVariadicDebugInfo( 1248 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1249 DI->getWrappedLocation(), DI->getExpression())) { 1250 // TODO: Dangling debug info will eventually either be resolved or produce 1251 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1252 // between the original dbg.value location and its resolved DBG_VALUE, 1253 // which we should ideally fill with an extra Undef DBG_VALUE. 1254 assert(DI->getNumVariableLocationOps() == 1 && 1255 "DbgValueInst without an ArgList should have a single location " 1256 "operand."); 1257 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1258 } 1259 } 1260 1261 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1262 const DIExpression *Expr) { 1263 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1264 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1265 DIExpression *DanglingExpr = DDI.getExpression(); 1266 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1267 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1268 << "\n"); 1269 return true; 1270 } 1271 return false; 1272 }; 1273 1274 for (auto &DDIMI : DanglingDebugInfoMap) { 1275 DanglingDebugInfoVector &DDIV = DDIMI.second; 1276 1277 // If debug info is to be dropped, run it through final checks to see 1278 // whether it can be salvaged. 1279 for (auto &DDI : DDIV) 1280 if (isMatchingDbgValue(DDI)) 1281 salvageUnresolvedDbgValue(DDI); 1282 1283 erase_if(DDIV, isMatchingDbgValue); 1284 } 1285 } 1286 1287 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1288 // generate the debug data structures now that we've seen its definition. 1289 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1290 SDValue Val) { 1291 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1292 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1293 return; 1294 1295 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1296 for (auto &DDI : DDIV) { 1297 DebugLoc DL = DDI.getDebugLoc(); 1298 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1299 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1300 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1301 DIExpression *Expr = DDI.getExpression(); 1302 assert(Variable->isValidLocationForIntrinsic(DL) && 1303 "Expected inlined-at fields to agree"); 1304 SDDbgValue *SDV; 1305 if (Val.getNode()) { 1306 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1307 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1308 // we couldn't resolve it directly when examining the DbgValue intrinsic 1309 // in the first place we should not be more successful here). Unless we 1310 // have some test case that prove this to be correct we should avoid 1311 // calling EmitFuncArgumentDbgValue here. 1312 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1313 FuncArgumentDbgValueKind::Value, Val)) { 1314 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1315 << "\n"); 1316 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1317 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1318 // inserted after the definition of Val when emitting the instructions 1319 // after ISel. An alternative could be to teach 1320 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1321 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1322 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1323 << ValSDNodeOrder << "\n"); 1324 SDV = getDbgValue(Val, Variable, Expr, DL, 1325 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1326 DAG.AddDbgValue(SDV, false); 1327 } else 1328 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1329 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1330 } else { 1331 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1332 auto Undef = UndefValue::get(V->getType()); 1333 auto SDV = 1334 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1335 DAG.AddDbgValue(SDV, false); 1336 } 1337 } 1338 DDIV.clear(); 1339 } 1340 1341 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1342 // TODO: For the variadic implementation, instead of only checking the fail 1343 // state of `handleDebugValue`, we need know specifically which values were 1344 // invalid, so that we attempt to salvage only those values when processing 1345 // a DIArgList. 1346 Value *V = DDI.getVariableLocationOp(0); 1347 Value *OrigV = V; 1348 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1349 DIExpression *Expr = DDI.getExpression(); 1350 DebugLoc DL = DDI.getDebugLoc(); 1351 unsigned SDOrder = DDI.getSDNodeOrder(); 1352 1353 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1354 // that DW_OP_stack_value is desired. 1355 bool StackValue = true; 1356 1357 // Can this Value can be encoded without any further work? 1358 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1359 return; 1360 1361 // Attempt to salvage back through as many instructions as possible. Bail if 1362 // a non-instruction is seen, such as a constant expression or global 1363 // variable. FIXME: Further work could recover those too. 1364 while (isa<Instruction>(V)) { 1365 Instruction &VAsInst = *cast<Instruction>(V); 1366 // Temporary "0", awaiting real implementation. 1367 SmallVector<uint64_t, 16> Ops; 1368 SmallVector<Value *, 4> AdditionalValues; 1369 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1370 AdditionalValues); 1371 // If we cannot salvage any further, and haven't yet found a suitable debug 1372 // expression, bail out. 1373 if (!V) 1374 break; 1375 1376 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1377 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1378 // here for variadic dbg_values, remove that condition. 1379 if (!AdditionalValues.empty()) 1380 break; 1381 1382 // New value and expr now represent this debuginfo. 1383 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1384 1385 // Some kind of simplification occurred: check whether the operand of the 1386 // salvaged debug expression can be encoded in this DAG. 1387 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1388 LLVM_DEBUG( 1389 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1390 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1391 return; 1392 } 1393 } 1394 1395 // This was the final opportunity to salvage this debug information, and it 1396 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1397 // any earlier variable location. 1398 assert(OrigV && "V shouldn't be null"); 1399 auto *Undef = UndefValue::get(OrigV->getType()); 1400 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1401 DAG.AddDbgValue(SDV, false); 1402 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1403 << "\n"); 1404 } 1405 1406 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1407 DILocalVariable *Var, 1408 DIExpression *Expr, DebugLoc DbgLoc, 1409 unsigned Order, bool IsVariadic) { 1410 if (Values.empty()) 1411 return true; 1412 SmallVector<SDDbgOperand> LocationOps; 1413 SmallVector<SDNode *> Dependencies; 1414 for (const Value *V : Values) { 1415 // Constant value. 1416 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1417 isa<ConstantPointerNull>(V)) { 1418 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1419 continue; 1420 } 1421 1422 // Look through IntToPtr constants. 1423 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1424 if (CE->getOpcode() == Instruction::IntToPtr) { 1425 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1426 continue; 1427 } 1428 1429 // If the Value is a frame index, we can create a FrameIndex debug value 1430 // without relying on the DAG at all. 1431 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1432 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1433 if (SI != FuncInfo.StaticAllocaMap.end()) { 1434 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1435 continue; 1436 } 1437 } 1438 1439 // Do not use getValue() in here; we don't want to generate code at 1440 // this point if it hasn't been done yet. 1441 SDValue N = NodeMap[V]; 1442 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1443 N = UnusedArgNodeMap[V]; 1444 if (N.getNode()) { 1445 // Only emit func arg dbg value for non-variadic dbg.values for now. 1446 if (!IsVariadic && 1447 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1448 FuncArgumentDbgValueKind::Value, N)) 1449 return true; 1450 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1451 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1452 // describe stack slot locations. 1453 // 1454 // Consider "int x = 0; int *px = &x;". There are two kinds of 1455 // interesting debug values here after optimization: 1456 // 1457 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1458 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1459 // 1460 // Both describe the direct values of their associated variables. 1461 Dependencies.push_back(N.getNode()); 1462 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1463 continue; 1464 } 1465 LocationOps.emplace_back( 1466 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1467 continue; 1468 } 1469 1470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1471 // Special rules apply for the first dbg.values of parameter variables in a 1472 // function. Identify them by the fact they reference Argument Values, that 1473 // they're parameters, and they are parameters of the current function. We 1474 // need to let them dangle until they get an SDNode. 1475 bool IsParamOfFunc = 1476 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1477 if (IsParamOfFunc) 1478 return false; 1479 1480 // The value is not used in this block yet (or it would have an SDNode). 1481 // We still want the value to appear for the user if possible -- if it has 1482 // an associated VReg, we can refer to that instead. 1483 auto VMI = FuncInfo.ValueMap.find(V); 1484 if (VMI != FuncInfo.ValueMap.end()) { 1485 unsigned Reg = VMI->second; 1486 // If this is a PHI node, it may be split up into several MI PHI nodes 1487 // (in FunctionLoweringInfo::set). 1488 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1489 V->getType(), std::nullopt); 1490 if (RFV.occupiesMultipleRegs()) { 1491 // FIXME: We could potentially support variadic dbg_values here. 1492 if (IsVariadic) 1493 return false; 1494 unsigned Offset = 0; 1495 unsigned BitsToDescribe = 0; 1496 if (auto VarSize = Var->getSizeInBits()) 1497 BitsToDescribe = *VarSize; 1498 if (auto Fragment = Expr->getFragmentInfo()) 1499 BitsToDescribe = Fragment->SizeInBits; 1500 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1501 // Bail out if all bits are described already. 1502 if (Offset >= BitsToDescribe) 1503 break; 1504 // TODO: handle scalable vectors. 1505 unsigned RegisterSize = RegAndSize.second; 1506 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1507 ? BitsToDescribe - Offset 1508 : RegisterSize; 1509 auto FragmentExpr = DIExpression::createFragmentExpression( 1510 Expr, Offset, FragmentSize); 1511 if (!FragmentExpr) 1512 continue; 1513 SDDbgValue *SDV = DAG.getVRegDbgValue( 1514 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1515 DAG.AddDbgValue(SDV, false); 1516 Offset += RegisterSize; 1517 } 1518 return true; 1519 } 1520 // We can use simple vreg locations for variadic dbg_values as well. 1521 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1522 continue; 1523 } 1524 // We failed to create a SDDbgOperand for V. 1525 return false; 1526 } 1527 1528 // We have created a SDDbgOperand for each Value in Values. 1529 // Should use Order instead of SDNodeOrder? 1530 assert(!LocationOps.empty()); 1531 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1532 /*IsIndirect=*/false, DbgLoc, 1533 SDNodeOrder, IsVariadic); 1534 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1535 return true; 1536 } 1537 1538 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1539 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1540 for (auto &Pair : DanglingDebugInfoMap) 1541 for (auto &DDI : Pair.second) 1542 salvageUnresolvedDbgValue(DDI); 1543 clearDanglingDebugInfo(); 1544 } 1545 1546 /// getCopyFromRegs - If there was virtual register allocated for the value V 1547 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1548 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1549 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1550 SDValue Result; 1551 1552 if (It != FuncInfo.ValueMap.end()) { 1553 Register InReg = It->second; 1554 1555 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1556 DAG.getDataLayout(), InReg, Ty, 1557 std::nullopt); // This is not an ABI copy. 1558 SDValue Chain = DAG.getEntryNode(); 1559 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1560 V); 1561 resolveDanglingDebugInfo(V, Result); 1562 } 1563 1564 return Result; 1565 } 1566 1567 /// getValue - Return an SDValue for the given Value. 1568 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1569 // If we already have an SDValue for this value, use it. It's important 1570 // to do this first, so that we don't create a CopyFromReg if we already 1571 // have a regular SDValue. 1572 SDValue &N = NodeMap[V]; 1573 if (N.getNode()) return N; 1574 1575 // If there's a virtual register allocated and initialized for this 1576 // value, use it. 1577 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1578 return copyFromReg; 1579 1580 // Otherwise create a new SDValue and remember it. 1581 SDValue Val = getValueImpl(V); 1582 NodeMap[V] = Val; 1583 resolveDanglingDebugInfo(V, Val); 1584 return Val; 1585 } 1586 1587 /// getNonRegisterValue - Return an SDValue for the given Value, but 1588 /// don't look in FuncInfo.ValueMap for a virtual register. 1589 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1590 // If we already have an SDValue for this value, use it. 1591 SDValue &N = NodeMap[V]; 1592 if (N.getNode()) { 1593 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1594 // Remove the debug location from the node as the node is about to be used 1595 // in a location which may differ from the original debug location. This 1596 // is relevant to Constant and ConstantFP nodes because they can appear 1597 // as constant expressions inside PHI nodes. 1598 N->setDebugLoc(DebugLoc()); 1599 } 1600 return N; 1601 } 1602 1603 // Otherwise create a new SDValue and remember it. 1604 SDValue Val = getValueImpl(V); 1605 NodeMap[V] = Val; 1606 resolveDanglingDebugInfo(V, Val); 1607 return Val; 1608 } 1609 1610 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1611 /// Create an SDValue for the given value. 1612 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1613 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1614 1615 if (const Constant *C = dyn_cast<Constant>(V)) { 1616 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1617 1618 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1619 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1620 1621 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1622 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1623 1624 if (isa<ConstantPointerNull>(C)) { 1625 unsigned AS = V->getType()->getPointerAddressSpace(); 1626 return DAG.getConstant(0, getCurSDLoc(), 1627 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1628 } 1629 1630 if (match(C, m_VScale())) 1631 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1632 1633 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1634 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1635 1636 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1637 return DAG.getUNDEF(VT); 1638 1639 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1640 visit(CE->getOpcode(), *CE); 1641 SDValue N1 = NodeMap[V]; 1642 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1643 return N1; 1644 } 1645 1646 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1647 SmallVector<SDValue, 4> Constants; 1648 for (const Use &U : C->operands()) { 1649 SDNode *Val = getValue(U).getNode(); 1650 // If the operand is an empty aggregate, there are no values. 1651 if (!Val) continue; 1652 // Add each leaf value from the operand to the Constants list 1653 // to form a flattened list of all the values. 1654 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1655 Constants.push_back(SDValue(Val, i)); 1656 } 1657 1658 return DAG.getMergeValues(Constants, getCurSDLoc()); 1659 } 1660 1661 if (const ConstantDataSequential *CDS = 1662 dyn_cast<ConstantDataSequential>(C)) { 1663 SmallVector<SDValue, 4> Ops; 1664 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1665 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1666 // Add each leaf value from the operand to the Constants list 1667 // to form a flattened list of all the values. 1668 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1669 Ops.push_back(SDValue(Val, i)); 1670 } 1671 1672 if (isa<ArrayType>(CDS->getType())) 1673 return DAG.getMergeValues(Ops, getCurSDLoc()); 1674 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1675 } 1676 1677 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1678 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1679 "Unknown struct or array constant!"); 1680 1681 SmallVector<EVT, 4> ValueVTs; 1682 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1683 unsigned NumElts = ValueVTs.size(); 1684 if (NumElts == 0) 1685 return SDValue(); // empty struct 1686 SmallVector<SDValue, 4> Constants(NumElts); 1687 for (unsigned i = 0; i != NumElts; ++i) { 1688 EVT EltVT = ValueVTs[i]; 1689 if (isa<UndefValue>(C)) 1690 Constants[i] = DAG.getUNDEF(EltVT); 1691 else if (EltVT.isFloatingPoint()) 1692 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1693 else 1694 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1695 } 1696 1697 return DAG.getMergeValues(Constants, getCurSDLoc()); 1698 } 1699 1700 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1701 return DAG.getBlockAddress(BA, VT); 1702 1703 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1704 return getValue(Equiv->getGlobalValue()); 1705 1706 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1707 return getValue(NC->getGlobalValue()); 1708 1709 VectorType *VecTy = cast<VectorType>(V->getType()); 1710 1711 // Now that we know the number and type of the elements, get that number of 1712 // elements into the Ops array based on what kind of constant it is. 1713 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1714 SmallVector<SDValue, 16> Ops; 1715 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1716 for (unsigned i = 0; i != NumElements; ++i) 1717 Ops.push_back(getValue(CV->getOperand(i))); 1718 1719 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1720 } 1721 1722 if (isa<ConstantAggregateZero>(C)) { 1723 EVT EltVT = 1724 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1725 1726 SDValue Op; 1727 if (EltVT.isFloatingPoint()) 1728 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1729 else 1730 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1731 1732 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1733 } 1734 1735 llvm_unreachable("Unknown vector constant"); 1736 } 1737 1738 // If this is a static alloca, generate it as the frameindex instead of 1739 // computation. 1740 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1741 DenseMap<const AllocaInst*, int>::iterator SI = 1742 FuncInfo.StaticAllocaMap.find(AI); 1743 if (SI != FuncInfo.StaticAllocaMap.end()) 1744 return DAG.getFrameIndex( 1745 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1746 } 1747 1748 // If this is an instruction which fast-isel has deferred, select it now. 1749 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1750 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1751 1752 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1753 Inst->getType(), std::nullopt); 1754 SDValue Chain = DAG.getEntryNode(); 1755 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1756 } 1757 1758 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1759 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1760 1761 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1762 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1763 1764 llvm_unreachable("Can't get register for value!"); 1765 } 1766 1767 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1768 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1769 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1770 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1771 bool IsSEH = isAsynchronousEHPersonality(Pers); 1772 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1773 if (!IsSEH) 1774 CatchPadMBB->setIsEHScopeEntry(); 1775 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1776 if (IsMSVCCXX || IsCoreCLR) 1777 CatchPadMBB->setIsEHFuncletEntry(); 1778 } 1779 1780 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1781 // Update machine-CFG edge. 1782 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1783 FuncInfo.MBB->addSuccessor(TargetMBB); 1784 TargetMBB->setIsEHCatchretTarget(true); 1785 DAG.getMachineFunction().setHasEHCatchret(true); 1786 1787 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1788 bool IsSEH = isAsynchronousEHPersonality(Pers); 1789 if (IsSEH) { 1790 // If this is not a fall-through branch or optimizations are switched off, 1791 // emit the branch. 1792 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1793 TM.getOptLevel() == CodeGenOpt::None) 1794 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1795 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1796 return; 1797 } 1798 1799 // Figure out the funclet membership for the catchret's successor. 1800 // This will be used by the FuncletLayout pass to determine how to order the 1801 // BB's. 1802 // A 'catchret' returns to the outer scope's color. 1803 Value *ParentPad = I.getCatchSwitchParentPad(); 1804 const BasicBlock *SuccessorColor; 1805 if (isa<ConstantTokenNone>(ParentPad)) 1806 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1807 else 1808 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1809 assert(SuccessorColor && "No parent funclet for catchret!"); 1810 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1811 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1812 1813 // Create the terminator node. 1814 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1815 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1816 DAG.getBasicBlock(SuccessorColorMBB)); 1817 DAG.setRoot(Ret); 1818 } 1819 1820 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1821 // Don't emit any special code for the cleanuppad instruction. It just marks 1822 // the start of an EH scope/funclet. 1823 FuncInfo.MBB->setIsEHScopeEntry(); 1824 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1825 if (Pers != EHPersonality::Wasm_CXX) { 1826 FuncInfo.MBB->setIsEHFuncletEntry(); 1827 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1828 } 1829 } 1830 1831 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1832 // not match, it is OK to add only the first unwind destination catchpad to the 1833 // successors, because there will be at least one invoke instruction within the 1834 // catch scope that points to the next unwind destination, if one exists, so 1835 // CFGSort cannot mess up with BB sorting order. 1836 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1837 // call within them, and catchpads only consisting of 'catch (...)' have a 1838 // '__cxa_end_catch' call within them, both of which generate invokes in case 1839 // the next unwind destination exists, i.e., the next unwind destination is not 1840 // the caller.) 1841 // 1842 // Having at most one EH pad successor is also simpler and helps later 1843 // transformations. 1844 // 1845 // For example, 1846 // current: 1847 // invoke void @foo to ... unwind label %catch.dispatch 1848 // catch.dispatch: 1849 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1850 // catch.start: 1851 // ... 1852 // ... in this BB or some other child BB dominated by this BB there will be an 1853 // invoke that points to 'next' BB as an unwind destination 1854 // 1855 // next: ; We don't need to add this to 'current' BB's successor 1856 // ... 1857 static void findWasmUnwindDestinations( 1858 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1859 BranchProbability Prob, 1860 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1861 &UnwindDests) { 1862 while (EHPadBB) { 1863 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1864 if (isa<CleanupPadInst>(Pad)) { 1865 // Stop on cleanup pads. 1866 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1867 UnwindDests.back().first->setIsEHScopeEntry(); 1868 break; 1869 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1870 // Add the catchpad handlers to the possible destinations. We don't 1871 // continue to the unwind destination of the catchswitch for wasm. 1872 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1873 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1874 UnwindDests.back().first->setIsEHScopeEntry(); 1875 } 1876 break; 1877 } else { 1878 continue; 1879 } 1880 } 1881 } 1882 1883 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1884 /// many places it could ultimately go. In the IR, we have a single unwind 1885 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1886 /// This function skips over imaginary basic blocks that hold catchswitch 1887 /// instructions, and finds all the "real" machine 1888 /// basic block destinations. As those destinations may not be successors of 1889 /// EHPadBB, here we also calculate the edge probability to those destinations. 1890 /// The passed-in Prob is the edge probability to EHPadBB. 1891 static void findUnwindDestinations( 1892 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1893 BranchProbability Prob, 1894 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1895 &UnwindDests) { 1896 EHPersonality Personality = 1897 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1898 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1899 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1900 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1901 bool IsSEH = isAsynchronousEHPersonality(Personality); 1902 1903 if (IsWasmCXX) { 1904 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1905 assert(UnwindDests.size() <= 1 && 1906 "There should be at most one unwind destination for wasm"); 1907 return; 1908 } 1909 1910 while (EHPadBB) { 1911 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1912 BasicBlock *NewEHPadBB = nullptr; 1913 if (isa<LandingPadInst>(Pad)) { 1914 // Stop on landingpads. They are not funclets. 1915 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1916 break; 1917 } else if (isa<CleanupPadInst>(Pad)) { 1918 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1919 // personalities. 1920 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1921 UnwindDests.back().first->setIsEHScopeEntry(); 1922 UnwindDests.back().first->setIsEHFuncletEntry(); 1923 break; 1924 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1925 // Add the catchpad handlers to the possible destinations. 1926 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1927 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1928 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1929 if (IsMSVCCXX || IsCoreCLR) 1930 UnwindDests.back().first->setIsEHFuncletEntry(); 1931 if (!IsSEH) 1932 UnwindDests.back().first->setIsEHScopeEntry(); 1933 } 1934 NewEHPadBB = CatchSwitch->getUnwindDest(); 1935 } else { 1936 continue; 1937 } 1938 1939 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1940 if (BPI && NewEHPadBB) 1941 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1942 EHPadBB = NewEHPadBB; 1943 } 1944 } 1945 1946 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1947 // Update successor info. 1948 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1949 auto UnwindDest = I.getUnwindDest(); 1950 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1951 BranchProbability UnwindDestProb = 1952 (BPI && UnwindDest) 1953 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1954 : BranchProbability::getZero(); 1955 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1956 for (auto &UnwindDest : UnwindDests) { 1957 UnwindDest.first->setIsEHPad(); 1958 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1959 } 1960 FuncInfo.MBB->normalizeSuccProbs(); 1961 1962 // Create the terminator node. 1963 SDValue Ret = 1964 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1965 DAG.setRoot(Ret); 1966 } 1967 1968 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1969 report_fatal_error("visitCatchSwitch not yet implemented!"); 1970 } 1971 1972 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1973 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1974 auto &DL = DAG.getDataLayout(); 1975 SDValue Chain = getControlRoot(); 1976 SmallVector<ISD::OutputArg, 8> Outs; 1977 SmallVector<SDValue, 8> OutVals; 1978 1979 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1980 // lower 1981 // 1982 // %val = call <ty> @llvm.experimental.deoptimize() 1983 // ret <ty> %val 1984 // 1985 // differently. 1986 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1987 LowerDeoptimizingReturn(); 1988 return; 1989 } 1990 1991 if (!FuncInfo.CanLowerReturn) { 1992 unsigned DemoteReg = FuncInfo.DemoteRegister; 1993 const Function *F = I.getParent()->getParent(); 1994 1995 // Emit a store of the return value through the virtual register. 1996 // Leave Outs empty so that LowerReturn won't try to load return 1997 // registers the usual way. 1998 SmallVector<EVT, 1> PtrValueVTs; 1999 ComputeValueVTs(TLI, DL, 2000 F->getReturnType()->getPointerTo( 2001 DAG.getDataLayout().getAllocaAddrSpace()), 2002 PtrValueVTs); 2003 2004 SDValue RetPtr = 2005 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2006 SDValue RetOp = getValue(I.getOperand(0)); 2007 2008 SmallVector<EVT, 4> ValueVTs, MemVTs; 2009 SmallVector<uint64_t, 4> Offsets; 2010 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2011 &Offsets); 2012 unsigned NumValues = ValueVTs.size(); 2013 2014 SmallVector<SDValue, 4> Chains(NumValues); 2015 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2016 for (unsigned i = 0; i != NumValues; ++i) { 2017 // An aggregate return value cannot wrap around the address space, so 2018 // offsets to its parts don't wrap either. 2019 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2020 TypeSize::Fixed(Offsets[i])); 2021 2022 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2023 if (MemVTs[i] != ValueVTs[i]) 2024 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2025 Chains[i] = DAG.getStore( 2026 Chain, getCurSDLoc(), Val, 2027 // FIXME: better loc info would be nice. 2028 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2029 commonAlignment(BaseAlign, Offsets[i])); 2030 } 2031 2032 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2033 MVT::Other, Chains); 2034 } else if (I.getNumOperands() != 0) { 2035 SmallVector<EVT, 4> ValueVTs; 2036 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2037 unsigned NumValues = ValueVTs.size(); 2038 if (NumValues) { 2039 SDValue RetOp = getValue(I.getOperand(0)); 2040 2041 const Function *F = I.getParent()->getParent(); 2042 2043 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2044 I.getOperand(0)->getType(), F->getCallingConv(), 2045 /*IsVarArg*/ false, DL); 2046 2047 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2048 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2049 ExtendKind = ISD::SIGN_EXTEND; 2050 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2051 ExtendKind = ISD::ZERO_EXTEND; 2052 2053 LLVMContext &Context = F->getContext(); 2054 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2055 2056 for (unsigned j = 0; j != NumValues; ++j) { 2057 EVT VT = ValueVTs[j]; 2058 2059 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2060 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2061 2062 CallingConv::ID CC = F->getCallingConv(); 2063 2064 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2065 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2066 SmallVector<SDValue, 4> Parts(NumParts); 2067 getCopyToParts(DAG, getCurSDLoc(), 2068 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2069 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2070 2071 // 'inreg' on function refers to return value 2072 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2073 if (RetInReg) 2074 Flags.setInReg(); 2075 2076 if (I.getOperand(0)->getType()->isPointerTy()) { 2077 Flags.setPointer(); 2078 Flags.setPointerAddrSpace( 2079 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2080 } 2081 2082 if (NeedsRegBlock) { 2083 Flags.setInConsecutiveRegs(); 2084 if (j == NumValues - 1) 2085 Flags.setInConsecutiveRegsLast(); 2086 } 2087 2088 // Propagate extension type if any 2089 if (ExtendKind == ISD::SIGN_EXTEND) 2090 Flags.setSExt(); 2091 else if (ExtendKind == ISD::ZERO_EXTEND) 2092 Flags.setZExt(); 2093 2094 for (unsigned i = 0; i < NumParts; ++i) { 2095 Outs.push_back(ISD::OutputArg(Flags, 2096 Parts[i].getValueType().getSimpleVT(), 2097 VT, /*isfixed=*/true, 0, 0)); 2098 OutVals.push_back(Parts[i]); 2099 } 2100 } 2101 } 2102 } 2103 2104 // Push in swifterror virtual register as the last element of Outs. This makes 2105 // sure swifterror virtual register will be returned in the swifterror 2106 // physical register. 2107 const Function *F = I.getParent()->getParent(); 2108 if (TLI.supportSwiftError() && 2109 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2110 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2111 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2112 Flags.setSwiftError(); 2113 Outs.push_back(ISD::OutputArg( 2114 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2115 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2116 // Create SDNode for the swifterror virtual register. 2117 OutVals.push_back( 2118 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2119 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2120 EVT(TLI.getPointerTy(DL)))); 2121 } 2122 2123 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2124 CallingConv::ID CallConv = 2125 DAG.getMachineFunction().getFunction().getCallingConv(); 2126 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2127 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2128 2129 // Verify that the target's LowerReturn behaved as expected. 2130 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2131 "LowerReturn didn't return a valid chain!"); 2132 2133 // Update the DAG with the new chain value resulting from return lowering. 2134 DAG.setRoot(Chain); 2135 } 2136 2137 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2138 /// created for it, emit nodes to copy the value into the virtual 2139 /// registers. 2140 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2141 // Skip empty types 2142 if (V->getType()->isEmptyTy()) 2143 return; 2144 2145 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2146 if (VMI != FuncInfo.ValueMap.end()) { 2147 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2148 "Unused value assigned virtual registers!"); 2149 CopyValueToVirtualRegister(V, VMI->second); 2150 } 2151 } 2152 2153 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2154 /// the current basic block, add it to ValueMap now so that we'll get a 2155 /// CopyTo/FromReg. 2156 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2157 // No need to export constants. 2158 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2159 2160 // Already exported? 2161 if (FuncInfo.isExportedInst(V)) return; 2162 2163 Register Reg = FuncInfo.InitializeRegForValue(V); 2164 CopyValueToVirtualRegister(V, Reg); 2165 } 2166 2167 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2168 const BasicBlock *FromBB) { 2169 // The operands of the setcc have to be in this block. We don't know 2170 // how to export them from some other block. 2171 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2172 // Can export from current BB. 2173 if (VI->getParent() == FromBB) 2174 return true; 2175 2176 // Is already exported, noop. 2177 return FuncInfo.isExportedInst(V); 2178 } 2179 2180 // If this is an argument, we can export it if the BB is the entry block or 2181 // if it is already exported. 2182 if (isa<Argument>(V)) { 2183 if (FromBB->isEntryBlock()) 2184 return true; 2185 2186 // Otherwise, can only export this if it is already exported. 2187 return FuncInfo.isExportedInst(V); 2188 } 2189 2190 // Otherwise, constants can always be exported. 2191 return true; 2192 } 2193 2194 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2195 BranchProbability 2196 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2197 const MachineBasicBlock *Dst) const { 2198 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2199 const BasicBlock *SrcBB = Src->getBasicBlock(); 2200 const BasicBlock *DstBB = Dst->getBasicBlock(); 2201 if (!BPI) { 2202 // If BPI is not available, set the default probability as 1 / N, where N is 2203 // the number of successors. 2204 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2205 return BranchProbability(1, SuccSize); 2206 } 2207 return BPI->getEdgeProbability(SrcBB, DstBB); 2208 } 2209 2210 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2211 MachineBasicBlock *Dst, 2212 BranchProbability Prob) { 2213 if (!FuncInfo.BPI) 2214 Src->addSuccessorWithoutProb(Dst); 2215 else { 2216 if (Prob.isUnknown()) 2217 Prob = getEdgeProbability(Src, Dst); 2218 Src->addSuccessor(Dst, Prob); 2219 } 2220 } 2221 2222 static bool InBlock(const Value *V, const BasicBlock *BB) { 2223 if (const Instruction *I = dyn_cast<Instruction>(V)) 2224 return I->getParent() == BB; 2225 return true; 2226 } 2227 2228 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2229 /// This function emits a branch and is used at the leaves of an OR or an 2230 /// AND operator tree. 2231 void 2232 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2233 MachineBasicBlock *TBB, 2234 MachineBasicBlock *FBB, 2235 MachineBasicBlock *CurBB, 2236 MachineBasicBlock *SwitchBB, 2237 BranchProbability TProb, 2238 BranchProbability FProb, 2239 bool InvertCond) { 2240 const BasicBlock *BB = CurBB->getBasicBlock(); 2241 2242 // If the leaf of the tree is a comparison, merge the condition into 2243 // the caseblock. 2244 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2245 // The operands of the cmp have to be in this block. We don't know 2246 // how to export them from some other block. If this is the first block 2247 // of the sequence, no exporting is needed. 2248 if (CurBB == SwitchBB || 2249 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2250 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2251 ISD::CondCode Condition; 2252 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2253 ICmpInst::Predicate Pred = 2254 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2255 Condition = getICmpCondCode(Pred); 2256 } else { 2257 const FCmpInst *FC = cast<FCmpInst>(Cond); 2258 FCmpInst::Predicate Pred = 2259 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2260 Condition = getFCmpCondCode(Pred); 2261 if (TM.Options.NoNaNsFPMath) 2262 Condition = getFCmpCodeWithoutNaN(Condition); 2263 } 2264 2265 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2266 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2267 SL->SwitchCases.push_back(CB); 2268 return; 2269 } 2270 } 2271 2272 // Create a CaseBlock record representing this branch. 2273 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2274 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2275 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2276 SL->SwitchCases.push_back(CB); 2277 } 2278 2279 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2280 MachineBasicBlock *TBB, 2281 MachineBasicBlock *FBB, 2282 MachineBasicBlock *CurBB, 2283 MachineBasicBlock *SwitchBB, 2284 Instruction::BinaryOps Opc, 2285 BranchProbability TProb, 2286 BranchProbability FProb, 2287 bool InvertCond) { 2288 // Skip over not part of the tree and remember to invert op and operands at 2289 // next level. 2290 Value *NotCond; 2291 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2292 InBlock(NotCond, CurBB->getBasicBlock())) { 2293 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2294 !InvertCond); 2295 return; 2296 } 2297 2298 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2299 const Value *BOpOp0, *BOpOp1; 2300 // Compute the effective opcode for Cond, taking into account whether it needs 2301 // to be inverted, e.g. 2302 // and (not (or A, B)), C 2303 // gets lowered as 2304 // and (and (not A, not B), C) 2305 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2306 if (BOp) { 2307 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2308 ? Instruction::And 2309 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2310 ? Instruction::Or 2311 : (Instruction::BinaryOps)0); 2312 if (InvertCond) { 2313 if (BOpc == Instruction::And) 2314 BOpc = Instruction::Or; 2315 else if (BOpc == Instruction::Or) 2316 BOpc = Instruction::And; 2317 } 2318 } 2319 2320 // If this node is not part of the or/and tree, emit it as a branch. 2321 // Note that all nodes in the tree should have same opcode. 2322 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2323 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2324 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2325 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2326 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2327 TProb, FProb, InvertCond); 2328 return; 2329 } 2330 2331 // Create TmpBB after CurBB. 2332 MachineFunction::iterator BBI(CurBB); 2333 MachineFunction &MF = DAG.getMachineFunction(); 2334 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2335 CurBB->getParent()->insert(++BBI, TmpBB); 2336 2337 if (Opc == Instruction::Or) { 2338 // Codegen X | Y as: 2339 // BB1: 2340 // jmp_if_X TBB 2341 // jmp TmpBB 2342 // TmpBB: 2343 // jmp_if_Y TBB 2344 // jmp FBB 2345 // 2346 2347 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2348 // The requirement is that 2349 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2350 // = TrueProb for original BB. 2351 // Assuming the original probabilities are A and B, one choice is to set 2352 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2353 // A/(1+B) and 2B/(1+B). This choice assumes that 2354 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2355 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2356 // TmpBB, but the math is more complicated. 2357 2358 auto NewTrueProb = TProb / 2; 2359 auto NewFalseProb = TProb / 2 + FProb; 2360 // Emit the LHS condition. 2361 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2362 NewFalseProb, InvertCond); 2363 2364 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2365 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2366 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2367 // Emit the RHS condition into TmpBB. 2368 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2369 Probs[1], InvertCond); 2370 } else { 2371 assert(Opc == Instruction::And && "Unknown merge op!"); 2372 // Codegen X & Y as: 2373 // BB1: 2374 // jmp_if_X TmpBB 2375 // jmp FBB 2376 // TmpBB: 2377 // jmp_if_Y TBB 2378 // jmp FBB 2379 // 2380 // This requires creation of TmpBB after CurBB. 2381 2382 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2383 // The requirement is that 2384 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2385 // = FalseProb for original BB. 2386 // Assuming the original probabilities are A and B, one choice is to set 2387 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2388 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2389 // TrueProb for BB1 * FalseProb for TmpBB. 2390 2391 auto NewTrueProb = TProb + FProb / 2; 2392 auto NewFalseProb = FProb / 2; 2393 // Emit the LHS condition. 2394 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2395 NewFalseProb, InvertCond); 2396 2397 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2398 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2399 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2400 // Emit the RHS condition into TmpBB. 2401 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2402 Probs[1], InvertCond); 2403 } 2404 } 2405 2406 /// If the set of cases should be emitted as a series of branches, return true. 2407 /// If we should emit this as a bunch of and/or'd together conditions, return 2408 /// false. 2409 bool 2410 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2411 if (Cases.size() != 2) return true; 2412 2413 // If this is two comparisons of the same values or'd or and'd together, they 2414 // will get folded into a single comparison, so don't emit two blocks. 2415 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2416 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2417 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2418 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2419 return false; 2420 } 2421 2422 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2423 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2424 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2425 Cases[0].CC == Cases[1].CC && 2426 isa<Constant>(Cases[0].CmpRHS) && 2427 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2428 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2429 return false; 2430 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2431 return false; 2432 } 2433 2434 return true; 2435 } 2436 2437 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2438 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2439 2440 // Update machine-CFG edges. 2441 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2442 2443 if (I.isUnconditional()) { 2444 // Update machine-CFG edges. 2445 BrMBB->addSuccessor(Succ0MBB); 2446 2447 // If this is not a fall-through branch or optimizations are switched off, 2448 // emit the branch. 2449 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2450 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2451 MVT::Other, getControlRoot(), 2452 DAG.getBasicBlock(Succ0MBB))); 2453 2454 return; 2455 } 2456 2457 // If this condition is one of the special cases we handle, do special stuff 2458 // now. 2459 const Value *CondVal = I.getCondition(); 2460 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2461 2462 // If this is a series of conditions that are or'd or and'd together, emit 2463 // this as a sequence of branches instead of setcc's with and/or operations. 2464 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2465 // unpredictable branches, and vector extracts because those jumps are likely 2466 // expensive for any target), this should improve performance. 2467 // For example, instead of something like: 2468 // cmp A, B 2469 // C = seteq 2470 // cmp D, E 2471 // F = setle 2472 // or C, F 2473 // jnz foo 2474 // Emit: 2475 // cmp A, B 2476 // je foo 2477 // cmp D, E 2478 // jle foo 2479 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2480 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2481 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2482 Value *Vec; 2483 const Value *BOp0, *BOp1; 2484 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2485 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2486 Opcode = Instruction::And; 2487 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2488 Opcode = Instruction::Or; 2489 2490 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2491 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2492 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2493 getEdgeProbability(BrMBB, Succ0MBB), 2494 getEdgeProbability(BrMBB, Succ1MBB), 2495 /*InvertCond=*/false); 2496 // If the compares in later blocks need to use values not currently 2497 // exported from this block, export them now. This block should always 2498 // be the first entry. 2499 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2500 2501 // Allow some cases to be rejected. 2502 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2503 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2504 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2505 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2506 } 2507 2508 // Emit the branch for this block. 2509 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2510 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2511 return; 2512 } 2513 2514 // Okay, we decided not to do this, remove any inserted MBB's and clear 2515 // SwitchCases. 2516 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2517 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2518 2519 SL->SwitchCases.clear(); 2520 } 2521 } 2522 2523 // Create a CaseBlock record representing this branch. 2524 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2525 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2526 2527 // Use visitSwitchCase to actually insert the fast branch sequence for this 2528 // cond branch. 2529 visitSwitchCase(CB, BrMBB); 2530 } 2531 2532 /// visitSwitchCase - Emits the necessary code to represent a single node in 2533 /// the binary search tree resulting from lowering a switch instruction. 2534 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2535 MachineBasicBlock *SwitchBB) { 2536 SDValue Cond; 2537 SDValue CondLHS = getValue(CB.CmpLHS); 2538 SDLoc dl = CB.DL; 2539 2540 if (CB.CC == ISD::SETTRUE) { 2541 // Branch or fall through to TrueBB. 2542 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2543 SwitchBB->normalizeSuccProbs(); 2544 if (CB.TrueBB != NextBlock(SwitchBB)) { 2545 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2546 DAG.getBasicBlock(CB.TrueBB))); 2547 } 2548 return; 2549 } 2550 2551 auto &TLI = DAG.getTargetLoweringInfo(); 2552 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2553 2554 // Build the setcc now. 2555 if (!CB.CmpMHS) { 2556 // Fold "(X == true)" to X and "(X == false)" to !X to 2557 // handle common cases produced by branch lowering. 2558 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2559 CB.CC == ISD::SETEQ) 2560 Cond = CondLHS; 2561 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2562 CB.CC == ISD::SETEQ) { 2563 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2564 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2565 } else { 2566 SDValue CondRHS = getValue(CB.CmpRHS); 2567 2568 // If a pointer's DAG type is larger than its memory type then the DAG 2569 // values are zero-extended. This breaks signed comparisons so truncate 2570 // back to the underlying type before doing the compare. 2571 if (CondLHS.getValueType() != MemVT) { 2572 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2573 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2574 } 2575 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2576 } 2577 } else { 2578 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2579 2580 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2581 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2582 2583 SDValue CmpOp = getValue(CB.CmpMHS); 2584 EVT VT = CmpOp.getValueType(); 2585 2586 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2587 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2588 ISD::SETLE); 2589 } else { 2590 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2591 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2592 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2593 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2594 } 2595 } 2596 2597 // Update successor info 2598 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2599 // TrueBB and FalseBB are always different unless the incoming IR is 2600 // degenerate. This only happens when running llc on weird IR. 2601 if (CB.TrueBB != CB.FalseBB) 2602 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2603 SwitchBB->normalizeSuccProbs(); 2604 2605 // If the lhs block is the next block, invert the condition so that we can 2606 // fall through to the lhs instead of the rhs block. 2607 if (CB.TrueBB == NextBlock(SwitchBB)) { 2608 std::swap(CB.TrueBB, CB.FalseBB); 2609 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2610 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2611 } 2612 2613 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2614 MVT::Other, getControlRoot(), Cond, 2615 DAG.getBasicBlock(CB.TrueBB)); 2616 2617 setValue(CurInst, BrCond); 2618 2619 // Insert the false branch. Do this even if it's a fall through branch, 2620 // this makes it easier to do DAG optimizations which require inverting 2621 // the branch condition. 2622 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2623 DAG.getBasicBlock(CB.FalseBB)); 2624 2625 DAG.setRoot(BrCond); 2626 } 2627 2628 /// visitJumpTable - Emit JumpTable node in the current MBB 2629 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2630 // Emit the code for the jump table 2631 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2632 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2633 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2634 JT.Reg, PTy); 2635 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2636 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2637 MVT::Other, Index.getValue(1), 2638 Table, Index); 2639 DAG.setRoot(BrJumpTable); 2640 } 2641 2642 /// visitJumpTableHeader - This function emits necessary code to produce index 2643 /// in the JumpTable from switch case. 2644 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2645 JumpTableHeader &JTH, 2646 MachineBasicBlock *SwitchBB) { 2647 SDLoc dl = getCurSDLoc(); 2648 2649 // Subtract the lowest switch case value from the value being switched on. 2650 SDValue SwitchOp = getValue(JTH.SValue); 2651 EVT VT = SwitchOp.getValueType(); 2652 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2653 DAG.getConstant(JTH.First, dl, VT)); 2654 2655 // The SDNode we just created, which holds the value being switched on minus 2656 // the smallest case value, needs to be copied to a virtual register so it 2657 // can be used as an index into the jump table in a subsequent basic block. 2658 // This value may be smaller or larger than the target's pointer type, and 2659 // therefore require extension or truncating. 2660 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2661 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2662 2663 unsigned JumpTableReg = 2664 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2665 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2666 JumpTableReg, SwitchOp); 2667 JT.Reg = JumpTableReg; 2668 2669 if (!JTH.FallthroughUnreachable) { 2670 // Emit the range check for the jump table, and branch to the default block 2671 // for the switch statement if the value being switched on exceeds the 2672 // largest case in the switch. 2673 SDValue CMP = DAG.getSetCC( 2674 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2675 Sub.getValueType()), 2676 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2677 2678 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2679 MVT::Other, CopyTo, CMP, 2680 DAG.getBasicBlock(JT.Default)); 2681 2682 // Avoid emitting unnecessary branches to the next block. 2683 if (JT.MBB != NextBlock(SwitchBB)) 2684 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2685 DAG.getBasicBlock(JT.MBB)); 2686 2687 DAG.setRoot(BrCond); 2688 } else { 2689 // Avoid emitting unnecessary branches to the next block. 2690 if (JT.MBB != NextBlock(SwitchBB)) 2691 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2692 DAG.getBasicBlock(JT.MBB))); 2693 else 2694 DAG.setRoot(CopyTo); 2695 } 2696 } 2697 2698 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2699 /// variable if there exists one. 2700 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2701 SDValue &Chain) { 2702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2703 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2704 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2705 MachineFunction &MF = DAG.getMachineFunction(); 2706 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2707 MachineSDNode *Node = 2708 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2709 if (Global) { 2710 MachinePointerInfo MPInfo(Global); 2711 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2712 MachineMemOperand::MODereferenceable; 2713 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2714 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2715 DAG.setNodeMemRefs(Node, {MemRef}); 2716 } 2717 if (PtrTy != PtrMemTy) 2718 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2719 return SDValue(Node, 0); 2720 } 2721 2722 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2723 /// tail spliced into a stack protector check success bb. 2724 /// 2725 /// For a high level explanation of how this fits into the stack protector 2726 /// generation see the comment on the declaration of class 2727 /// StackProtectorDescriptor. 2728 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2729 MachineBasicBlock *ParentBB) { 2730 2731 // First create the loads to the guard/stack slot for the comparison. 2732 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2733 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2734 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2735 2736 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2737 int FI = MFI.getStackProtectorIndex(); 2738 2739 SDValue Guard; 2740 SDLoc dl = getCurSDLoc(); 2741 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2742 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2743 Align Align = 2744 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2745 2746 // Generate code to load the content of the guard slot. 2747 SDValue GuardVal = DAG.getLoad( 2748 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2749 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2750 MachineMemOperand::MOVolatile); 2751 2752 if (TLI.useStackGuardXorFP()) 2753 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2754 2755 // Retrieve guard check function, nullptr if instrumentation is inlined. 2756 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2757 // The target provides a guard check function to validate the guard value. 2758 // Generate a call to that function with the content of the guard slot as 2759 // argument. 2760 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2761 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2762 2763 TargetLowering::ArgListTy Args; 2764 TargetLowering::ArgListEntry Entry; 2765 Entry.Node = GuardVal; 2766 Entry.Ty = FnTy->getParamType(0); 2767 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2768 Entry.IsInReg = true; 2769 Args.push_back(Entry); 2770 2771 TargetLowering::CallLoweringInfo CLI(DAG); 2772 CLI.setDebugLoc(getCurSDLoc()) 2773 .setChain(DAG.getEntryNode()) 2774 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2775 getValue(GuardCheckFn), std::move(Args)); 2776 2777 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2778 DAG.setRoot(Result.second); 2779 return; 2780 } 2781 2782 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2783 // Otherwise, emit a volatile load to retrieve the stack guard value. 2784 SDValue Chain = DAG.getEntryNode(); 2785 if (TLI.useLoadStackGuardNode()) { 2786 Guard = getLoadStackGuard(DAG, dl, Chain); 2787 } else { 2788 const Value *IRGuard = TLI.getSDagStackGuard(M); 2789 SDValue GuardPtr = getValue(IRGuard); 2790 2791 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2792 MachinePointerInfo(IRGuard, 0), Align, 2793 MachineMemOperand::MOVolatile); 2794 } 2795 2796 // Perform the comparison via a getsetcc. 2797 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2798 *DAG.getContext(), 2799 Guard.getValueType()), 2800 Guard, GuardVal, ISD::SETNE); 2801 2802 // If the guard/stackslot do not equal, branch to failure MBB. 2803 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2804 MVT::Other, GuardVal.getOperand(0), 2805 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2806 // Otherwise branch to success MBB. 2807 SDValue Br = DAG.getNode(ISD::BR, dl, 2808 MVT::Other, BrCond, 2809 DAG.getBasicBlock(SPD.getSuccessMBB())); 2810 2811 DAG.setRoot(Br); 2812 } 2813 2814 /// Codegen the failure basic block for a stack protector check. 2815 /// 2816 /// A failure stack protector machine basic block consists simply of a call to 2817 /// __stack_chk_fail(). 2818 /// 2819 /// For a high level explanation of how this fits into the stack protector 2820 /// generation see the comment on the declaration of class 2821 /// StackProtectorDescriptor. 2822 void 2823 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2824 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2825 TargetLowering::MakeLibCallOptions CallOptions; 2826 CallOptions.setDiscardResult(true); 2827 SDValue Chain = 2828 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2829 std::nullopt, CallOptions, getCurSDLoc()) 2830 .second; 2831 // On PS4/PS5, the "return address" must still be within the calling 2832 // function, even if it's at the very end, so emit an explicit TRAP here. 2833 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2834 if (TM.getTargetTriple().isPS()) 2835 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2836 // WebAssembly needs an unreachable instruction after a non-returning call, 2837 // because the function return type can be different from __stack_chk_fail's 2838 // return type (void). 2839 if (TM.getTargetTriple().isWasm()) 2840 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2841 2842 DAG.setRoot(Chain); 2843 } 2844 2845 /// visitBitTestHeader - This function emits necessary code to produce value 2846 /// suitable for "bit tests" 2847 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2848 MachineBasicBlock *SwitchBB) { 2849 SDLoc dl = getCurSDLoc(); 2850 2851 // Subtract the minimum value. 2852 SDValue SwitchOp = getValue(B.SValue); 2853 EVT VT = SwitchOp.getValueType(); 2854 SDValue RangeSub = 2855 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2856 2857 // Determine the type of the test operands. 2858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2859 bool UsePtrType = false; 2860 if (!TLI.isTypeLegal(VT)) { 2861 UsePtrType = true; 2862 } else { 2863 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2864 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2865 // Switch table case range are encoded into series of masks. 2866 // Just use pointer type, it's guaranteed to fit. 2867 UsePtrType = true; 2868 break; 2869 } 2870 } 2871 SDValue Sub = RangeSub; 2872 if (UsePtrType) { 2873 VT = TLI.getPointerTy(DAG.getDataLayout()); 2874 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2875 } 2876 2877 B.RegVT = VT.getSimpleVT(); 2878 B.Reg = FuncInfo.CreateReg(B.RegVT); 2879 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2880 2881 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2882 2883 if (!B.FallthroughUnreachable) 2884 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2885 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2886 SwitchBB->normalizeSuccProbs(); 2887 2888 SDValue Root = CopyTo; 2889 if (!B.FallthroughUnreachable) { 2890 // Conditional branch to the default block. 2891 SDValue RangeCmp = DAG.getSetCC(dl, 2892 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2893 RangeSub.getValueType()), 2894 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2895 ISD::SETUGT); 2896 2897 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2898 DAG.getBasicBlock(B.Default)); 2899 } 2900 2901 // Avoid emitting unnecessary branches to the next block. 2902 if (MBB != NextBlock(SwitchBB)) 2903 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2904 2905 DAG.setRoot(Root); 2906 } 2907 2908 /// visitBitTestCase - this function produces one "bit test" 2909 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2910 MachineBasicBlock* NextMBB, 2911 BranchProbability BranchProbToNext, 2912 unsigned Reg, 2913 BitTestCase &B, 2914 MachineBasicBlock *SwitchBB) { 2915 SDLoc dl = getCurSDLoc(); 2916 MVT VT = BB.RegVT; 2917 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2918 SDValue Cmp; 2919 unsigned PopCount = llvm::popcount(B.Mask); 2920 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2921 if (PopCount == 1) { 2922 // Testing for a single bit; just compare the shift count with what it 2923 // would need to be to shift a 1 bit in that position. 2924 Cmp = DAG.getSetCC( 2925 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2926 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2927 ISD::SETEQ); 2928 } else if (PopCount == BB.Range) { 2929 // There is only one zero bit in the range, test for it directly. 2930 Cmp = DAG.getSetCC( 2931 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2932 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2933 } else { 2934 // Make desired shift 2935 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2936 DAG.getConstant(1, dl, VT), ShiftOp); 2937 2938 // Emit bit tests and jumps 2939 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2940 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2941 Cmp = DAG.getSetCC( 2942 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2943 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2944 } 2945 2946 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2947 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2948 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2949 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2950 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2951 // one as they are relative probabilities (and thus work more like weights), 2952 // and hence we need to normalize them to let the sum of them become one. 2953 SwitchBB->normalizeSuccProbs(); 2954 2955 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2956 MVT::Other, getControlRoot(), 2957 Cmp, DAG.getBasicBlock(B.TargetBB)); 2958 2959 // Avoid emitting unnecessary branches to the next block. 2960 if (NextMBB != NextBlock(SwitchBB)) 2961 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2962 DAG.getBasicBlock(NextMBB)); 2963 2964 DAG.setRoot(BrAnd); 2965 } 2966 2967 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2968 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2969 2970 // Retrieve successors. Look through artificial IR level blocks like 2971 // catchswitch for successors. 2972 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2973 const BasicBlock *EHPadBB = I.getSuccessor(1); 2974 2975 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2976 // have to do anything here to lower funclet bundles. 2977 assert(!I.hasOperandBundlesOtherThan( 2978 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2979 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2980 LLVMContext::OB_cfguardtarget, 2981 LLVMContext::OB_clang_arc_attachedcall}) && 2982 "Cannot lower invokes with arbitrary operand bundles yet!"); 2983 2984 const Value *Callee(I.getCalledOperand()); 2985 const Function *Fn = dyn_cast<Function>(Callee); 2986 if (isa<InlineAsm>(Callee)) 2987 visitInlineAsm(I, EHPadBB); 2988 else if (Fn && Fn->isIntrinsic()) { 2989 switch (Fn->getIntrinsicID()) { 2990 default: 2991 llvm_unreachable("Cannot invoke this intrinsic"); 2992 case Intrinsic::donothing: 2993 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2994 case Intrinsic::seh_try_begin: 2995 case Intrinsic::seh_scope_begin: 2996 case Intrinsic::seh_try_end: 2997 case Intrinsic::seh_scope_end: 2998 break; 2999 case Intrinsic::experimental_patchpoint_void: 3000 case Intrinsic::experimental_patchpoint_i64: 3001 visitPatchpoint(I, EHPadBB); 3002 break; 3003 case Intrinsic::experimental_gc_statepoint: 3004 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3005 break; 3006 case Intrinsic::wasm_rethrow: { 3007 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3008 // special because it can be invoked, so we manually lower it to a DAG 3009 // node here. 3010 SmallVector<SDValue, 8> Ops; 3011 Ops.push_back(getRoot()); // inchain 3012 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3013 Ops.push_back( 3014 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3015 TLI.getPointerTy(DAG.getDataLayout()))); 3016 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3017 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3018 break; 3019 } 3020 } 3021 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3022 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3023 // Eventually we will support lowering the @llvm.experimental.deoptimize 3024 // intrinsic, and right now there are no plans to support other intrinsics 3025 // with deopt state. 3026 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3027 } else { 3028 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3029 } 3030 3031 // If the value of the invoke is used outside of its defining block, make it 3032 // available as a virtual register. 3033 // We already took care of the exported value for the statepoint instruction 3034 // during call to the LowerStatepoint. 3035 if (!isa<GCStatepointInst>(I)) { 3036 CopyToExportRegsIfNeeded(&I); 3037 } 3038 3039 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3040 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3041 BranchProbability EHPadBBProb = 3042 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3043 : BranchProbability::getZero(); 3044 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3045 3046 // Update successor info. 3047 addSuccessorWithProb(InvokeMBB, Return); 3048 for (auto &UnwindDest : UnwindDests) { 3049 UnwindDest.first->setIsEHPad(); 3050 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3051 } 3052 InvokeMBB->normalizeSuccProbs(); 3053 3054 // Drop into normal successor. 3055 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3056 DAG.getBasicBlock(Return))); 3057 } 3058 3059 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3060 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3061 3062 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3063 // have to do anything here to lower funclet bundles. 3064 assert(!I.hasOperandBundlesOtherThan( 3065 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3066 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3067 3068 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3069 visitInlineAsm(I); 3070 CopyToExportRegsIfNeeded(&I); 3071 3072 // Retrieve successors. 3073 SmallPtrSet<BasicBlock *, 8> Dests; 3074 Dests.insert(I.getDefaultDest()); 3075 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3076 3077 // Update successor info. 3078 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3079 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3080 BasicBlock *Dest = I.getIndirectDest(i); 3081 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3082 Target->setIsInlineAsmBrIndirectTarget(); 3083 Target->setMachineBlockAddressTaken(); 3084 Target->setLabelMustBeEmitted(); 3085 // Don't add duplicate machine successors. 3086 if (Dests.insert(Dest).second) 3087 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3088 } 3089 CallBrMBB->normalizeSuccProbs(); 3090 3091 // Drop into default successor. 3092 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3093 MVT::Other, getControlRoot(), 3094 DAG.getBasicBlock(Return))); 3095 } 3096 3097 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3098 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3099 } 3100 3101 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3102 assert(FuncInfo.MBB->isEHPad() && 3103 "Call to landingpad not in landing pad!"); 3104 3105 // If there aren't registers to copy the values into (e.g., during SjLj 3106 // exceptions), then don't bother to create these DAG nodes. 3107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3108 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3109 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3110 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3111 return; 3112 3113 // If landingpad's return type is token type, we don't create DAG nodes 3114 // for its exception pointer and selector value. The extraction of exception 3115 // pointer or selector value from token type landingpads is not currently 3116 // supported. 3117 if (LP.getType()->isTokenTy()) 3118 return; 3119 3120 SmallVector<EVT, 2> ValueVTs; 3121 SDLoc dl = getCurSDLoc(); 3122 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3123 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3124 3125 // Get the two live-in registers as SDValues. The physregs have already been 3126 // copied into virtual registers. 3127 SDValue Ops[2]; 3128 if (FuncInfo.ExceptionPointerVirtReg) { 3129 Ops[0] = DAG.getZExtOrTrunc( 3130 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3131 FuncInfo.ExceptionPointerVirtReg, 3132 TLI.getPointerTy(DAG.getDataLayout())), 3133 dl, ValueVTs[0]); 3134 } else { 3135 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3136 } 3137 Ops[1] = DAG.getZExtOrTrunc( 3138 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3139 FuncInfo.ExceptionSelectorVirtReg, 3140 TLI.getPointerTy(DAG.getDataLayout())), 3141 dl, ValueVTs[1]); 3142 3143 // Merge into one. 3144 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3145 DAG.getVTList(ValueVTs), Ops); 3146 setValue(&LP, Res); 3147 } 3148 3149 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3150 MachineBasicBlock *Last) { 3151 // Update JTCases. 3152 for (JumpTableBlock &JTB : SL->JTCases) 3153 if (JTB.first.HeaderBB == First) 3154 JTB.first.HeaderBB = Last; 3155 3156 // Update BitTestCases. 3157 for (BitTestBlock &BTB : SL->BitTestCases) 3158 if (BTB.Parent == First) 3159 BTB.Parent = Last; 3160 } 3161 3162 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3163 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3164 3165 // Update machine-CFG edges with unique successors. 3166 SmallSet<BasicBlock*, 32> Done; 3167 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3168 BasicBlock *BB = I.getSuccessor(i); 3169 bool Inserted = Done.insert(BB).second; 3170 if (!Inserted) 3171 continue; 3172 3173 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3174 addSuccessorWithProb(IndirectBrMBB, Succ); 3175 } 3176 IndirectBrMBB->normalizeSuccProbs(); 3177 3178 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3179 MVT::Other, getControlRoot(), 3180 getValue(I.getAddress()))); 3181 } 3182 3183 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3184 if (!DAG.getTarget().Options.TrapUnreachable) 3185 return; 3186 3187 // We may be able to ignore unreachable behind a noreturn call. 3188 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3189 const BasicBlock &BB = *I.getParent(); 3190 if (&I != &BB.front()) { 3191 BasicBlock::const_iterator PredI = 3192 std::prev(BasicBlock::const_iterator(&I)); 3193 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3194 if (Call->doesNotReturn()) 3195 return; 3196 } 3197 } 3198 } 3199 3200 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3201 } 3202 3203 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3204 SDNodeFlags Flags; 3205 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3206 Flags.copyFMF(*FPOp); 3207 3208 SDValue Op = getValue(I.getOperand(0)); 3209 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3210 Op, Flags); 3211 setValue(&I, UnNodeValue); 3212 } 3213 3214 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3215 SDNodeFlags Flags; 3216 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3217 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3218 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3219 } 3220 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3221 Flags.setExact(ExactOp->isExact()); 3222 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3223 Flags.copyFMF(*FPOp); 3224 3225 SDValue Op1 = getValue(I.getOperand(0)); 3226 SDValue Op2 = getValue(I.getOperand(1)); 3227 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3228 Op1, Op2, Flags); 3229 setValue(&I, BinNodeValue); 3230 } 3231 3232 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3233 SDValue Op1 = getValue(I.getOperand(0)); 3234 SDValue Op2 = getValue(I.getOperand(1)); 3235 3236 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3237 Op1.getValueType(), DAG.getDataLayout()); 3238 3239 // Coerce the shift amount to the right type if we can. This exposes the 3240 // truncate or zext to optimization early. 3241 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3242 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3243 "Unexpected shift type"); 3244 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3245 } 3246 3247 bool nuw = false; 3248 bool nsw = false; 3249 bool exact = false; 3250 3251 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3252 3253 if (const OverflowingBinaryOperator *OFBinOp = 3254 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3255 nuw = OFBinOp->hasNoUnsignedWrap(); 3256 nsw = OFBinOp->hasNoSignedWrap(); 3257 } 3258 if (const PossiblyExactOperator *ExactOp = 3259 dyn_cast<const PossiblyExactOperator>(&I)) 3260 exact = ExactOp->isExact(); 3261 } 3262 SDNodeFlags Flags; 3263 Flags.setExact(exact); 3264 Flags.setNoSignedWrap(nsw); 3265 Flags.setNoUnsignedWrap(nuw); 3266 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3267 Flags); 3268 setValue(&I, Res); 3269 } 3270 3271 void SelectionDAGBuilder::visitSDiv(const User &I) { 3272 SDValue Op1 = getValue(I.getOperand(0)); 3273 SDValue Op2 = getValue(I.getOperand(1)); 3274 3275 SDNodeFlags Flags; 3276 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3277 cast<PossiblyExactOperator>(&I)->isExact()); 3278 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3279 Op2, Flags)); 3280 } 3281 3282 void SelectionDAGBuilder::visitICmp(const User &I) { 3283 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3284 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3285 predicate = IC->getPredicate(); 3286 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3287 predicate = ICmpInst::Predicate(IC->getPredicate()); 3288 SDValue Op1 = getValue(I.getOperand(0)); 3289 SDValue Op2 = getValue(I.getOperand(1)); 3290 ISD::CondCode Opcode = getICmpCondCode(predicate); 3291 3292 auto &TLI = DAG.getTargetLoweringInfo(); 3293 EVT MemVT = 3294 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3295 3296 // If a pointer's DAG type is larger than its memory type then the DAG values 3297 // are zero-extended. This breaks signed comparisons so truncate back to the 3298 // underlying type before doing the compare. 3299 if (Op1.getValueType() != MemVT) { 3300 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3301 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3302 } 3303 3304 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3305 I.getType()); 3306 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3307 } 3308 3309 void SelectionDAGBuilder::visitFCmp(const User &I) { 3310 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3311 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3312 predicate = FC->getPredicate(); 3313 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3314 predicate = FCmpInst::Predicate(FC->getPredicate()); 3315 SDValue Op1 = getValue(I.getOperand(0)); 3316 SDValue Op2 = getValue(I.getOperand(1)); 3317 3318 ISD::CondCode Condition = getFCmpCondCode(predicate); 3319 auto *FPMO = cast<FPMathOperator>(&I); 3320 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3321 Condition = getFCmpCodeWithoutNaN(Condition); 3322 3323 SDNodeFlags Flags; 3324 Flags.copyFMF(*FPMO); 3325 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3326 3327 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3328 I.getType()); 3329 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3330 } 3331 3332 // Check if the condition of the select has one use or two users that are both 3333 // selects with the same condition. 3334 static bool hasOnlySelectUsers(const Value *Cond) { 3335 return llvm::all_of(Cond->users(), [](const Value *V) { 3336 return isa<SelectInst>(V); 3337 }); 3338 } 3339 3340 void SelectionDAGBuilder::visitSelect(const User &I) { 3341 SmallVector<EVT, 4> ValueVTs; 3342 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3343 ValueVTs); 3344 unsigned NumValues = ValueVTs.size(); 3345 if (NumValues == 0) return; 3346 3347 SmallVector<SDValue, 4> Values(NumValues); 3348 SDValue Cond = getValue(I.getOperand(0)); 3349 SDValue LHSVal = getValue(I.getOperand(1)); 3350 SDValue RHSVal = getValue(I.getOperand(2)); 3351 SmallVector<SDValue, 1> BaseOps(1, Cond); 3352 ISD::NodeType OpCode = 3353 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3354 3355 bool IsUnaryAbs = false; 3356 bool Negate = false; 3357 3358 SDNodeFlags Flags; 3359 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3360 Flags.copyFMF(*FPOp); 3361 3362 // Min/max matching is only viable if all output VTs are the same. 3363 if (all_equal(ValueVTs)) { 3364 EVT VT = ValueVTs[0]; 3365 LLVMContext &Ctx = *DAG.getContext(); 3366 auto &TLI = DAG.getTargetLoweringInfo(); 3367 3368 // We care about the legality of the operation after it has been type 3369 // legalized. 3370 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3371 VT = TLI.getTypeToTransformTo(Ctx, VT); 3372 3373 // If the vselect is legal, assume we want to leave this as a vector setcc + 3374 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3375 // min/max is legal on the scalar type. 3376 bool UseScalarMinMax = VT.isVector() && 3377 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3378 3379 // ValueTracking's select pattern matching does not account for -0.0, 3380 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3381 // -0.0 is less than +0.0. 3382 Value *LHS, *RHS; 3383 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3384 ISD::NodeType Opc = ISD::DELETED_NODE; 3385 switch (SPR.Flavor) { 3386 case SPF_UMAX: Opc = ISD::UMAX; break; 3387 case SPF_UMIN: Opc = ISD::UMIN; break; 3388 case SPF_SMAX: Opc = ISD::SMAX; break; 3389 case SPF_SMIN: Opc = ISD::SMIN; break; 3390 case SPF_FMINNUM: 3391 switch (SPR.NaNBehavior) { 3392 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3393 case SPNB_RETURNS_NAN: break; 3394 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3395 case SPNB_RETURNS_ANY: 3396 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3397 (UseScalarMinMax && 3398 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3399 Opc = ISD::FMINNUM; 3400 break; 3401 } 3402 break; 3403 case SPF_FMAXNUM: 3404 switch (SPR.NaNBehavior) { 3405 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3406 case SPNB_RETURNS_NAN: break; 3407 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3408 case SPNB_RETURNS_ANY: 3409 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3410 (UseScalarMinMax && 3411 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3412 Opc = ISD::FMAXNUM; 3413 break; 3414 } 3415 break; 3416 case SPF_NABS: 3417 Negate = true; 3418 [[fallthrough]]; 3419 case SPF_ABS: 3420 IsUnaryAbs = true; 3421 Opc = ISD::ABS; 3422 break; 3423 default: break; 3424 } 3425 3426 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3427 (TLI.isOperationLegalOrCustom(Opc, VT) || 3428 (UseScalarMinMax && 3429 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3430 // If the underlying comparison instruction is used by any other 3431 // instruction, the consumed instructions won't be destroyed, so it is 3432 // not profitable to convert to a min/max. 3433 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3434 OpCode = Opc; 3435 LHSVal = getValue(LHS); 3436 RHSVal = getValue(RHS); 3437 BaseOps.clear(); 3438 } 3439 3440 if (IsUnaryAbs) { 3441 OpCode = Opc; 3442 LHSVal = getValue(LHS); 3443 BaseOps.clear(); 3444 } 3445 } 3446 3447 if (IsUnaryAbs) { 3448 for (unsigned i = 0; i != NumValues; ++i) { 3449 SDLoc dl = getCurSDLoc(); 3450 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3451 Values[i] = 3452 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3453 if (Negate) 3454 Values[i] = DAG.getNegative(Values[i], dl, VT); 3455 } 3456 } else { 3457 for (unsigned i = 0; i != NumValues; ++i) { 3458 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3459 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3460 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3461 Values[i] = DAG.getNode( 3462 OpCode, getCurSDLoc(), 3463 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3464 } 3465 } 3466 3467 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3468 DAG.getVTList(ValueVTs), Values)); 3469 } 3470 3471 void SelectionDAGBuilder::visitTrunc(const User &I) { 3472 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3473 SDValue N = getValue(I.getOperand(0)); 3474 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3475 I.getType()); 3476 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3477 } 3478 3479 void SelectionDAGBuilder::visitZExt(const User &I) { 3480 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3481 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3482 SDValue N = getValue(I.getOperand(0)); 3483 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3484 I.getType()); 3485 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3486 } 3487 3488 void SelectionDAGBuilder::visitSExt(const User &I) { 3489 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3490 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3491 SDValue N = getValue(I.getOperand(0)); 3492 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3493 I.getType()); 3494 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3495 } 3496 3497 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3498 // FPTrunc is never a no-op cast, no need to check 3499 SDValue N = getValue(I.getOperand(0)); 3500 SDLoc dl = getCurSDLoc(); 3501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3502 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3503 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3504 DAG.getTargetConstant( 3505 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3506 } 3507 3508 void SelectionDAGBuilder::visitFPExt(const User &I) { 3509 // FPExt is never a no-op cast, no need to check 3510 SDValue N = getValue(I.getOperand(0)); 3511 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3512 I.getType()); 3513 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3514 } 3515 3516 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3517 // FPToUI is never a no-op cast, no need to check 3518 SDValue N = getValue(I.getOperand(0)); 3519 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3520 I.getType()); 3521 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3522 } 3523 3524 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3525 // FPToSI is never a no-op cast, no need to check 3526 SDValue N = getValue(I.getOperand(0)); 3527 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3528 I.getType()); 3529 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3530 } 3531 3532 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3533 // UIToFP is never a no-op cast, no need to check 3534 SDValue N = getValue(I.getOperand(0)); 3535 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3536 I.getType()); 3537 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3538 } 3539 3540 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3541 // SIToFP is never a no-op cast, no need to check 3542 SDValue N = getValue(I.getOperand(0)); 3543 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3544 I.getType()); 3545 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3546 } 3547 3548 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3549 // What to do depends on the size of the integer and the size of the pointer. 3550 // We can either truncate, zero extend, or no-op, accordingly. 3551 SDValue N = getValue(I.getOperand(0)); 3552 auto &TLI = DAG.getTargetLoweringInfo(); 3553 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3554 I.getType()); 3555 EVT PtrMemVT = 3556 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3557 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3558 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3559 setValue(&I, N); 3560 } 3561 3562 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3563 // What to do depends on the size of the integer and the size of the pointer. 3564 // We can either truncate, zero extend, or no-op, accordingly. 3565 SDValue N = getValue(I.getOperand(0)); 3566 auto &TLI = DAG.getTargetLoweringInfo(); 3567 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3568 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3569 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3570 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3571 setValue(&I, N); 3572 } 3573 3574 void SelectionDAGBuilder::visitBitCast(const User &I) { 3575 SDValue N = getValue(I.getOperand(0)); 3576 SDLoc dl = getCurSDLoc(); 3577 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3578 I.getType()); 3579 3580 // BitCast assures us that source and destination are the same size so this is 3581 // either a BITCAST or a no-op. 3582 if (DestVT != N.getValueType()) 3583 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3584 DestVT, N)); // convert types. 3585 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3586 // might fold any kind of constant expression to an integer constant and that 3587 // is not what we are looking for. Only recognize a bitcast of a genuine 3588 // constant integer as an opaque constant. 3589 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3590 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3591 /*isOpaque*/true)); 3592 else 3593 setValue(&I, N); // noop cast. 3594 } 3595 3596 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3597 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3598 const Value *SV = I.getOperand(0); 3599 SDValue N = getValue(SV); 3600 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3601 3602 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3603 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3604 3605 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3606 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3607 3608 setValue(&I, N); 3609 } 3610 3611 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3612 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3613 SDValue InVec = getValue(I.getOperand(0)); 3614 SDValue InVal = getValue(I.getOperand(1)); 3615 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3616 TLI.getVectorIdxTy(DAG.getDataLayout())); 3617 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3618 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3619 InVec, InVal, InIdx)); 3620 } 3621 3622 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3623 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3624 SDValue InVec = getValue(I.getOperand(0)); 3625 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3626 TLI.getVectorIdxTy(DAG.getDataLayout())); 3627 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3628 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3629 InVec, InIdx)); 3630 } 3631 3632 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3633 SDValue Src1 = getValue(I.getOperand(0)); 3634 SDValue Src2 = getValue(I.getOperand(1)); 3635 ArrayRef<int> Mask; 3636 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3637 Mask = SVI->getShuffleMask(); 3638 else 3639 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3640 SDLoc DL = getCurSDLoc(); 3641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3642 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3643 EVT SrcVT = Src1.getValueType(); 3644 3645 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3646 VT.isScalableVector()) { 3647 // Canonical splat form of first element of first input vector. 3648 SDValue FirstElt = 3649 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3650 DAG.getVectorIdxConstant(0, DL)); 3651 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3652 return; 3653 } 3654 3655 // For now, we only handle splats for scalable vectors. 3656 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3657 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3658 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3659 3660 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3661 unsigned MaskNumElts = Mask.size(); 3662 3663 if (SrcNumElts == MaskNumElts) { 3664 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3665 return; 3666 } 3667 3668 // Normalize the shuffle vector since mask and vector length don't match. 3669 if (SrcNumElts < MaskNumElts) { 3670 // Mask is longer than the source vectors. We can use concatenate vector to 3671 // make the mask and vectors lengths match. 3672 3673 if (MaskNumElts % SrcNumElts == 0) { 3674 // Mask length is a multiple of the source vector length. 3675 // Check if the shuffle is some kind of concatenation of the input 3676 // vectors. 3677 unsigned NumConcat = MaskNumElts / SrcNumElts; 3678 bool IsConcat = true; 3679 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3680 for (unsigned i = 0; i != MaskNumElts; ++i) { 3681 int Idx = Mask[i]; 3682 if (Idx < 0) 3683 continue; 3684 // Ensure the indices in each SrcVT sized piece are sequential and that 3685 // the same source is used for the whole piece. 3686 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3687 (ConcatSrcs[i / SrcNumElts] >= 0 && 3688 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3689 IsConcat = false; 3690 break; 3691 } 3692 // Remember which source this index came from. 3693 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3694 } 3695 3696 // The shuffle is concatenating multiple vectors together. Just emit 3697 // a CONCAT_VECTORS operation. 3698 if (IsConcat) { 3699 SmallVector<SDValue, 8> ConcatOps; 3700 for (auto Src : ConcatSrcs) { 3701 if (Src < 0) 3702 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3703 else if (Src == 0) 3704 ConcatOps.push_back(Src1); 3705 else 3706 ConcatOps.push_back(Src2); 3707 } 3708 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3709 return; 3710 } 3711 } 3712 3713 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3714 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3715 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3716 PaddedMaskNumElts); 3717 3718 // Pad both vectors with undefs to make them the same length as the mask. 3719 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3720 3721 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3722 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3723 MOps1[0] = Src1; 3724 MOps2[0] = Src2; 3725 3726 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3727 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3728 3729 // Readjust mask for new input vector length. 3730 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3731 for (unsigned i = 0; i != MaskNumElts; ++i) { 3732 int Idx = Mask[i]; 3733 if (Idx >= (int)SrcNumElts) 3734 Idx -= SrcNumElts - PaddedMaskNumElts; 3735 MappedOps[i] = Idx; 3736 } 3737 3738 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3739 3740 // If the concatenated vector was padded, extract a subvector with the 3741 // correct number of elements. 3742 if (MaskNumElts != PaddedMaskNumElts) 3743 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3744 DAG.getVectorIdxConstant(0, DL)); 3745 3746 setValue(&I, Result); 3747 return; 3748 } 3749 3750 if (SrcNumElts > MaskNumElts) { 3751 // Analyze the access pattern of the vector to see if we can extract 3752 // two subvectors and do the shuffle. 3753 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3754 bool CanExtract = true; 3755 for (int Idx : Mask) { 3756 unsigned Input = 0; 3757 if (Idx < 0) 3758 continue; 3759 3760 if (Idx >= (int)SrcNumElts) { 3761 Input = 1; 3762 Idx -= SrcNumElts; 3763 } 3764 3765 // If all the indices come from the same MaskNumElts sized portion of 3766 // the sources we can use extract. Also make sure the extract wouldn't 3767 // extract past the end of the source. 3768 int NewStartIdx = alignDown(Idx, MaskNumElts); 3769 if (NewStartIdx + MaskNumElts > SrcNumElts || 3770 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3771 CanExtract = false; 3772 // Make sure we always update StartIdx as we use it to track if all 3773 // elements are undef. 3774 StartIdx[Input] = NewStartIdx; 3775 } 3776 3777 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3778 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3779 return; 3780 } 3781 if (CanExtract) { 3782 // Extract appropriate subvector and generate a vector shuffle 3783 for (unsigned Input = 0; Input < 2; ++Input) { 3784 SDValue &Src = Input == 0 ? Src1 : Src2; 3785 if (StartIdx[Input] < 0) 3786 Src = DAG.getUNDEF(VT); 3787 else { 3788 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3789 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3790 } 3791 } 3792 3793 // Calculate new mask. 3794 SmallVector<int, 8> MappedOps(Mask); 3795 for (int &Idx : MappedOps) { 3796 if (Idx >= (int)SrcNumElts) 3797 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3798 else if (Idx >= 0) 3799 Idx -= StartIdx[0]; 3800 } 3801 3802 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3803 return; 3804 } 3805 } 3806 3807 // We can't use either concat vectors or extract subvectors so fall back to 3808 // replacing the shuffle with extract and build vector. 3809 // to insert and build vector. 3810 EVT EltVT = VT.getVectorElementType(); 3811 SmallVector<SDValue,8> Ops; 3812 for (int Idx : Mask) { 3813 SDValue Res; 3814 3815 if (Idx < 0) { 3816 Res = DAG.getUNDEF(EltVT); 3817 } else { 3818 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3819 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3820 3821 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3822 DAG.getVectorIdxConstant(Idx, DL)); 3823 } 3824 3825 Ops.push_back(Res); 3826 } 3827 3828 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3829 } 3830 3831 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3832 ArrayRef<unsigned> Indices = I.getIndices(); 3833 const Value *Op0 = I.getOperand(0); 3834 const Value *Op1 = I.getOperand(1); 3835 Type *AggTy = I.getType(); 3836 Type *ValTy = Op1->getType(); 3837 bool IntoUndef = isa<UndefValue>(Op0); 3838 bool FromUndef = isa<UndefValue>(Op1); 3839 3840 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3841 3842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3843 SmallVector<EVT, 4> AggValueVTs; 3844 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3845 SmallVector<EVT, 4> ValValueVTs; 3846 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3847 3848 unsigned NumAggValues = AggValueVTs.size(); 3849 unsigned NumValValues = ValValueVTs.size(); 3850 SmallVector<SDValue, 4> Values(NumAggValues); 3851 3852 // Ignore an insertvalue that produces an empty object 3853 if (!NumAggValues) { 3854 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3855 return; 3856 } 3857 3858 SDValue Agg = getValue(Op0); 3859 unsigned i = 0; 3860 // Copy the beginning value(s) from the original aggregate. 3861 for (; i != LinearIndex; ++i) 3862 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3863 SDValue(Agg.getNode(), Agg.getResNo() + i); 3864 // Copy values from the inserted value(s). 3865 if (NumValValues) { 3866 SDValue Val = getValue(Op1); 3867 for (; i != LinearIndex + NumValValues; ++i) 3868 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3869 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3870 } 3871 // Copy remaining value(s) from the original aggregate. 3872 for (; i != NumAggValues; ++i) 3873 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3874 SDValue(Agg.getNode(), Agg.getResNo() + i); 3875 3876 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3877 DAG.getVTList(AggValueVTs), Values)); 3878 } 3879 3880 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3881 ArrayRef<unsigned> Indices = I.getIndices(); 3882 const Value *Op0 = I.getOperand(0); 3883 Type *AggTy = Op0->getType(); 3884 Type *ValTy = I.getType(); 3885 bool OutOfUndef = isa<UndefValue>(Op0); 3886 3887 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3888 3889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3890 SmallVector<EVT, 4> ValValueVTs; 3891 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3892 3893 unsigned NumValValues = ValValueVTs.size(); 3894 3895 // Ignore a extractvalue that produces an empty object 3896 if (!NumValValues) { 3897 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3898 return; 3899 } 3900 3901 SmallVector<SDValue, 4> Values(NumValValues); 3902 3903 SDValue Agg = getValue(Op0); 3904 // Copy out the selected value(s). 3905 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3906 Values[i - LinearIndex] = 3907 OutOfUndef ? 3908 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3909 SDValue(Agg.getNode(), Agg.getResNo() + i); 3910 3911 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3912 DAG.getVTList(ValValueVTs), Values)); 3913 } 3914 3915 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3916 Value *Op0 = I.getOperand(0); 3917 // Note that the pointer operand may be a vector of pointers. Take the scalar 3918 // element which holds a pointer. 3919 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3920 SDValue N = getValue(Op0); 3921 SDLoc dl = getCurSDLoc(); 3922 auto &TLI = DAG.getTargetLoweringInfo(); 3923 3924 // Normalize Vector GEP - all scalar operands should be converted to the 3925 // splat vector. 3926 bool IsVectorGEP = I.getType()->isVectorTy(); 3927 ElementCount VectorElementCount = 3928 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3929 : ElementCount::getFixed(0); 3930 3931 if (IsVectorGEP && !N.getValueType().isVector()) { 3932 LLVMContext &Context = *DAG.getContext(); 3933 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3934 N = DAG.getSplat(VT, dl, N); 3935 } 3936 3937 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3938 GTI != E; ++GTI) { 3939 const Value *Idx = GTI.getOperand(); 3940 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3941 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3942 if (Field) { 3943 // N = N + Offset 3944 uint64_t Offset = 3945 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3946 3947 // In an inbounds GEP with an offset that is nonnegative even when 3948 // interpreted as signed, assume there is no unsigned overflow. 3949 SDNodeFlags Flags; 3950 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3951 Flags.setNoUnsignedWrap(true); 3952 3953 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3954 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3955 } 3956 } else { 3957 // IdxSize is the width of the arithmetic according to IR semantics. 3958 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3959 // (and fix up the result later). 3960 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3961 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3962 TypeSize ElementSize = 3963 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3964 // We intentionally mask away the high bits here; ElementSize may not 3965 // fit in IdxTy. 3966 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3967 bool ElementScalable = ElementSize.isScalable(); 3968 3969 // If this is a scalar constant or a splat vector of constants, 3970 // handle it quickly. 3971 const auto *C = dyn_cast<Constant>(Idx); 3972 if (C && isa<VectorType>(C->getType())) 3973 C = C->getSplatValue(); 3974 3975 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3976 if (CI && CI->isZero()) 3977 continue; 3978 if (CI && !ElementScalable) { 3979 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3980 LLVMContext &Context = *DAG.getContext(); 3981 SDValue OffsVal; 3982 if (IsVectorGEP) 3983 OffsVal = DAG.getConstant( 3984 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3985 else 3986 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3987 3988 // In an inbounds GEP with an offset that is nonnegative even when 3989 // interpreted as signed, assume there is no unsigned overflow. 3990 SDNodeFlags Flags; 3991 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3992 Flags.setNoUnsignedWrap(true); 3993 3994 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3995 3996 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3997 continue; 3998 } 3999 4000 // N = N + Idx * ElementMul; 4001 SDValue IdxN = getValue(Idx); 4002 4003 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4004 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4005 VectorElementCount); 4006 IdxN = DAG.getSplat(VT, dl, IdxN); 4007 } 4008 4009 // If the index is smaller or larger than intptr_t, truncate or extend 4010 // it. 4011 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4012 4013 if (ElementScalable) { 4014 EVT VScaleTy = N.getValueType().getScalarType(); 4015 SDValue VScale = DAG.getNode( 4016 ISD::VSCALE, dl, VScaleTy, 4017 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4018 if (IsVectorGEP) 4019 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4020 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4021 } else { 4022 // If this is a multiply by a power of two, turn it into a shl 4023 // immediately. This is a very common case. 4024 if (ElementMul != 1) { 4025 if (ElementMul.isPowerOf2()) { 4026 unsigned Amt = ElementMul.logBase2(); 4027 IdxN = DAG.getNode(ISD::SHL, dl, 4028 N.getValueType(), IdxN, 4029 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4030 } else { 4031 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4032 IdxN.getValueType()); 4033 IdxN = DAG.getNode(ISD::MUL, dl, 4034 N.getValueType(), IdxN, Scale); 4035 } 4036 } 4037 } 4038 4039 N = DAG.getNode(ISD::ADD, dl, 4040 N.getValueType(), N, IdxN); 4041 } 4042 } 4043 4044 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4045 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4046 if (IsVectorGEP) { 4047 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4048 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4049 } 4050 4051 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4052 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4053 4054 setValue(&I, N); 4055 } 4056 4057 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4058 // If this is a fixed sized alloca in the entry block of the function, 4059 // allocate it statically on the stack. 4060 if (FuncInfo.StaticAllocaMap.count(&I)) 4061 return; // getValue will auto-populate this. 4062 4063 SDLoc dl = getCurSDLoc(); 4064 Type *Ty = I.getAllocatedType(); 4065 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4066 auto &DL = DAG.getDataLayout(); 4067 TypeSize TySize = DL.getTypeAllocSize(Ty); 4068 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4069 4070 SDValue AllocSize = getValue(I.getArraySize()); 4071 4072 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4073 if (AllocSize.getValueType() != IntPtr) 4074 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4075 4076 if (TySize.isScalable()) 4077 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4078 DAG.getVScale(dl, IntPtr, 4079 APInt(IntPtr.getScalarSizeInBits(), 4080 TySize.getKnownMinValue()))); 4081 else 4082 AllocSize = 4083 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4084 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4085 4086 // Handle alignment. If the requested alignment is less than or equal to 4087 // the stack alignment, ignore it. If the size is greater than or equal to 4088 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4089 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4090 if (*Alignment <= StackAlign) 4091 Alignment = std::nullopt; 4092 4093 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4094 // Round the size of the allocation up to the stack alignment size 4095 // by add SA-1 to the size. This doesn't overflow because we're computing 4096 // an address inside an alloca. 4097 SDNodeFlags Flags; 4098 Flags.setNoUnsignedWrap(true); 4099 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4100 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4101 4102 // Mask out the low bits for alignment purposes. 4103 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4104 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4105 4106 SDValue Ops[] = { 4107 getRoot(), AllocSize, 4108 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4109 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4110 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4111 setValue(&I, DSA); 4112 DAG.setRoot(DSA.getValue(1)); 4113 4114 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4115 } 4116 4117 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4118 if (I.isAtomic()) 4119 return visitAtomicLoad(I); 4120 4121 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4122 const Value *SV = I.getOperand(0); 4123 if (TLI.supportSwiftError()) { 4124 // Swifterror values can come from either a function parameter with 4125 // swifterror attribute or an alloca with swifterror attribute. 4126 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4127 if (Arg->hasSwiftErrorAttr()) 4128 return visitLoadFromSwiftError(I); 4129 } 4130 4131 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4132 if (Alloca->isSwiftError()) 4133 return visitLoadFromSwiftError(I); 4134 } 4135 } 4136 4137 SDValue Ptr = getValue(SV); 4138 4139 Type *Ty = I.getType(); 4140 SmallVector<EVT, 4> ValueVTs, MemVTs; 4141 SmallVector<uint64_t, 4> Offsets; 4142 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4143 unsigned NumValues = ValueVTs.size(); 4144 if (NumValues == 0) 4145 return; 4146 4147 Align Alignment = I.getAlign(); 4148 AAMDNodes AAInfo = I.getAAMetadata(); 4149 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4150 bool isVolatile = I.isVolatile(); 4151 MachineMemOperand::Flags MMOFlags = 4152 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4153 4154 SDValue Root; 4155 bool ConstantMemory = false; 4156 if (isVolatile) 4157 // Serialize volatile loads with other side effects. 4158 Root = getRoot(); 4159 else if (NumValues > MaxParallelChains) 4160 Root = getMemoryRoot(); 4161 else if (AA && 4162 AA->pointsToConstantMemory(MemoryLocation( 4163 SV, 4164 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4165 AAInfo))) { 4166 // Do not serialize (non-volatile) loads of constant memory with anything. 4167 Root = DAG.getEntryNode(); 4168 ConstantMemory = true; 4169 MMOFlags |= MachineMemOperand::MOInvariant; 4170 } else { 4171 // Do not serialize non-volatile loads against each other. 4172 Root = DAG.getRoot(); 4173 } 4174 4175 SDLoc dl = getCurSDLoc(); 4176 4177 if (isVolatile) 4178 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4179 4180 // An aggregate load cannot wrap around the address space, so offsets to its 4181 // parts don't wrap either. 4182 SDNodeFlags Flags; 4183 Flags.setNoUnsignedWrap(true); 4184 4185 SmallVector<SDValue, 4> Values(NumValues); 4186 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4187 EVT PtrVT = Ptr.getValueType(); 4188 4189 unsigned ChainI = 0; 4190 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4191 // Serializing loads here may result in excessive register pressure, and 4192 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4193 // could recover a bit by hoisting nodes upward in the chain by recognizing 4194 // they are side-effect free or do not alias. The optimizer should really 4195 // avoid this case by converting large object/array copies to llvm.memcpy 4196 // (MaxParallelChains should always remain as failsafe). 4197 if (ChainI == MaxParallelChains) { 4198 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4199 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4200 ArrayRef(Chains.data(), ChainI)); 4201 Root = Chain; 4202 ChainI = 0; 4203 } 4204 SDValue A = DAG.getNode(ISD::ADD, dl, 4205 PtrVT, Ptr, 4206 DAG.getConstant(Offsets[i], dl, PtrVT), 4207 Flags); 4208 4209 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4210 MachinePointerInfo(SV, Offsets[i]), Alignment, 4211 MMOFlags, AAInfo, Ranges); 4212 Chains[ChainI] = L.getValue(1); 4213 4214 if (MemVTs[i] != ValueVTs[i]) 4215 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4216 4217 Values[i] = L; 4218 } 4219 4220 if (!ConstantMemory) { 4221 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4222 ArrayRef(Chains.data(), ChainI)); 4223 if (isVolatile) 4224 DAG.setRoot(Chain); 4225 else 4226 PendingLoads.push_back(Chain); 4227 } 4228 4229 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4230 DAG.getVTList(ValueVTs), Values)); 4231 } 4232 4233 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4234 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4235 "call visitStoreToSwiftError when backend supports swifterror"); 4236 4237 SmallVector<EVT, 4> ValueVTs; 4238 SmallVector<uint64_t, 4> Offsets; 4239 const Value *SrcV = I.getOperand(0); 4240 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4241 SrcV->getType(), ValueVTs, &Offsets); 4242 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4243 "expect a single EVT for swifterror"); 4244 4245 SDValue Src = getValue(SrcV); 4246 // Create a virtual register, then update the virtual register. 4247 Register VReg = 4248 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4249 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4250 // Chain can be getRoot or getControlRoot. 4251 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4252 SDValue(Src.getNode(), Src.getResNo())); 4253 DAG.setRoot(CopyNode); 4254 } 4255 4256 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4257 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4258 "call visitLoadFromSwiftError when backend supports swifterror"); 4259 4260 assert(!I.isVolatile() && 4261 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4262 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4263 "Support volatile, non temporal, invariant for load_from_swift_error"); 4264 4265 const Value *SV = I.getOperand(0); 4266 Type *Ty = I.getType(); 4267 assert( 4268 (!AA || 4269 !AA->pointsToConstantMemory(MemoryLocation( 4270 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4271 I.getAAMetadata()))) && 4272 "load_from_swift_error should not be constant memory"); 4273 4274 SmallVector<EVT, 4> ValueVTs; 4275 SmallVector<uint64_t, 4> Offsets; 4276 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4277 ValueVTs, &Offsets); 4278 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4279 "expect a single EVT for swifterror"); 4280 4281 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4282 SDValue L = DAG.getCopyFromReg( 4283 getRoot(), getCurSDLoc(), 4284 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4285 4286 setValue(&I, L); 4287 } 4288 4289 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4290 if (I.isAtomic()) 4291 return visitAtomicStore(I); 4292 4293 const Value *SrcV = I.getOperand(0); 4294 const Value *PtrV = I.getOperand(1); 4295 4296 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4297 if (TLI.supportSwiftError()) { 4298 // Swifterror values can come from either a function parameter with 4299 // swifterror attribute or an alloca with swifterror attribute. 4300 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4301 if (Arg->hasSwiftErrorAttr()) 4302 return visitStoreToSwiftError(I); 4303 } 4304 4305 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4306 if (Alloca->isSwiftError()) 4307 return visitStoreToSwiftError(I); 4308 } 4309 } 4310 4311 SmallVector<EVT, 4> ValueVTs, MemVTs; 4312 SmallVector<uint64_t, 4> Offsets; 4313 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4314 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4315 unsigned NumValues = ValueVTs.size(); 4316 if (NumValues == 0) 4317 return; 4318 4319 // Get the lowered operands. Note that we do this after 4320 // checking if NumResults is zero, because with zero results 4321 // the operands won't have values in the map. 4322 SDValue Src = getValue(SrcV); 4323 SDValue Ptr = getValue(PtrV); 4324 4325 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4326 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4327 SDLoc dl = getCurSDLoc(); 4328 Align Alignment = I.getAlign(); 4329 AAMDNodes AAInfo = I.getAAMetadata(); 4330 4331 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4332 4333 // An aggregate load cannot wrap around the address space, so offsets to its 4334 // parts don't wrap either. 4335 SDNodeFlags Flags; 4336 Flags.setNoUnsignedWrap(true); 4337 4338 unsigned ChainI = 0; 4339 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4340 // See visitLoad comments. 4341 if (ChainI == MaxParallelChains) { 4342 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4343 ArrayRef(Chains.data(), ChainI)); 4344 Root = Chain; 4345 ChainI = 0; 4346 } 4347 SDValue Add = 4348 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4349 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4350 if (MemVTs[i] != ValueVTs[i]) 4351 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4352 SDValue St = 4353 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4354 Alignment, MMOFlags, AAInfo); 4355 Chains[ChainI] = St; 4356 } 4357 4358 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4359 ArrayRef(Chains.data(), ChainI)); 4360 setValue(&I, StoreNode); 4361 DAG.setRoot(StoreNode); 4362 } 4363 4364 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4365 bool IsCompressing) { 4366 SDLoc sdl = getCurSDLoc(); 4367 4368 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4369 MaybeAlign &Alignment) { 4370 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4371 Src0 = I.getArgOperand(0); 4372 Ptr = I.getArgOperand(1); 4373 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4374 Mask = I.getArgOperand(3); 4375 }; 4376 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4377 MaybeAlign &Alignment) { 4378 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4379 Src0 = I.getArgOperand(0); 4380 Ptr = I.getArgOperand(1); 4381 Mask = I.getArgOperand(2); 4382 Alignment = std::nullopt; 4383 }; 4384 4385 Value *PtrOperand, *MaskOperand, *Src0Operand; 4386 MaybeAlign Alignment; 4387 if (IsCompressing) 4388 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4389 else 4390 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4391 4392 SDValue Ptr = getValue(PtrOperand); 4393 SDValue Src0 = getValue(Src0Operand); 4394 SDValue Mask = getValue(MaskOperand); 4395 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4396 4397 EVT VT = Src0.getValueType(); 4398 if (!Alignment) 4399 Alignment = DAG.getEVTAlign(VT); 4400 4401 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4402 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4403 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4404 SDValue StoreNode = 4405 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4406 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4407 DAG.setRoot(StoreNode); 4408 setValue(&I, StoreNode); 4409 } 4410 4411 // Get a uniform base for the Gather/Scatter intrinsic. 4412 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4413 // We try to represent it as a base pointer + vector of indices. 4414 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4415 // The first operand of the GEP may be a single pointer or a vector of pointers 4416 // Example: 4417 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4418 // or 4419 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4420 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4421 // 4422 // When the first GEP operand is a single pointer - it is the uniform base we 4423 // are looking for. If first operand of the GEP is a splat vector - we 4424 // extract the splat value and use it as a uniform base. 4425 // In all other cases the function returns 'false'. 4426 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4427 ISD::MemIndexType &IndexType, SDValue &Scale, 4428 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4429 uint64_t ElemSize) { 4430 SelectionDAG& DAG = SDB->DAG; 4431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4432 const DataLayout &DL = DAG.getDataLayout(); 4433 4434 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4435 4436 // Handle splat constant pointer. 4437 if (auto *C = dyn_cast<Constant>(Ptr)) { 4438 C = C->getSplatValue(); 4439 if (!C) 4440 return false; 4441 4442 Base = SDB->getValue(C); 4443 4444 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4445 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4446 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4447 IndexType = ISD::SIGNED_SCALED; 4448 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4449 return true; 4450 } 4451 4452 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4453 if (!GEP || GEP->getParent() != CurBB) 4454 return false; 4455 4456 if (GEP->getNumOperands() != 2) 4457 return false; 4458 4459 const Value *BasePtr = GEP->getPointerOperand(); 4460 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4461 4462 // Make sure the base is scalar and the index is a vector. 4463 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4464 return false; 4465 4466 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4467 4468 // Target may not support the required addressing mode. 4469 if (ScaleVal != 1 && 4470 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4471 return false; 4472 4473 Base = SDB->getValue(BasePtr); 4474 Index = SDB->getValue(IndexVal); 4475 IndexType = ISD::SIGNED_SCALED; 4476 4477 Scale = 4478 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4479 return true; 4480 } 4481 4482 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4483 SDLoc sdl = getCurSDLoc(); 4484 4485 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4486 const Value *Ptr = I.getArgOperand(1); 4487 SDValue Src0 = getValue(I.getArgOperand(0)); 4488 SDValue Mask = getValue(I.getArgOperand(3)); 4489 EVT VT = Src0.getValueType(); 4490 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4491 ->getMaybeAlignValue() 4492 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4494 4495 SDValue Base; 4496 SDValue Index; 4497 ISD::MemIndexType IndexType; 4498 SDValue Scale; 4499 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4500 I.getParent(), VT.getScalarStoreSize()); 4501 4502 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4503 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4504 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4505 // TODO: Make MachineMemOperands aware of scalable 4506 // vectors. 4507 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4508 if (!UniformBase) { 4509 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4510 Index = getValue(Ptr); 4511 IndexType = ISD::SIGNED_SCALED; 4512 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4513 } 4514 4515 EVT IdxVT = Index.getValueType(); 4516 EVT EltTy = IdxVT.getVectorElementType(); 4517 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4518 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4519 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4520 } 4521 4522 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4523 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4524 Ops, MMO, IndexType, false); 4525 DAG.setRoot(Scatter); 4526 setValue(&I, Scatter); 4527 } 4528 4529 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4530 SDLoc sdl = getCurSDLoc(); 4531 4532 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4533 MaybeAlign &Alignment) { 4534 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4535 Ptr = I.getArgOperand(0); 4536 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4537 Mask = I.getArgOperand(2); 4538 Src0 = I.getArgOperand(3); 4539 }; 4540 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4541 MaybeAlign &Alignment) { 4542 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4543 Ptr = I.getArgOperand(0); 4544 Alignment = std::nullopt; 4545 Mask = I.getArgOperand(1); 4546 Src0 = I.getArgOperand(2); 4547 }; 4548 4549 Value *PtrOperand, *MaskOperand, *Src0Operand; 4550 MaybeAlign Alignment; 4551 if (IsExpanding) 4552 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4553 else 4554 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4555 4556 SDValue Ptr = getValue(PtrOperand); 4557 SDValue Src0 = getValue(Src0Operand); 4558 SDValue Mask = getValue(MaskOperand); 4559 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4560 4561 EVT VT = Src0.getValueType(); 4562 if (!Alignment) 4563 Alignment = DAG.getEVTAlign(VT); 4564 4565 AAMDNodes AAInfo = I.getAAMetadata(); 4566 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4567 4568 // Do not serialize masked loads of constant memory with anything. 4569 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4570 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4571 4572 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4573 4574 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4575 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4576 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4577 4578 SDValue Load = 4579 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4580 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4581 if (AddToChain) 4582 PendingLoads.push_back(Load.getValue(1)); 4583 setValue(&I, Load); 4584 } 4585 4586 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4587 SDLoc sdl = getCurSDLoc(); 4588 4589 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4590 const Value *Ptr = I.getArgOperand(0); 4591 SDValue Src0 = getValue(I.getArgOperand(3)); 4592 SDValue Mask = getValue(I.getArgOperand(2)); 4593 4594 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4595 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4596 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4597 ->getMaybeAlignValue() 4598 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4599 4600 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4601 4602 SDValue Root = DAG.getRoot(); 4603 SDValue Base; 4604 SDValue Index; 4605 ISD::MemIndexType IndexType; 4606 SDValue Scale; 4607 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4608 I.getParent(), VT.getScalarStoreSize()); 4609 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4610 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4611 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4612 // TODO: Make MachineMemOperands aware of scalable 4613 // vectors. 4614 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4615 4616 if (!UniformBase) { 4617 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4618 Index = getValue(Ptr); 4619 IndexType = ISD::SIGNED_SCALED; 4620 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4621 } 4622 4623 EVT IdxVT = Index.getValueType(); 4624 EVT EltTy = IdxVT.getVectorElementType(); 4625 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4626 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4627 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4628 } 4629 4630 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4631 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4632 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4633 4634 PendingLoads.push_back(Gather.getValue(1)); 4635 setValue(&I, Gather); 4636 } 4637 4638 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4639 SDLoc dl = getCurSDLoc(); 4640 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4641 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4642 SyncScope::ID SSID = I.getSyncScopeID(); 4643 4644 SDValue InChain = getRoot(); 4645 4646 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4647 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4648 4649 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4650 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4651 4652 MachineFunction &MF = DAG.getMachineFunction(); 4653 MachineMemOperand *MMO = MF.getMachineMemOperand( 4654 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4655 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4656 FailureOrdering); 4657 4658 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4659 dl, MemVT, VTs, InChain, 4660 getValue(I.getPointerOperand()), 4661 getValue(I.getCompareOperand()), 4662 getValue(I.getNewValOperand()), MMO); 4663 4664 SDValue OutChain = L.getValue(2); 4665 4666 setValue(&I, L); 4667 DAG.setRoot(OutChain); 4668 } 4669 4670 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4671 SDLoc dl = getCurSDLoc(); 4672 ISD::NodeType NT; 4673 switch (I.getOperation()) { 4674 default: llvm_unreachable("Unknown atomicrmw operation"); 4675 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4676 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4677 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4678 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4679 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4680 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4681 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4682 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4683 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4684 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4685 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4686 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4687 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4688 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4689 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4690 case AtomicRMWInst::UIncWrap: 4691 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4692 break; 4693 case AtomicRMWInst::UDecWrap: 4694 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4695 break; 4696 } 4697 AtomicOrdering Ordering = I.getOrdering(); 4698 SyncScope::ID SSID = I.getSyncScopeID(); 4699 4700 SDValue InChain = getRoot(); 4701 4702 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4704 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4705 4706 MachineFunction &MF = DAG.getMachineFunction(); 4707 MachineMemOperand *MMO = MF.getMachineMemOperand( 4708 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4709 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4710 4711 SDValue L = 4712 DAG.getAtomic(NT, dl, MemVT, InChain, 4713 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4714 MMO); 4715 4716 SDValue OutChain = L.getValue(1); 4717 4718 setValue(&I, L); 4719 DAG.setRoot(OutChain); 4720 } 4721 4722 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4723 SDLoc dl = getCurSDLoc(); 4724 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4725 SDValue Ops[3]; 4726 Ops[0] = getRoot(); 4727 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4728 TLI.getFenceOperandTy(DAG.getDataLayout())); 4729 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4730 TLI.getFenceOperandTy(DAG.getDataLayout())); 4731 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4732 setValue(&I, N); 4733 DAG.setRoot(N); 4734 } 4735 4736 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4737 SDLoc dl = getCurSDLoc(); 4738 AtomicOrdering Order = I.getOrdering(); 4739 SyncScope::ID SSID = I.getSyncScopeID(); 4740 4741 SDValue InChain = getRoot(); 4742 4743 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4744 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4745 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4746 4747 if (!TLI.supportsUnalignedAtomics() && 4748 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4749 report_fatal_error("Cannot generate unaligned atomic load"); 4750 4751 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4752 4753 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4754 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4755 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4756 4757 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4758 4759 SDValue Ptr = getValue(I.getPointerOperand()); 4760 4761 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4762 // TODO: Once this is better exercised by tests, it should be merged with 4763 // the normal path for loads to prevent future divergence. 4764 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4765 if (MemVT != VT) 4766 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4767 4768 setValue(&I, L); 4769 SDValue OutChain = L.getValue(1); 4770 if (!I.isUnordered()) 4771 DAG.setRoot(OutChain); 4772 else 4773 PendingLoads.push_back(OutChain); 4774 return; 4775 } 4776 4777 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4778 Ptr, MMO); 4779 4780 SDValue OutChain = L.getValue(1); 4781 if (MemVT != VT) 4782 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4783 4784 setValue(&I, L); 4785 DAG.setRoot(OutChain); 4786 } 4787 4788 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4789 SDLoc dl = getCurSDLoc(); 4790 4791 AtomicOrdering Ordering = I.getOrdering(); 4792 SyncScope::ID SSID = I.getSyncScopeID(); 4793 4794 SDValue InChain = getRoot(); 4795 4796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4797 EVT MemVT = 4798 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4799 4800 if (!TLI.supportsUnalignedAtomics() && 4801 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4802 report_fatal_error("Cannot generate unaligned atomic store"); 4803 4804 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4805 4806 MachineFunction &MF = DAG.getMachineFunction(); 4807 MachineMemOperand *MMO = MF.getMachineMemOperand( 4808 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4809 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4810 4811 SDValue Val = getValue(I.getValueOperand()); 4812 if (Val.getValueType() != MemVT) 4813 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4814 SDValue Ptr = getValue(I.getPointerOperand()); 4815 4816 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4817 // TODO: Once this is better exercised by tests, it should be merged with 4818 // the normal path for stores to prevent future divergence. 4819 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4820 setValue(&I, S); 4821 DAG.setRoot(S); 4822 return; 4823 } 4824 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4825 Ptr, Val, MMO); 4826 4827 setValue(&I, OutChain); 4828 DAG.setRoot(OutChain); 4829 } 4830 4831 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4832 /// node. 4833 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4834 unsigned Intrinsic) { 4835 // Ignore the callsite's attributes. A specific call site may be marked with 4836 // readnone, but the lowering code will expect the chain based on the 4837 // definition. 4838 const Function *F = I.getCalledFunction(); 4839 bool HasChain = !F->doesNotAccessMemory(); 4840 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4841 4842 // Build the operand list. 4843 SmallVector<SDValue, 8> Ops; 4844 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4845 if (OnlyLoad) { 4846 // We don't need to serialize loads against other loads. 4847 Ops.push_back(DAG.getRoot()); 4848 } else { 4849 Ops.push_back(getRoot()); 4850 } 4851 } 4852 4853 // Info is set by getTgtMemIntrinsic 4854 TargetLowering::IntrinsicInfo Info; 4855 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4856 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4857 DAG.getMachineFunction(), 4858 Intrinsic); 4859 4860 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4861 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4862 Info.opc == ISD::INTRINSIC_W_CHAIN) 4863 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4864 TLI.getPointerTy(DAG.getDataLayout()))); 4865 4866 // Add all operands of the call to the operand list. 4867 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4868 const Value *Arg = I.getArgOperand(i); 4869 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4870 Ops.push_back(getValue(Arg)); 4871 continue; 4872 } 4873 4874 // Use TargetConstant instead of a regular constant for immarg. 4875 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4876 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4877 assert(CI->getBitWidth() <= 64 && 4878 "large intrinsic immediates not handled"); 4879 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4880 } else { 4881 Ops.push_back( 4882 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4883 } 4884 } 4885 4886 SmallVector<EVT, 4> ValueVTs; 4887 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4888 4889 if (HasChain) 4890 ValueVTs.push_back(MVT::Other); 4891 4892 SDVTList VTs = DAG.getVTList(ValueVTs); 4893 4894 // Propagate fast-math-flags from IR to node(s). 4895 SDNodeFlags Flags; 4896 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4897 Flags.copyFMF(*FPMO); 4898 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4899 4900 // Create the node. 4901 SDValue Result; 4902 // In some cases, custom collection of operands from CallInst I may be needed. 4903 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4904 if (IsTgtIntrinsic) { 4905 // This is target intrinsic that touches memory 4906 // 4907 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4908 // didn't yield anything useful. 4909 MachinePointerInfo MPI; 4910 if (Info.ptrVal) 4911 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4912 else if (Info.fallbackAddressSpace) 4913 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4914 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4915 Info.memVT, MPI, Info.align, Info.flags, 4916 Info.size, I.getAAMetadata()); 4917 } else if (!HasChain) { 4918 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4919 } else if (!I.getType()->isVoidTy()) { 4920 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4921 } else { 4922 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4923 } 4924 4925 if (HasChain) { 4926 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4927 if (OnlyLoad) 4928 PendingLoads.push_back(Chain); 4929 else 4930 DAG.setRoot(Chain); 4931 } 4932 4933 if (!I.getType()->isVoidTy()) { 4934 if (!isa<VectorType>(I.getType())) 4935 Result = lowerRangeToAssertZExt(DAG, I, Result); 4936 4937 MaybeAlign Alignment = I.getRetAlign(); 4938 4939 // Insert `assertalign` node if there's an alignment. 4940 if (InsertAssertAlign && Alignment) { 4941 Result = 4942 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4943 } 4944 4945 setValue(&I, Result); 4946 } 4947 } 4948 4949 /// GetSignificand - Get the significand and build it into a floating-point 4950 /// number with exponent of 1: 4951 /// 4952 /// Op = (Op & 0x007fffff) | 0x3f800000; 4953 /// 4954 /// where Op is the hexadecimal representation of floating point value. 4955 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4956 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4957 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4958 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4959 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4960 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4961 } 4962 4963 /// GetExponent - Get the exponent: 4964 /// 4965 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4966 /// 4967 /// where Op is the hexadecimal representation of floating point value. 4968 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4969 const TargetLowering &TLI, const SDLoc &dl) { 4970 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4971 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4972 SDValue t1 = DAG.getNode( 4973 ISD::SRL, dl, MVT::i32, t0, 4974 DAG.getConstant(23, dl, 4975 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4976 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4977 DAG.getConstant(127, dl, MVT::i32)); 4978 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4979 } 4980 4981 /// getF32Constant - Get 32-bit floating point constant. 4982 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4983 const SDLoc &dl) { 4984 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4985 MVT::f32); 4986 } 4987 4988 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4989 SelectionDAG &DAG) { 4990 // TODO: What fast-math-flags should be set on the floating-point nodes? 4991 4992 // IntegerPartOfX = ((int32_t)(t0); 4993 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4994 4995 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4996 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4997 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4998 4999 // IntegerPartOfX <<= 23; 5000 IntegerPartOfX = 5001 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5002 DAG.getConstant(23, dl, 5003 DAG.getTargetLoweringInfo().getShiftAmountTy( 5004 MVT::i32, DAG.getDataLayout()))); 5005 5006 SDValue TwoToFractionalPartOfX; 5007 if (LimitFloatPrecision <= 6) { 5008 // For floating-point precision of 6: 5009 // 5010 // TwoToFractionalPartOfX = 5011 // 0.997535578f + 5012 // (0.735607626f + 0.252464424f * x) * x; 5013 // 5014 // error 0.0144103317, which is 6 bits 5015 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5016 getF32Constant(DAG, 0x3e814304, dl)); 5017 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5018 getF32Constant(DAG, 0x3f3c50c8, dl)); 5019 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5020 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5021 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5022 } else if (LimitFloatPrecision <= 12) { 5023 // For floating-point precision of 12: 5024 // 5025 // TwoToFractionalPartOfX = 5026 // 0.999892986f + 5027 // (0.696457318f + 5028 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5029 // 5030 // error 0.000107046256, which is 13 to 14 bits 5031 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5032 getF32Constant(DAG, 0x3da235e3, dl)); 5033 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5034 getF32Constant(DAG, 0x3e65b8f3, dl)); 5035 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5036 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5037 getF32Constant(DAG, 0x3f324b07, dl)); 5038 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5039 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5040 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5041 } else { // LimitFloatPrecision <= 18 5042 // For floating-point precision of 18: 5043 // 5044 // TwoToFractionalPartOfX = 5045 // 0.999999982f + 5046 // (0.693148872f + 5047 // (0.240227044f + 5048 // (0.554906021e-1f + 5049 // (0.961591928e-2f + 5050 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5051 // error 2.47208000*10^(-7), which is better than 18 bits 5052 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5053 getF32Constant(DAG, 0x3924b03e, dl)); 5054 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5055 getF32Constant(DAG, 0x3ab24b87, dl)); 5056 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5057 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5058 getF32Constant(DAG, 0x3c1d8c17, dl)); 5059 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5060 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5061 getF32Constant(DAG, 0x3d634a1d, dl)); 5062 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5063 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5064 getF32Constant(DAG, 0x3e75fe14, dl)); 5065 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5066 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5067 getF32Constant(DAG, 0x3f317234, dl)); 5068 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5069 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5070 getF32Constant(DAG, 0x3f800000, dl)); 5071 } 5072 5073 // Add the exponent into the result in integer domain. 5074 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5075 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5076 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5077 } 5078 5079 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5080 /// limited-precision mode. 5081 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5082 const TargetLowering &TLI, SDNodeFlags Flags) { 5083 if (Op.getValueType() == MVT::f32 && 5084 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5085 5086 // Put the exponent in the right bit position for later addition to the 5087 // final result: 5088 // 5089 // t0 = Op * log2(e) 5090 5091 // TODO: What fast-math-flags should be set here? 5092 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5093 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5094 return getLimitedPrecisionExp2(t0, dl, DAG); 5095 } 5096 5097 // No special expansion. 5098 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5099 } 5100 5101 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5102 /// limited-precision mode. 5103 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5104 const TargetLowering &TLI, SDNodeFlags Flags) { 5105 // TODO: What fast-math-flags should be set on the floating-point nodes? 5106 5107 if (Op.getValueType() == MVT::f32 && 5108 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5109 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5110 5111 // Scale the exponent by log(2). 5112 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5113 SDValue LogOfExponent = 5114 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5115 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5116 5117 // Get the significand and build it into a floating-point number with 5118 // exponent of 1. 5119 SDValue X = GetSignificand(DAG, Op1, dl); 5120 5121 SDValue LogOfMantissa; 5122 if (LimitFloatPrecision <= 6) { 5123 // For floating-point precision of 6: 5124 // 5125 // LogofMantissa = 5126 // -1.1609546f + 5127 // (1.4034025f - 0.23903021f * x) * x; 5128 // 5129 // error 0.0034276066, which is better than 8 bits 5130 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5131 getF32Constant(DAG, 0xbe74c456, dl)); 5132 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5133 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5135 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5136 getF32Constant(DAG, 0x3f949a29, dl)); 5137 } else if (LimitFloatPrecision <= 12) { 5138 // For floating-point precision of 12: 5139 // 5140 // LogOfMantissa = 5141 // -1.7417939f + 5142 // (2.8212026f + 5143 // (-1.4699568f + 5144 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5145 // 5146 // error 0.000061011436, which is 14 bits 5147 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5148 getF32Constant(DAG, 0xbd67b6d6, dl)); 5149 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5150 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5152 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5153 getF32Constant(DAG, 0x3fbc278b, dl)); 5154 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5155 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5156 getF32Constant(DAG, 0x40348e95, dl)); 5157 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5158 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5159 getF32Constant(DAG, 0x3fdef31a, dl)); 5160 } else { // LimitFloatPrecision <= 18 5161 // For floating-point precision of 18: 5162 // 5163 // LogOfMantissa = 5164 // -2.1072184f + 5165 // (4.2372794f + 5166 // (-3.7029485f + 5167 // (2.2781945f + 5168 // (-0.87823314f + 5169 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5170 // 5171 // error 0.0000023660568, which is better than 18 bits 5172 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5173 getF32Constant(DAG, 0xbc91e5ac, dl)); 5174 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5175 getF32Constant(DAG, 0x3e4350aa, dl)); 5176 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5177 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5178 getF32Constant(DAG, 0x3f60d3e3, dl)); 5179 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5180 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5181 getF32Constant(DAG, 0x4011cdf0, dl)); 5182 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5183 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5184 getF32Constant(DAG, 0x406cfd1c, dl)); 5185 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5186 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5187 getF32Constant(DAG, 0x408797cb, dl)); 5188 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5189 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5190 getF32Constant(DAG, 0x4006dcab, dl)); 5191 } 5192 5193 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5194 } 5195 5196 // No special expansion. 5197 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5198 } 5199 5200 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5201 /// limited-precision mode. 5202 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5203 const TargetLowering &TLI, SDNodeFlags Flags) { 5204 // TODO: What fast-math-flags should be set on the floating-point nodes? 5205 5206 if (Op.getValueType() == MVT::f32 && 5207 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5208 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5209 5210 // Get the exponent. 5211 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5212 5213 // Get the significand and build it into a floating-point number with 5214 // exponent of 1. 5215 SDValue X = GetSignificand(DAG, Op1, dl); 5216 5217 // Different possible minimax approximations of significand in 5218 // floating-point for various degrees of accuracy over [1,2]. 5219 SDValue Log2ofMantissa; 5220 if (LimitFloatPrecision <= 6) { 5221 // For floating-point precision of 6: 5222 // 5223 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5224 // 5225 // error 0.0049451742, which is more than 7 bits 5226 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5227 getF32Constant(DAG, 0xbeb08fe0, dl)); 5228 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5229 getF32Constant(DAG, 0x40019463, dl)); 5230 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5231 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5232 getF32Constant(DAG, 0x3fd6633d, dl)); 5233 } else if (LimitFloatPrecision <= 12) { 5234 // For floating-point precision of 12: 5235 // 5236 // Log2ofMantissa = 5237 // -2.51285454f + 5238 // (4.07009056f + 5239 // (-2.12067489f + 5240 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5241 // 5242 // error 0.0000876136000, which is better than 13 bits 5243 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5244 getF32Constant(DAG, 0xbda7262e, dl)); 5245 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5246 getF32Constant(DAG, 0x3f25280b, dl)); 5247 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5248 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5249 getF32Constant(DAG, 0x4007b923, dl)); 5250 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5251 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5252 getF32Constant(DAG, 0x40823e2f, dl)); 5253 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5254 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5255 getF32Constant(DAG, 0x4020d29c, dl)); 5256 } else { // LimitFloatPrecision <= 18 5257 // For floating-point precision of 18: 5258 // 5259 // Log2ofMantissa = 5260 // -3.0400495f + 5261 // (6.1129976f + 5262 // (-5.3420409f + 5263 // (3.2865683f + 5264 // (-1.2669343f + 5265 // (0.27515199f - 5266 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5267 // 5268 // error 0.0000018516, which is better than 18 bits 5269 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5270 getF32Constant(DAG, 0xbcd2769e, dl)); 5271 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5272 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5273 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5274 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5275 getF32Constant(DAG, 0x3fa22ae7, dl)); 5276 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5277 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5278 getF32Constant(DAG, 0x40525723, dl)); 5279 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5280 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5281 getF32Constant(DAG, 0x40aaf200, dl)); 5282 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5283 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5284 getF32Constant(DAG, 0x40c39dad, dl)); 5285 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5286 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5287 getF32Constant(DAG, 0x4042902c, dl)); 5288 } 5289 5290 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5291 } 5292 5293 // No special expansion. 5294 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5295 } 5296 5297 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5298 /// limited-precision mode. 5299 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5300 const TargetLowering &TLI, SDNodeFlags Flags) { 5301 // TODO: What fast-math-flags should be set on the floating-point nodes? 5302 5303 if (Op.getValueType() == MVT::f32 && 5304 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5305 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5306 5307 // Scale the exponent by log10(2) [0.30102999f]. 5308 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5309 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5310 getF32Constant(DAG, 0x3e9a209a, dl)); 5311 5312 // Get the significand and build it into a floating-point number with 5313 // exponent of 1. 5314 SDValue X = GetSignificand(DAG, Op1, dl); 5315 5316 SDValue Log10ofMantissa; 5317 if (LimitFloatPrecision <= 6) { 5318 // For floating-point precision of 6: 5319 // 5320 // Log10ofMantissa = 5321 // -0.50419619f + 5322 // (0.60948995f - 0.10380950f * x) * x; 5323 // 5324 // error 0.0014886165, which is 6 bits 5325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5326 getF32Constant(DAG, 0xbdd49a13, dl)); 5327 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5328 getF32Constant(DAG, 0x3f1c0789, dl)); 5329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5330 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5331 getF32Constant(DAG, 0x3f011300, dl)); 5332 } else if (LimitFloatPrecision <= 12) { 5333 // For floating-point precision of 12: 5334 // 5335 // Log10ofMantissa = 5336 // -0.64831180f + 5337 // (0.91751397f + 5338 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5339 // 5340 // error 0.00019228036, which is better than 12 bits 5341 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5342 getF32Constant(DAG, 0x3d431f31, dl)); 5343 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5344 getF32Constant(DAG, 0x3ea21fb2, dl)); 5345 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5346 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5347 getF32Constant(DAG, 0x3f6ae232, dl)); 5348 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5349 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5350 getF32Constant(DAG, 0x3f25f7c3, dl)); 5351 } else { // LimitFloatPrecision <= 18 5352 // For floating-point precision of 18: 5353 // 5354 // Log10ofMantissa = 5355 // -0.84299375f + 5356 // (1.5327582f + 5357 // (-1.0688956f + 5358 // (0.49102474f + 5359 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5360 // 5361 // error 0.0000037995730, which is better than 18 bits 5362 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5363 getF32Constant(DAG, 0x3c5d51ce, dl)); 5364 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5365 getF32Constant(DAG, 0x3e00685a, dl)); 5366 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5367 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5368 getF32Constant(DAG, 0x3efb6798, dl)); 5369 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5370 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5371 getF32Constant(DAG, 0x3f88d192, dl)); 5372 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5373 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5374 getF32Constant(DAG, 0x3fc4316c, dl)); 5375 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5376 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5377 getF32Constant(DAG, 0x3f57ce70, dl)); 5378 } 5379 5380 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5381 } 5382 5383 // No special expansion. 5384 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5385 } 5386 5387 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5388 /// limited-precision mode. 5389 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5390 const TargetLowering &TLI, SDNodeFlags Flags) { 5391 if (Op.getValueType() == MVT::f32 && 5392 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5393 return getLimitedPrecisionExp2(Op, dl, DAG); 5394 5395 // No special expansion. 5396 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5397 } 5398 5399 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5400 /// limited-precision mode with x == 10.0f. 5401 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5402 SelectionDAG &DAG, const TargetLowering &TLI, 5403 SDNodeFlags Flags) { 5404 bool IsExp10 = false; 5405 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5406 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5407 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5408 APFloat Ten(10.0f); 5409 IsExp10 = LHSC->isExactlyValue(Ten); 5410 } 5411 } 5412 5413 // TODO: What fast-math-flags should be set on the FMUL node? 5414 if (IsExp10) { 5415 // Put the exponent in the right bit position for later addition to the 5416 // final result: 5417 // 5418 // #define LOG2OF10 3.3219281f 5419 // t0 = Op * LOG2OF10; 5420 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5421 getF32Constant(DAG, 0x40549a78, dl)); 5422 return getLimitedPrecisionExp2(t0, dl, DAG); 5423 } 5424 5425 // No special expansion. 5426 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5427 } 5428 5429 /// ExpandPowI - Expand a llvm.powi intrinsic. 5430 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5431 SelectionDAG &DAG) { 5432 // If RHS is a constant, we can expand this out to a multiplication tree if 5433 // it's beneficial on the target, otherwise we end up lowering to a call to 5434 // __powidf2 (for example). 5435 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5436 unsigned Val = RHSC->getSExtValue(); 5437 5438 // powi(x, 0) -> 1.0 5439 if (Val == 0) 5440 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5441 5442 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5443 Val, DAG.shouldOptForSize())) { 5444 // Get the exponent as a positive value. 5445 if ((int)Val < 0) 5446 Val = -Val; 5447 // We use the simple binary decomposition method to generate the multiply 5448 // sequence. There are more optimal ways to do this (for example, 5449 // powi(x,15) generates one more multiply than it should), but this has 5450 // the benefit of being both really simple and much better than a libcall. 5451 SDValue Res; // Logically starts equal to 1.0 5452 SDValue CurSquare = LHS; 5453 // TODO: Intrinsics should have fast-math-flags that propagate to these 5454 // nodes. 5455 while (Val) { 5456 if (Val & 1) { 5457 if (Res.getNode()) 5458 Res = 5459 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5460 else 5461 Res = CurSquare; // 1.0*CurSquare. 5462 } 5463 5464 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5465 CurSquare, CurSquare); 5466 Val >>= 1; 5467 } 5468 5469 // If the original was negative, invert the result, producing 1/(x*x*x). 5470 if (RHSC->getSExtValue() < 0) 5471 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5472 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5473 return Res; 5474 } 5475 } 5476 5477 // Otherwise, expand to a libcall. 5478 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5479 } 5480 5481 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5482 SDValue LHS, SDValue RHS, SDValue Scale, 5483 SelectionDAG &DAG, const TargetLowering &TLI) { 5484 EVT VT = LHS.getValueType(); 5485 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5486 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5487 LLVMContext &Ctx = *DAG.getContext(); 5488 5489 // If the type is legal but the operation isn't, this node might survive all 5490 // the way to operation legalization. If we end up there and we do not have 5491 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5492 // node. 5493 5494 // Coax the legalizer into expanding the node during type legalization instead 5495 // by bumping the size by one bit. This will force it to Promote, enabling the 5496 // early expansion and avoiding the need to expand later. 5497 5498 // We don't have to do this if Scale is 0; that can always be expanded, unless 5499 // it's a saturating signed operation. Those can experience true integer 5500 // division overflow, a case which we must avoid. 5501 5502 // FIXME: We wouldn't have to do this (or any of the early 5503 // expansion/promotion) if it was possible to expand a libcall of an 5504 // illegal type during operation legalization. But it's not, so things 5505 // get a bit hacky. 5506 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5507 if ((ScaleInt > 0 || (Saturating && Signed)) && 5508 (TLI.isTypeLegal(VT) || 5509 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5510 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5511 Opcode, VT, ScaleInt); 5512 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5513 EVT PromVT; 5514 if (VT.isScalarInteger()) 5515 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5516 else if (VT.isVector()) { 5517 PromVT = VT.getVectorElementType(); 5518 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5519 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5520 } else 5521 llvm_unreachable("Wrong VT for DIVFIX?"); 5522 if (Signed) { 5523 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5524 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5525 } else { 5526 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5527 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5528 } 5529 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5530 // For saturating operations, we need to shift up the LHS to get the 5531 // proper saturation width, and then shift down again afterwards. 5532 if (Saturating) 5533 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5534 DAG.getConstant(1, DL, ShiftTy)); 5535 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5536 if (Saturating) 5537 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5538 DAG.getConstant(1, DL, ShiftTy)); 5539 return DAG.getZExtOrTrunc(Res, DL, VT); 5540 } 5541 } 5542 5543 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5544 } 5545 5546 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5547 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5548 static void 5549 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5550 const SDValue &N) { 5551 switch (N.getOpcode()) { 5552 case ISD::CopyFromReg: { 5553 SDValue Op = N.getOperand(1); 5554 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5555 Op.getValueType().getSizeInBits()); 5556 return; 5557 } 5558 case ISD::BITCAST: 5559 case ISD::AssertZext: 5560 case ISD::AssertSext: 5561 case ISD::TRUNCATE: 5562 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5563 return; 5564 case ISD::BUILD_PAIR: 5565 case ISD::BUILD_VECTOR: 5566 case ISD::CONCAT_VECTORS: 5567 for (SDValue Op : N->op_values()) 5568 getUnderlyingArgRegs(Regs, Op); 5569 return; 5570 default: 5571 return; 5572 } 5573 } 5574 5575 /// If the DbgValueInst is a dbg_value of a function argument, create the 5576 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5577 /// instruction selection, they will be inserted to the entry BB. 5578 /// We don't currently support this for variadic dbg_values, as they shouldn't 5579 /// appear for function arguments or in the prologue. 5580 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5581 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5582 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5583 const Argument *Arg = dyn_cast<Argument>(V); 5584 if (!Arg) 5585 return false; 5586 5587 MachineFunction &MF = DAG.getMachineFunction(); 5588 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5589 5590 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5591 // we've been asked to pursue. 5592 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5593 bool Indirect) { 5594 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5595 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5596 // pointing at the VReg, which will be patched up later. 5597 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5598 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5599 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5600 /* isKill */ false, /* isDead */ false, 5601 /* isUndef */ false, /* isEarlyClobber */ false, 5602 /* SubReg */ 0, /* isDebug */ true)}); 5603 5604 auto *NewDIExpr = FragExpr; 5605 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5606 // the DIExpression. 5607 if (Indirect) 5608 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5609 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5610 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5611 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5612 } else { 5613 // Create a completely standard DBG_VALUE. 5614 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5615 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5616 } 5617 }; 5618 5619 if (Kind == FuncArgumentDbgValueKind::Value) { 5620 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5621 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5622 // the entry block. 5623 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5624 if (!IsInEntryBlock) 5625 return false; 5626 5627 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5628 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5629 // variable that also is a param. 5630 // 5631 // Although, if we are at the top of the entry block already, we can still 5632 // emit using ArgDbgValue. This might catch some situations when the 5633 // dbg.value refers to an argument that isn't used in the entry block, so 5634 // any CopyToReg node would be optimized out and the only way to express 5635 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5636 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5637 // we should only emit as ArgDbgValue if the Variable is an argument to the 5638 // current function, and the dbg.value intrinsic is found in the entry 5639 // block. 5640 bool VariableIsFunctionInputArg = Variable->isParameter() && 5641 !DL->getInlinedAt(); 5642 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5643 if (!IsInPrologue && !VariableIsFunctionInputArg) 5644 return false; 5645 5646 // Here we assume that a function argument on IR level only can be used to 5647 // describe one input parameter on source level. If we for example have 5648 // source code like this 5649 // 5650 // struct A { long x, y; }; 5651 // void foo(struct A a, long b) { 5652 // ... 5653 // b = a.x; 5654 // ... 5655 // } 5656 // 5657 // and IR like this 5658 // 5659 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5660 // entry: 5661 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5662 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5663 // call void @llvm.dbg.value(metadata i32 %b, "b", 5664 // ... 5665 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5666 // ... 5667 // 5668 // then the last dbg.value is describing a parameter "b" using a value that 5669 // is an argument. But since we already has used %a1 to describe a parameter 5670 // we should not handle that last dbg.value here (that would result in an 5671 // incorrect hoisting of the DBG_VALUE to the function entry). 5672 // Notice that we allow one dbg.value per IR level argument, to accommodate 5673 // for the situation with fragments above. 5674 if (VariableIsFunctionInputArg) { 5675 unsigned ArgNo = Arg->getArgNo(); 5676 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5677 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5678 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5679 return false; 5680 FuncInfo.DescribedArgs.set(ArgNo); 5681 } 5682 } 5683 5684 bool IsIndirect = false; 5685 std::optional<MachineOperand> Op; 5686 // Some arguments' frame index is recorded during argument lowering. 5687 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5688 if (FI != std::numeric_limits<int>::max()) 5689 Op = MachineOperand::CreateFI(FI); 5690 5691 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5692 if (!Op && N.getNode()) { 5693 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5694 Register Reg; 5695 if (ArgRegsAndSizes.size() == 1) 5696 Reg = ArgRegsAndSizes.front().first; 5697 5698 if (Reg && Reg.isVirtual()) { 5699 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5700 Register PR = RegInfo.getLiveInPhysReg(Reg); 5701 if (PR) 5702 Reg = PR; 5703 } 5704 if (Reg) { 5705 Op = MachineOperand::CreateReg(Reg, false); 5706 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5707 } 5708 } 5709 5710 if (!Op && N.getNode()) { 5711 // Check if frame index is available. 5712 SDValue LCandidate = peekThroughBitcasts(N); 5713 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5714 if (FrameIndexSDNode *FINode = 5715 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5716 Op = MachineOperand::CreateFI(FINode->getIndex()); 5717 } 5718 5719 if (!Op) { 5720 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5721 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5722 SplitRegs) { 5723 unsigned Offset = 0; 5724 for (const auto &RegAndSize : SplitRegs) { 5725 // If the expression is already a fragment, the current register 5726 // offset+size might extend beyond the fragment. In this case, only 5727 // the register bits that are inside the fragment are relevant. 5728 int RegFragmentSizeInBits = RegAndSize.second; 5729 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5730 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5731 // The register is entirely outside the expression fragment, 5732 // so is irrelevant for debug info. 5733 if (Offset >= ExprFragmentSizeInBits) 5734 break; 5735 // The register is partially outside the expression fragment, only 5736 // the low bits within the fragment are relevant for debug info. 5737 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5738 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5739 } 5740 } 5741 5742 auto FragmentExpr = DIExpression::createFragmentExpression( 5743 Expr, Offset, RegFragmentSizeInBits); 5744 Offset += RegAndSize.second; 5745 // If a valid fragment expression cannot be created, the variable's 5746 // correct value cannot be determined and so it is set as Undef. 5747 if (!FragmentExpr) { 5748 SDDbgValue *SDV = DAG.getConstantDbgValue( 5749 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5750 DAG.AddDbgValue(SDV, false); 5751 continue; 5752 } 5753 MachineInstr *NewMI = 5754 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5755 Kind != FuncArgumentDbgValueKind::Value); 5756 FuncInfo.ArgDbgValues.push_back(NewMI); 5757 } 5758 }; 5759 5760 // Check if ValueMap has reg number. 5761 DenseMap<const Value *, Register>::const_iterator 5762 VMI = FuncInfo.ValueMap.find(V); 5763 if (VMI != FuncInfo.ValueMap.end()) { 5764 const auto &TLI = DAG.getTargetLoweringInfo(); 5765 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5766 V->getType(), std::nullopt); 5767 if (RFV.occupiesMultipleRegs()) { 5768 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5769 return true; 5770 } 5771 5772 Op = MachineOperand::CreateReg(VMI->second, false); 5773 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5774 } else if (ArgRegsAndSizes.size() > 1) { 5775 // This was split due to the calling convention, and no virtual register 5776 // mapping exists for the value. 5777 splitMultiRegDbgValue(ArgRegsAndSizes); 5778 return true; 5779 } 5780 } 5781 5782 if (!Op) 5783 return false; 5784 5785 assert(Variable->isValidLocationForIntrinsic(DL) && 5786 "Expected inlined-at fields to agree"); 5787 MachineInstr *NewMI = nullptr; 5788 5789 if (Op->isReg()) 5790 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5791 else 5792 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5793 Variable, Expr); 5794 5795 // Otherwise, use ArgDbgValues. 5796 FuncInfo.ArgDbgValues.push_back(NewMI); 5797 return true; 5798 } 5799 5800 /// Return the appropriate SDDbgValue based on N. 5801 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5802 DILocalVariable *Variable, 5803 DIExpression *Expr, 5804 const DebugLoc &dl, 5805 unsigned DbgSDNodeOrder) { 5806 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5807 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5808 // stack slot locations. 5809 // 5810 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5811 // debug values here after optimization: 5812 // 5813 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5814 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5815 // 5816 // Both describe the direct values of their associated variables. 5817 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5818 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5819 } 5820 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5821 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5822 } 5823 5824 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5825 switch (Intrinsic) { 5826 case Intrinsic::smul_fix: 5827 return ISD::SMULFIX; 5828 case Intrinsic::umul_fix: 5829 return ISD::UMULFIX; 5830 case Intrinsic::smul_fix_sat: 5831 return ISD::SMULFIXSAT; 5832 case Intrinsic::umul_fix_sat: 5833 return ISD::UMULFIXSAT; 5834 case Intrinsic::sdiv_fix: 5835 return ISD::SDIVFIX; 5836 case Intrinsic::udiv_fix: 5837 return ISD::UDIVFIX; 5838 case Intrinsic::sdiv_fix_sat: 5839 return ISD::SDIVFIXSAT; 5840 case Intrinsic::udiv_fix_sat: 5841 return ISD::UDIVFIXSAT; 5842 default: 5843 llvm_unreachable("Unhandled fixed point intrinsic"); 5844 } 5845 } 5846 5847 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5848 const char *FunctionName) { 5849 assert(FunctionName && "FunctionName must not be nullptr"); 5850 SDValue Callee = DAG.getExternalSymbol( 5851 FunctionName, 5852 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5853 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5854 } 5855 5856 /// Given a @llvm.call.preallocated.setup, return the corresponding 5857 /// preallocated call. 5858 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5859 assert(cast<CallBase>(PreallocatedSetup) 5860 ->getCalledFunction() 5861 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5862 "expected call_preallocated_setup Value"); 5863 for (const auto *U : PreallocatedSetup->users()) { 5864 auto *UseCall = cast<CallBase>(U); 5865 const Function *Fn = UseCall->getCalledFunction(); 5866 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5867 return UseCall; 5868 } 5869 } 5870 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5871 } 5872 5873 /// Lower the call to the specified intrinsic function. 5874 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5875 unsigned Intrinsic) { 5876 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5877 SDLoc sdl = getCurSDLoc(); 5878 DebugLoc dl = getCurDebugLoc(); 5879 SDValue Res; 5880 5881 SDNodeFlags Flags; 5882 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5883 Flags.copyFMF(*FPOp); 5884 5885 switch (Intrinsic) { 5886 default: 5887 // By default, turn this into a target intrinsic node. 5888 visitTargetIntrinsic(I, Intrinsic); 5889 return; 5890 case Intrinsic::vscale: { 5891 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5892 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5893 return; 5894 } 5895 case Intrinsic::vastart: visitVAStart(I); return; 5896 case Intrinsic::vaend: visitVAEnd(I); return; 5897 case Intrinsic::vacopy: visitVACopy(I); return; 5898 case Intrinsic::returnaddress: 5899 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5900 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5901 getValue(I.getArgOperand(0)))); 5902 return; 5903 case Intrinsic::addressofreturnaddress: 5904 setValue(&I, 5905 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5906 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5907 return; 5908 case Intrinsic::sponentry: 5909 setValue(&I, 5910 DAG.getNode(ISD::SPONENTRY, sdl, 5911 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5912 return; 5913 case Intrinsic::frameaddress: 5914 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5915 TLI.getFrameIndexTy(DAG.getDataLayout()), 5916 getValue(I.getArgOperand(0)))); 5917 return; 5918 case Intrinsic::read_volatile_register: 5919 case Intrinsic::read_register: { 5920 Value *Reg = I.getArgOperand(0); 5921 SDValue Chain = getRoot(); 5922 SDValue RegName = 5923 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5924 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5925 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5926 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5927 setValue(&I, Res); 5928 DAG.setRoot(Res.getValue(1)); 5929 return; 5930 } 5931 case Intrinsic::write_register: { 5932 Value *Reg = I.getArgOperand(0); 5933 Value *RegValue = I.getArgOperand(1); 5934 SDValue Chain = getRoot(); 5935 SDValue RegName = 5936 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5937 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5938 RegName, getValue(RegValue))); 5939 return; 5940 } 5941 case Intrinsic::memcpy: { 5942 const auto &MCI = cast<MemCpyInst>(I); 5943 SDValue Op1 = getValue(I.getArgOperand(0)); 5944 SDValue Op2 = getValue(I.getArgOperand(1)); 5945 SDValue Op3 = getValue(I.getArgOperand(2)); 5946 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5947 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5948 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5949 Align Alignment = std::min(DstAlign, SrcAlign); 5950 bool isVol = MCI.isVolatile(); 5951 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5952 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5953 // node. 5954 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5955 SDValue MC = DAG.getMemcpy( 5956 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5957 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5958 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5959 updateDAGForMaybeTailCall(MC); 5960 return; 5961 } 5962 case Intrinsic::memcpy_inline: { 5963 const auto &MCI = cast<MemCpyInlineInst>(I); 5964 SDValue Dst = getValue(I.getArgOperand(0)); 5965 SDValue Src = getValue(I.getArgOperand(1)); 5966 SDValue Size = getValue(I.getArgOperand(2)); 5967 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5968 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5969 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5970 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5971 Align Alignment = std::min(DstAlign, SrcAlign); 5972 bool isVol = MCI.isVolatile(); 5973 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5974 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5975 // node. 5976 SDValue MC = DAG.getMemcpy( 5977 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5978 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5979 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5980 updateDAGForMaybeTailCall(MC); 5981 return; 5982 } 5983 case Intrinsic::memset: { 5984 const auto &MSI = cast<MemSetInst>(I); 5985 SDValue Op1 = getValue(I.getArgOperand(0)); 5986 SDValue Op2 = getValue(I.getArgOperand(1)); 5987 SDValue Op3 = getValue(I.getArgOperand(2)); 5988 // @llvm.memset defines 0 and 1 to both mean no alignment. 5989 Align Alignment = MSI.getDestAlign().valueOrOne(); 5990 bool isVol = MSI.isVolatile(); 5991 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5992 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5993 SDValue MS = DAG.getMemset( 5994 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5995 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5996 updateDAGForMaybeTailCall(MS); 5997 return; 5998 } 5999 case Intrinsic::memset_inline: { 6000 const auto &MSII = cast<MemSetInlineInst>(I); 6001 SDValue Dst = getValue(I.getArgOperand(0)); 6002 SDValue Value = getValue(I.getArgOperand(1)); 6003 SDValue Size = getValue(I.getArgOperand(2)); 6004 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6005 // @llvm.memset defines 0 and 1 to both mean no alignment. 6006 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6007 bool isVol = MSII.isVolatile(); 6008 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6009 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6010 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6011 /* AlwaysInline */ true, isTC, 6012 MachinePointerInfo(I.getArgOperand(0)), 6013 I.getAAMetadata()); 6014 updateDAGForMaybeTailCall(MC); 6015 return; 6016 } 6017 case Intrinsic::memmove: { 6018 const auto &MMI = cast<MemMoveInst>(I); 6019 SDValue Op1 = getValue(I.getArgOperand(0)); 6020 SDValue Op2 = getValue(I.getArgOperand(1)); 6021 SDValue Op3 = getValue(I.getArgOperand(2)); 6022 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6023 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6024 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6025 Align Alignment = std::min(DstAlign, SrcAlign); 6026 bool isVol = MMI.isVolatile(); 6027 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6028 // FIXME: Support passing different dest/src alignments to the memmove DAG 6029 // node. 6030 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6031 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6032 isTC, MachinePointerInfo(I.getArgOperand(0)), 6033 MachinePointerInfo(I.getArgOperand(1)), 6034 I.getAAMetadata(), AA); 6035 updateDAGForMaybeTailCall(MM); 6036 return; 6037 } 6038 case Intrinsic::memcpy_element_unordered_atomic: { 6039 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6040 SDValue Dst = getValue(MI.getRawDest()); 6041 SDValue Src = getValue(MI.getRawSource()); 6042 SDValue Length = getValue(MI.getLength()); 6043 6044 Type *LengthTy = MI.getLength()->getType(); 6045 unsigned ElemSz = MI.getElementSizeInBytes(); 6046 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6047 SDValue MC = 6048 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6049 isTC, MachinePointerInfo(MI.getRawDest()), 6050 MachinePointerInfo(MI.getRawSource())); 6051 updateDAGForMaybeTailCall(MC); 6052 return; 6053 } 6054 case Intrinsic::memmove_element_unordered_atomic: { 6055 auto &MI = cast<AtomicMemMoveInst>(I); 6056 SDValue Dst = getValue(MI.getRawDest()); 6057 SDValue Src = getValue(MI.getRawSource()); 6058 SDValue Length = getValue(MI.getLength()); 6059 6060 Type *LengthTy = MI.getLength()->getType(); 6061 unsigned ElemSz = MI.getElementSizeInBytes(); 6062 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6063 SDValue MC = 6064 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6065 isTC, MachinePointerInfo(MI.getRawDest()), 6066 MachinePointerInfo(MI.getRawSource())); 6067 updateDAGForMaybeTailCall(MC); 6068 return; 6069 } 6070 case Intrinsic::memset_element_unordered_atomic: { 6071 auto &MI = cast<AtomicMemSetInst>(I); 6072 SDValue Dst = getValue(MI.getRawDest()); 6073 SDValue Val = getValue(MI.getValue()); 6074 SDValue Length = getValue(MI.getLength()); 6075 6076 Type *LengthTy = MI.getLength()->getType(); 6077 unsigned ElemSz = MI.getElementSizeInBytes(); 6078 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6079 SDValue MC = 6080 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6081 isTC, MachinePointerInfo(MI.getRawDest())); 6082 updateDAGForMaybeTailCall(MC); 6083 return; 6084 } 6085 case Intrinsic::call_preallocated_setup: { 6086 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6087 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6088 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6089 getRoot(), SrcValue); 6090 setValue(&I, Res); 6091 DAG.setRoot(Res); 6092 return; 6093 } 6094 case Intrinsic::call_preallocated_arg: { 6095 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6096 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6097 SDValue Ops[3]; 6098 Ops[0] = getRoot(); 6099 Ops[1] = SrcValue; 6100 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6101 MVT::i32); // arg index 6102 SDValue Res = DAG.getNode( 6103 ISD::PREALLOCATED_ARG, sdl, 6104 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6105 setValue(&I, Res); 6106 DAG.setRoot(Res.getValue(1)); 6107 return; 6108 } 6109 case Intrinsic::dbg_declare: { 6110 // Debug intrinsics are handled separately in assignment tracking mode. 6111 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent())) 6112 return; 6113 // Assume dbg.declare can not currently use DIArgList, i.e. 6114 // it is non-variadic. 6115 const auto &DI = cast<DbgVariableIntrinsic>(I); 6116 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6117 DILocalVariable *Variable = DI.getVariable(); 6118 DIExpression *Expression = DI.getExpression(); 6119 dropDanglingDebugInfo(Variable, Expression); 6120 assert(Variable && "Missing variable"); 6121 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6122 << "\n"); 6123 // Check if address has undef value. 6124 const Value *Address = DI.getVariableLocationOp(0); 6125 if (!Address || isa<UndefValue>(Address) || 6126 (Address->use_empty() && !isa<Argument>(Address))) { 6127 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6128 << " (bad/undef/unused-arg address)\n"); 6129 return; 6130 } 6131 6132 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6133 6134 // Check if this variable can be described by a frame index, typically 6135 // either as a static alloca or a byval parameter. 6136 int FI = std::numeric_limits<int>::max(); 6137 if (const auto *AI = 6138 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6139 if (AI->isStaticAlloca()) { 6140 auto I = FuncInfo.StaticAllocaMap.find(AI); 6141 if (I != FuncInfo.StaticAllocaMap.end()) 6142 FI = I->second; 6143 } 6144 } else if (const auto *Arg = dyn_cast<Argument>( 6145 Address->stripInBoundsConstantOffsets())) { 6146 FI = FuncInfo.getArgumentFrameIndex(Arg); 6147 } 6148 6149 // llvm.dbg.declare is handled as a frame index in the MachineFunction 6150 // variable table. 6151 if (FI != std::numeric_limits<int>::max()) { 6152 LLVM_DEBUG(dbgs() << "Skipping " << DI 6153 << " (variable info stashed in MF side table)\n"); 6154 return; 6155 } 6156 6157 SDValue &N = NodeMap[Address]; 6158 if (!N.getNode() && isa<Argument>(Address)) 6159 // Check unused arguments map. 6160 N = UnusedArgNodeMap[Address]; 6161 SDDbgValue *SDV; 6162 if (N.getNode()) { 6163 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6164 Address = BCI->getOperand(0); 6165 // Parameters are handled specially. 6166 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6167 if (isParameter && FINode) { 6168 // Byval parameter. We have a frame index at this point. 6169 SDV = 6170 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6171 /*IsIndirect*/ true, dl, SDNodeOrder); 6172 } else if (isa<Argument>(Address)) { 6173 // Address is an argument, so try to emit its dbg value using 6174 // virtual register info from the FuncInfo.ValueMap. 6175 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6176 FuncArgumentDbgValueKind::Declare, N); 6177 return; 6178 } else { 6179 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6180 true, dl, SDNodeOrder); 6181 } 6182 DAG.AddDbgValue(SDV, isParameter); 6183 } else { 6184 // If Address is an argument then try to emit its dbg value using 6185 // virtual register info from the FuncInfo.ValueMap. 6186 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6187 FuncArgumentDbgValueKind::Declare, N)) { 6188 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6189 << " (could not emit func-arg dbg_value)\n"); 6190 } 6191 } 6192 return; 6193 } 6194 case Intrinsic::dbg_label: { 6195 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6196 DILabel *Label = DI.getLabel(); 6197 assert(Label && "Missing label"); 6198 6199 SDDbgLabel *SDV; 6200 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6201 DAG.AddDbgLabel(SDV); 6202 return; 6203 } 6204 case Intrinsic::dbg_assign: { 6205 // Debug intrinsics are handled seperately in assignment tracking mode. 6206 assert(isAssignmentTrackingEnabled(*I.getFunction()->getParent()) && 6207 "expected assignment tracking to be enabled"); 6208 return; 6209 } 6210 case Intrinsic::dbg_value: { 6211 // Debug intrinsics are handled seperately in assignment tracking mode. 6212 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent())) 6213 return; 6214 const DbgValueInst &DI = cast<DbgValueInst>(I); 6215 assert(DI.getVariable() && "Missing variable"); 6216 6217 DILocalVariable *Variable = DI.getVariable(); 6218 DIExpression *Expression = DI.getExpression(); 6219 dropDanglingDebugInfo(Variable, Expression); 6220 SmallVector<Value *, 4> Values(DI.getValues()); 6221 if (Values.empty()) 6222 return; 6223 6224 if (llvm::is_contained(Values, nullptr)) 6225 return; 6226 6227 bool IsVariadic = DI.hasArgList(); 6228 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6229 SDNodeOrder, IsVariadic)) 6230 addDanglingDebugInfo(&DI, SDNodeOrder); 6231 return; 6232 } 6233 6234 case Intrinsic::eh_typeid_for: { 6235 // Find the type id for the given typeinfo. 6236 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6237 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6238 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6239 setValue(&I, Res); 6240 return; 6241 } 6242 6243 case Intrinsic::eh_return_i32: 6244 case Intrinsic::eh_return_i64: 6245 DAG.getMachineFunction().setCallsEHReturn(true); 6246 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6247 MVT::Other, 6248 getControlRoot(), 6249 getValue(I.getArgOperand(0)), 6250 getValue(I.getArgOperand(1)))); 6251 return; 6252 case Intrinsic::eh_unwind_init: 6253 DAG.getMachineFunction().setCallsUnwindInit(true); 6254 return; 6255 case Intrinsic::eh_dwarf_cfa: 6256 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6257 TLI.getPointerTy(DAG.getDataLayout()), 6258 getValue(I.getArgOperand(0)))); 6259 return; 6260 case Intrinsic::eh_sjlj_callsite: { 6261 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6262 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6263 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6264 6265 MMI.setCurrentCallSite(CI->getZExtValue()); 6266 return; 6267 } 6268 case Intrinsic::eh_sjlj_functioncontext: { 6269 // Get and store the index of the function context. 6270 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6271 AllocaInst *FnCtx = 6272 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6273 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6274 MFI.setFunctionContextIndex(FI); 6275 return; 6276 } 6277 case Intrinsic::eh_sjlj_setjmp: { 6278 SDValue Ops[2]; 6279 Ops[0] = getRoot(); 6280 Ops[1] = getValue(I.getArgOperand(0)); 6281 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6282 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6283 setValue(&I, Op.getValue(0)); 6284 DAG.setRoot(Op.getValue(1)); 6285 return; 6286 } 6287 case Intrinsic::eh_sjlj_longjmp: 6288 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6289 getRoot(), getValue(I.getArgOperand(0)))); 6290 return; 6291 case Intrinsic::eh_sjlj_setup_dispatch: 6292 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6293 getRoot())); 6294 return; 6295 case Intrinsic::masked_gather: 6296 visitMaskedGather(I); 6297 return; 6298 case Intrinsic::masked_load: 6299 visitMaskedLoad(I); 6300 return; 6301 case Intrinsic::masked_scatter: 6302 visitMaskedScatter(I); 6303 return; 6304 case Intrinsic::masked_store: 6305 visitMaskedStore(I); 6306 return; 6307 case Intrinsic::masked_expandload: 6308 visitMaskedLoad(I, true /* IsExpanding */); 6309 return; 6310 case Intrinsic::masked_compressstore: 6311 visitMaskedStore(I, true /* IsCompressing */); 6312 return; 6313 case Intrinsic::powi: 6314 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6315 getValue(I.getArgOperand(1)), DAG)); 6316 return; 6317 case Intrinsic::log: 6318 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6319 return; 6320 case Intrinsic::log2: 6321 setValue(&I, 6322 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6323 return; 6324 case Intrinsic::log10: 6325 setValue(&I, 6326 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6327 return; 6328 case Intrinsic::exp: 6329 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6330 return; 6331 case Intrinsic::exp2: 6332 setValue(&I, 6333 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6334 return; 6335 case Intrinsic::pow: 6336 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6337 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6338 return; 6339 case Intrinsic::sqrt: 6340 case Intrinsic::fabs: 6341 case Intrinsic::sin: 6342 case Intrinsic::cos: 6343 case Intrinsic::floor: 6344 case Intrinsic::ceil: 6345 case Intrinsic::trunc: 6346 case Intrinsic::rint: 6347 case Intrinsic::nearbyint: 6348 case Intrinsic::round: 6349 case Intrinsic::roundeven: 6350 case Intrinsic::canonicalize: { 6351 unsigned Opcode; 6352 switch (Intrinsic) { 6353 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6354 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6355 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6356 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6357 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6358 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6359 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6360 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6361 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6362 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6363 case Intrinsic::round: Opcode = ISD::FROUND; break; 6364 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6365 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6366 } 6367 6368 setValue(&I, DAG.getNode(Opcode, sdl, 6369 getValue(I.getArgOperand(0)).getValueType(), 6370 getValue(I.getArgOperand(0)), Flags)); 6371 return; 6372 } 6373 case Intrinsic::lround: 6374 case Intrinsic::llround: 6375 case Intrinsic::lrint: 6376 case Intrinsic::llrint: { 6377 unsigned Opcode; 6378 switch (Intrinsic) { 6379 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6380 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6381 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6382 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6383 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6384 } 6385 6386 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6387 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6388 getValue(I.getArgOperand(0)))); 6389 return; 6390 } 6391 case Intrinsic::minnum: 6392 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6393 getValue(I.getArgOperand(0)).getValueType(), 6394 getValue(I.getArgOperand(0)), 6395 getValue(I.getArgOperand(1)), Flags)); 6396 return; 6397 case Intrinsic::maxnum: 6398 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6399 getValue(I.getArgOperand(0)).getValueType(), 6400 getValue(I.getArgOperand(0)), 6401 getValue(I.getArgOperand(1)), Flags)); 6402 return; 6403 case Intrinsic::minimum: 6404 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6405 getValue(I.getArgOperand(0)).getValueType(), 6406 getValue(I.getArgOperand(0)), 6407 getValue(I.getArgOperand(1)), Flags)); 6408 return; 6409 case Intrinsic::maximum: 6410 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6411 getValue(I.getArgOperand(0)).getValueType(), 6412 getValue(I.getArgOperand(0)), 6413 getValue(I.getArgOperand(1)), Flags)); 6414 return; 6415 case Intrinsic::copysign: 6416 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6417 getValue(I.getArgOperand(0)).getValueType(), 6418 getValue(I.getArgOperand(0)), 6419 getValue(I.getArgOperand(1)), Flags)); 6420 return; 6421 case Intrinsic::arithmetic_fence: { 6422 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6423 getValue(I.getArgOperand(0)).getValueType(), 6424 getValue(I.getArgOperand(0)), Flags)); 6425 return; 6426 } 6427 case Intrinsic::fma: 6428 setValue(&I, DAG.getNode( 6429 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6430 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6431 getValue(I.getArgOperand(2)), Flags)); 6432 return; 6433 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6434 case Intrinsic::INTRINSIC: 6435 #include "llvm/IR/ConstrainedOps.def" 6436 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6437 return; 6438 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6439 #include "llvm/IR/VPIntrinsics.def" 6440 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6441 return; 6442 case Intrinsic::fptrunc_round: { 6443 // Get the last argument, the metadata and convert it to an integer in the 6444 // call 6445 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6446 std::optional<RoundingMode> RoundMode = 6447 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6448 6449 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6450 6451 // Propagate fast-math-flags from IR to node(s). 6452 SDNodeFlags Flags; 6453 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6454 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6455 6456 SDValue Result; 6457 Result = DAG.getNode( 6458 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6459 DAG.getTargetConstant((int)*RoundMode, sdl, 6460 TLI.getPointerTy(DAG.getDataLayout()))); 6461 setValue(&I, Result); 6462 6463 return; 6464 } 6465 case Intrinsic::fmuladd: { 6466 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6467 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6468 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6469 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6470 getValue(I.getArgOperand(0)).getValueType(), 6471 getValue(I.getArgOperand(0)), 6472 getValue(I.getArgOperand(1)), 6473 getValue(I.getArgOperand(2)), Flags)); 6474 } else { 6475 // TODO: Intrinsic calls should have fast-math-flags. 6476 SDValue Mul = DAG.getNode( 6477 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6478 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6479 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6480 getValue(I.getArgOperand(0)).getValueType(), 6481 Mul, getValue(I.getArgOperand(2)), Flags); 6482 setValue(&I, Add); 6483 } 6484 return; 6485 } 6486 case Intrinsic::convert_to_fp16: 6487 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6488 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6489 getValue(I.getArgOperand(0)), 6490 DAG.getTargetConstant(0, sdl, 6491 MVT::i32)))); 6492 return; 6493 case Intrinsic::convert_from_fp16: 6494 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6495 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6496 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6497 getValue(I.getArgOperand(0))))); 6498 return; 6499 case Intrinsic::fptosi_sat: { 6500 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6501 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6502 getValue(I.getArgOperand(0)), 6503 DAG.getValueType(VT.getScalarType()))); 6504 return; 6505 } 6506 case Intrinsic::fptoui_sat: { 6507 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6508 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6509 getValue(I.getArgOperand(0)), 6510 DAG.getValueType(VT.getScalarType()))); 6511 return; 6512 } 6513 case Intrinsic::set_rounding: 6514 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6515 {getRoot(), getValue(I.getArgOperand(0))}); 6516 setValue(&I, Res); 6517 DAG.setRoot(Res.getValue(0)); 6518 return; 6519 case Intrinsic::is_fpclass: { 6520 const DataLayout DLayout = DAG.getDataLayout(); 6521 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6522 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6523 FPClassTest Test = static_cast<FPClassTest>( 6524 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6525 MachineFunction &MF = DAG.getMachineFunction(); 6526 const Function &F = MF.getFunction(); 6527 SDValue Op = getValue(I.getArgOperand(0)); 6528 SDNodeFlags Flags; 6529 Flags.setNoFPExcept( 6530 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6531 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6532 // expansion can use illegal types. Making expansion early allows 6533 // legalizing these types prior to selection. 6534 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6535 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6536 setValue(&I, Result); 6537 return; 6538 } 6539 6540 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6541 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6542 setValue(&I, V); 6543 return; 6544 } 6545 case Intrinsic::pcmarker: { 6546 SDValue Tmp = getValue(I.getArgOperand(0)); 6547 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6548 return; 6549 } 6550 case Intrinsic::readcyclecounter: { 6551 SDValue Op = getRoot(); 6552 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6553 DAG.getVTList(MVT::i64, MVT::Other), Op); 6554 setValue(&I, Res); 6555 DAG.setRoot(Res.getValue(1)); 6556 return; 6557 } 6558 case Intrinsic::bitreverse: 6559 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6560 getValue(I.getArgOperand(0)).getValueType(), 6561 getValue(I.getArgOperand(0)))); 6562 return; 6563 case Intrinsic::bswap: 6564 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6565 getValue(I.getArgOperand(0)).getValueType(), 6566 getValue(I.getArgOperand(0)))); 6567 return; 6568 case Intrinsic::cttz: { 6569 SDValue Arg = getValue(I.getArgOperand(0)); 6570 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6571 EVT Ty = Arg.getValueType(); 6572 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6573 sdl, Ty, Arg)); 6574 return; 6575 } 6576 case Intrinsic::ctlz: { 6577 SDValue Arg = getValue(I.getArgOperand(0)); 6578 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6579 EVT Ty = Arg.getValueType(); 6580 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6581 sdl, Ty, Arg)); 6582 return; 6583 } 6584 case Intrinsic::ctpop: { 6585 SDValue Arg = getValue(I.getArgOperand(0)); 6586 EVT Ty = Arg.getValueType(); 6587 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6588 return; 6589 } 6590 case Intrinsic::fshl: 6591 case Intrinsic::fshr: { 6592 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6593 SDValue X = getValue(I.getArgOperand(0)); 6594 SDValue Y = getValue(I.getArgOperand(1)); 6595 SDValue Z = getValue(I.getArgOperand(2)); 6596 EVT VT = X.getValueType(); 6597 6598 if (X == Y) { 6599 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6600 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6601 } else { 6602 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6603 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6604 } 6605 return; 6606 } 6607 case Intrinsic::sadd_sat: { 6608 SDValue Op1 = getValue(I.getArgOperand(0)); 6609 SDValue Op2 = getValue(I.getArgOperand(1)); 6610 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6611 return; 6612 } 6613 case Intrinsic::uadd_sat: { 6614 SDValue Op1 = getValue(I.getArgOperand(0)); 6615 SDValue Op2 = getValue(I.getArgOperand(1)); 6616 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6617 return; 6618 } 6619 case Intrinsic::ssub_sat: { 6620 SDValue Op1 = getValue(I.getArgOperand(0)); 6621 SDValue Op2 = getValue(I.getArgOperand(1)); 6622 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6623 return; 6624 } 6625 case Intrinsic::usub_sat: { 6626 SDValue Op1 = getValue(I.getArgOperand(0)); 6627 SDValue Op2 = getValue(I.getArgOperand(1)); 6628 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6629 return; 6630 } 6631 case Intrinsic::sshl_sat: { 6632 SDValue Op1 = getValue(I.getArgOperand(0)); 6633 SDValue Op2 = getValue(I.getArgOperand(1)); 6634 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6635 return; 6636 } 6637 case Intrinsic::ushl_sat: { 6638 SDValue Op1 = getValue(I.getArgOperand(0)); 6639 SDValue Op2 = getValue(I.getArgOperand(1)); 6640 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6641 return; 6642 } 6643 case Intrinsic::smul_fix: 6644 case Intrinsic::umul_fix: 6645 case Intrinsic::smul_fix_sat: 6646 case Intrinsic::umul_fix_sat: { 6647 SDValue Op1 = getValue(I.getArgOperand(0)); 6648 SDValue Op2 = getValue(I.getArgOperand(1)); 6649 SDValue Op3 = getValue(I.getArgOperand(2)); 6650 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6651 Op1.getValueType(), Op1, Op2, Op3)); 6652 return; 6653 } 6654 case Intrinsic::sdiv_fix: 6655 case Intrinsic::udiv_fix: 6656 case Intrinsic::sdiv_fix_sat: 6657 case Intrinsic::udiv_fix_sat: { 6658 SDValue Op1 = getValue(I.getArgOperand(0)); 6659 SDValue Op2 = getValue(I.getArgOperand(1)); 6660 SDValue Op3 = getValue(I.getArgOperand(2)); 6661 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6662 Op1, Op2, Op3, DAG, TLI)); 6663 return; 6664 } 6665 case Intrinsic::smax: { 6666 SDValue Op1 = getValue(I.getArgOperand(0)); 6667 SDValue Op2 = getValue(I.getArgOperand(1)); 6668 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6669 return; 6670 } 6671 case Intrinsic::smin: { 6672 SDValue Op1 = getValue(I.getArgOperand(0)); 6673 SDValue Op2 = getValue(I.getArgOperand(1)); 6674 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6675 return; 6676 } 6677 case Intrinsic::umax: { 6678 SDValue Op1 = getValue(I.getArgOperand(0)); 6679 SDValue Op2 = getValue(I.getArgOperand(1)); 6680 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6681 return; 6682 } 6683 case Intrinsic::umin: { 6684 SDValue Op1 = getValue(I.getArgOperand(0)); 6685 SDValue Op2 = getValue(I.getArgOperand(1)); 6686 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6687 return; 6688 } 6689 case Intrinsic::abs: { 6690 // TODO: Preserve "int min is poison" arg in SDAG? 6691 SDValue Op1 = getValue(I.getArgOperand(0)); 6692 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6693 return; 6694 } 6695 case Intrinsic::stacksave: { 6696 SDValue Op = getRoot(); 6697 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6698 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6699 setValue(&I, Res); 6700 DAG.setRoot(Res.getValue(1)); 6701 return; 6702 } 6703 case Intrinsic::stackrestore: 6704 Res = getValue(I.getArgOperand(0)); 6705 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6706 return; 6707 case Intrinsic::get_dynamic_area_offset: { 6708 SDValue Op = getRoot(); 6709 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6710 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6711 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6712 // target. 6713 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6714 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6715 " intrinsic!"); 6716 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6717 Op); 6718 DAG.setRoot(Op); 6719 setValue(&I, Res); 6720 return; 6721 } 6722 case Intrinsic::stackguard: { 6723 MachineFunction &MF = DAG.getMachineFunction(); 6724 const Module &M = *MF.getFunction().getParent(); 6725 SDValue Chain = getRoot(); 6726 if (TLI.useLoadStackGuardNode()) { 6727 Res = getLoadStackGuard(DAG, sdl, Chain); 6728 } else { 6729 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6730 const Value *Global = TLI.getSDagStackGuard(M); 6731 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6732 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6733 MachinePointerInfo(Global, 0), Align, 6734 MachineMemOperand::MOVolatile); 6735 } 6736 if (TLI.useStackGuardXorFP()) 6737 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6738 DAG.setRoot(Chain); 6739 setValue(&I, Res); 6740 return; 6741 } 6742 case Intrinsic::stackprotector: { 6743 // Emit code into the DAG to store the stack guard onto the stack. 6744 MachineFunction &MF = DAG.getMachineFunction(); 6745 MachineFrameInfo &MFI = MF.getFrameInfo(); 6746 SDValue Src, Chain = getRoot(); 6747 6748 if (TLI.useLoadStackGuardNode()) 6749 Src = getLoadStackGuard(DAG, sdl, Chain); 6750 else 6751 Src = getValue(I.getArgOperand(0)); // The guard's value. 6752 6753 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6754 6755 int FI = FuncInfo.StaticAllocaMap[Slot]; 6756 MFI.setStackProtectorIndex(FI); 6757 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6758 6759 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6760 6761 // Store the stack protector onto the stack. 6762 Res = DAG.getStore( 6763 Chain, sdl, Src, FIN, 6764 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6765 MaybeAlign(), MachineMemOperand::MOVolatile); 6766 setValue(&I, Res); 6767 DAG.setRoot(Res); 6768 return; 6769 } 6770 case Intrinsic::objectsize: 6771 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6772 6773 case Intrinsic::is_constant: 6774 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6775 6776 case Intrinsic::annotation: 6777 case Intrinsic::ptr_annotation: 6778 case Intrinsic::launder_invariant_group: 6779 case Intrinsic::strip_invariant_group: 6780 // Drop the intrinsic, but forward the value 6781 setValue(&I, getValue(I.getOperand(0))); 6782 return; 6783 6784 case Intrinsic::assume: 6785 case Intrinsic::experimental_noalias_scope_decl: 6786 case Intrinsic::var_annotation: 6787 case Intrinsic::sideeffect: 6788 // Discard annotate attributes, noalias scope declarations, assumptions, and 6789 // artificial side-effects. 6790 return; 6791 6792 case Intrinsic::codeview_annotation: { 6793 // Emit a label associated with this metadata. 6794 MachineFunction &MF = DAG.getMachineFunction(); 6795 MCSymbol *Label = 6796 MF.getMMI().getContext().createTempSymbol("annotation", true); 6797 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6798 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6799 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6800 DAG.setRoot(Res); 6801 return; 6802 } 6803 6804 case Intrinsic::init_trampoline: { 6805 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6806 6807 SDValue Ops[6]; 6808 Ops[0] = getRoot(); 6809 Ops[1] = getValue(I.getArgOperand(0)); 6810 Ops[2] = getValue(I.getArgOperand(1)); 6811 Ops[3] = getValue(I.getArgOperand(2)); 6812 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6813 Ops[5] = DAG.getSrcValue(F); 6814 6815 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6816 6817 DAG.setRoot(Res); 6818 return; 6819 } 6820 case Intrinsic::adjust_trampoline: 6821 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6822 TLI.getPointerTy(DAG.getDataLayout()), 6823 getValue(I.getArgOperand(0)))); 6824 return; 6825 case Intrinsic::gcroot: { 6826 assert(DAG.getMachineFunction().getFunction().hasGC() && 6827 "only valid in functions with gc specified, enforced by Verifier"); 6828 assert(GFI && "implied by previous"); 6829 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6830 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6831 6832 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6833 GFI->addStackRoot(FI->getIndex(), TypeMap); 6834 return; 6835 } 6836 case Intrinsic::gcread: 6837 case Intrinsic::gcwrite: 6838 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6839 case Intrinsic::get_rounding: 6840 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6841 setValue(&I, Res); 6842 DAG.setRoot(Res.getValue(1)); 6843 return; 6844 6845 case Intrinsic::expect: 6846 // Just replace __builtin_expect(exp, c) with EXP. 6847 setValue(&I, getValue(I.getArgOperand(0))); 6848 return; 6849 6850 case Intrinsic::ubsantrap: 6851 case Intrinsic::debugtrap: 6852 case Intrinsic::trap: { 6853 StringRef TrapFuncName = 6854 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6855 if (TrapFuncName.empty()) { 6856 switch (Intrinsic) { 6857 case Intrinsic::trap: 6858 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6859 break; 6860 case Intrinsic::debugtrap: 6861 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6862 break; 6863 case Intrinsic::ubsantrap: 6864 DAG.setRoot(DAG.getNode( 6865 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6866 DAG.getTargetConstant( 6867 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6868 MVT::i32))); 6869 break; 6870 default: llvm_unreachable("unknown trap intrinsic"); 6871 } 6872 return; 6873 } 6874 TargetLowering::ArgListTy Args; 6875 if (Intrinsic == Intrinsic::ubsantrap) { 6876 Args.push_back(TargetLoweringBase::ArgListEntry()); 6877 Args[0].Val = I.getArgOperand(0); 6878 Args[0].Node = getValue(Args[0].Val); 6879 Args[0].Ty = Args[0].Val->getType(); 6880 } 6881 6882 TargetLowering::CallLoweringInfo CLI(DAG); 6883 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6884 CallingConv::C, I.getType(), 6885 DAG.getExternalSymbol(TrapFuncName.data(), 6886 TLI.getPointerTy(DAG.getDataLayout())), 6887 std::move(Args)); 6888 6889 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6890 DAG.setRoot(Result.second); 6891 return; 6892 } 6893 6894 case Intrinsic::uadd_with_overflow: 6895 case Intrinsic::sadd_with_overflow: 6896 case Intrinsic::usub_with_overflow: 6897 case Intrinsic::ssub_with_overflow: 6898 case Intrinsic::umul_with_overflow: 6899 case Intrinsic::smul_with_overflow: { 6900 ISD::NodeType Op; 6901 switch (Intrinsic) { 6902 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6903 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6904 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6905 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6906 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6907 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6908 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6909 } 6910 SDValue Op1 = getValue(I.getArgOperand(0)); 6911 SDValue Op2 = getValue(I.getArgOperand(1)); 6912 6913 EVT ResultVT = Op1.getValueType(); 6914 EVT OverflowVT = MVT::i1; 6915 if (ResultVT.isVector()) 6916 OverflowVT = EVT::getVectorVT( 6917 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6918 6919 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6920 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6921 return; 6922 } 6923 case Intrinsic::prefetch: { 6924 SDValue Ops[5]; 6925 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6926 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6927 Ops[0] = DAG.getRoot(); 6928 Ops[1] = getValue(I.getArgOperand(0)); 6929 Ops[2] = getValue(I.getArgOperand(1)); 6930 Ops[3] = getValue(I.getArgOperand(2)); 6931 Ops[4] = getValue(I.getArgOperand(3)); 6932 SDValue Result = DAG.getMemIntrinsicNode( 6933 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6934 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6935 /* align */ std::nullopt, Flags); 6936 6937 // Chain the prefetch in parallell with any pending loads, to stay out of 6938 // the way of later optimizations. 6939 PendingLoads.push_back(Result); 6940 Result = getRoot(); 6941 DAG.setRoot(Result); 6942 return; 6943 } 6944 case Intrinsic::lifetime_start: 6945 case Intrinsic::lifetime_end: { 6946 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6947 // Stack coloring is not enabled in O0, discard region information. 6948 if (TM.getOptLevel() == CodeGenOpt::None) 6949 return; 6950 6951 const int64_t ObjectSize = 6952 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6953 Value *const ObjectPtr = I.getArgOperand(1); 6954 SmallVector<const Value *, 4> Allocas; 6955 getUnderlyingObjects(ObjectPtr, Allocas); 6956 6957 for (const Value *Alloca : Allocas) { 6958 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6959 6960 // Could not find an Alloca. 6961 if (!LifetimeObject) 6962 continue; 6963 6964 // First check that the Alloca is static, otherwise it won't have a 6965 // valid frame index. 6966 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6967 if (SI == FuncInfo.StaticAllocaMap.end()) 6968 return; 6969 6970 const int FrameIndex = SI->second; 6971 int64_t Offset; 6972 if (GetPointerBaseWithConstantOffset( 6973 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6974 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6975 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6976 Offset); 6977 DAG.setRoot(Res); 6978 } 6979 return; 6980 } 6981 case Intrinsic::pseudoprobe: { 6982 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6983 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6984 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6985 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6986 DAG.setRoot(Res); 6987 return; 6988 } 6989 case Intrinsic::invariant_start: 6990 // Discard region information. 6991 setValue(&I, 6992 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6993 return; 6994 case Intrinsic::invariant_end: 6995 // Discard region information. 6996 return; 6997 case Intrinsic::clear_cache: 6998 /// FunctionName may be null. 6999 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7000 lowerCallToExternalSymbol(I, FunctionName); 7001 return; 7002 case Intrinsic::donothing: 7003 case Intrinsic::seh_try_begin: 7004 case Intrinsic::seh_scope_begin: 7005 case Intrinsic::seh_try_end: 7006 case Intrinsic::seh_scope_end: 7007 // ignore 7008 return; 7009 case Intrinsic::experimental_stackmap: 7010 visitStackmap(I); 7011 return; 7012 case Intrinsic::experimental_patchpoint_void: 7013 case Intrinsic::experimental_patchpoint_i64: 7014 visitPatchpoint(I); 7015 return; 7016 case Intrinsic::experimental_gc_statepoint: 7017 LowerStatepoint(cast<GCStatepointInst>(I)); 7018 return; 7019 case Intrinsic::experimental_gc_result: 7020 visitGCResult(cast<GCResultInst>(I)); 7021 return; 7022 case Intrinsic::experimental_gc_relocate: 7023 visitGCRelocate(cast<GCRelocateInst>(I)); 7024 return; 7025 case Intrinsic::instrprof_cover: 7026 llvm_unreachable("instrprof failed to lower a cover"); 7027 case Intrinsic::instrprof_increment: 7028 llvm_unreachable("instrprof failed to lower an increment"); 7029 case Intrinsic::instrprof_value_profile: 7030 llvm_unreachable("instrprof failed to lower a value profiling call"); 7031 case Intrinsic::localescape: { 7032 MachineFunction &MF = DAG.getMachineFunction(); 7033 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7034 7035 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7036 // is the same on all targets. 7037 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7038 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7039 if (isa<ConstantPointerNull>(Arg)) 7040 continue; // Skip null pointers. They represent a hole in index space. 7041 AllocaInst *Slot = cast<AllocaInst>(Arg); 7042 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7043 "can only escape static allocas"); 7044 int FI = FuncInfo.StaticAllocaMap[Slot]; 7045 MCSymbol *FrameAllocSym = 7046 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7047 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7049 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7050 .addSym(FrameAllocSym) 7051 .addFrameIndex(FI); 7052 } 7053 7054 return; 7055 } 7056 7057 case Intrinsic::localrecover: { 7058 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7059 MachineFunction &MF = DAG.getMachineFunction(); 7060 7061 // Get the symbol that defines the frame offset. 7062 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7063 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7064 unsigned IdxVal = 7065 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7066 MCSymbol *FrameAllocSym = 7067 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7068 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7069 7070 Value *FP = I.getArgOperand(1); 7071 SDValue FPVal = getValue(FP); 7072 EVT PtrVT = FPVal.getValueType(); 7073 7074 // Create a MCSymbol for the label to avoid any target lowering 7075 // that would make this PC relative. 7076 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7077 SDValue OffsetVal = 7078 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7079 7080 // Add the offset to the FP. 7081 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7082 setValue(&I, Add); 7083 7084 return; 7085 } 7086 7087 case Intrinsic::eh_exceptionpointer: 7088 case Intrinsic::eh_exceptioncode: { 7089 // Get the exception pointer vreg, copy from it, and resize it to fit. 7090 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7091 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7092 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7093 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7094 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7095 if (Intrinsic == Intrinsic::eh_exceptioncode) 7096 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7097 setValue(&I, N); 7098 return; 7099 } 7100 case Intrinsic::xray_customevent: { 7101 // Here we want to make sure that the intrinsic behaves as if it has a 7102 // specific calling convention, and only for x86_64. 7103 // FIXME: Support other platforms later. 7104 const auto &Triple = DAG.getTarget().getTargetTriple(); 7105 if (Triple.getArch() != Triple::x86_64) 7106 return; 7107 7108 SmallVector<SDValue, 8> Ops; 7109 7110 // We want to say that we always want the arguments in registers. 7111 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7112 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7113 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7114 SDValue Chain = getRoot(); 7115 Ops.push_back(LogEntryVal); 7116 Ops.push_back(StrSizeVal); 7117 Ops.push_back(Chain); 7118 7119 // We need to enforce the calling convention for the callsite, so that 7120 // argument ordering is enforced correctly, and that register allocation can 7121 // see that some registers may be assumed clobbered and have to preserve 7122 // them across calls to the intrinsic. 7123 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7124 sdl, NodeTys, Ops); 7125 SDValue patchableNode = SDValue(MN, 0); 7126 DAG.setRoot(patchableNode); 7127 setValue(&I, patchableNode); 7128 return; 7129 } 7130 case Intrinsic::xray_typedevent: { 7131 // Here we want to make sure that the intrinsic behaves as if it has a 7132 // specific calling convention, and only for x86_64. 7133 // FIXME: Support other platforms later. 7134 const auto &Triple = DAG.getTarget().getTargetTriple(); 7135 if (Triple.getArch() != Triple::x86_64) 7136 return; 7137 7138 SmallVector<SDValue, 8> Ops; 7139 7140 // We want to say that we always want the arguments in registers. 7141 // It's unclear to me how manipulating the selection DAG here forces callers 7142 // to provide arguments in registers instead of on the stack. 7143 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7144 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7145 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7146 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7147 SDValue Chain = getRoot(); 7148 Ops.push_back(LogTypeId); 7149 Ops.push_back(LogEntryVal); 7150 Ops.push_back(StrSizeVal); 7151 Ops.push_back(Chain); 7152 7153 // We need to enforce the calling convention for the callsite, so that 7154 // argument ordering is enforced correctly, and that register allocation can 7155 // see that some registers may be assumed clobbered and have to preserve 7156 // them across calls to the intrinsic. 7157 MachineSDNode *MN = DAG.getMachineNode( 7158 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7159 SDValue patchableNode = SDValue(MN, 0); 7160 DAG.setRoot(patchableNode); 7161 setValue(&I, patchableNode); 7162 return; 7163 } 7164 case Intrinsic::experimental_deoptimize: 7165 LowerDeoptimizeCall(&I); 7166 return; 7167 case Intrinsic::experimental_stepvector: 7168 visitStepVector(I); 7169 return; 7170 case Intrinsic::vector_reduce_fadd: 7171 case Intrinsic::vector_reduce_fmul: 7172 case Intrinsic::vector_reduce_add: 7173 case Intrinsic::vector_reduce_mul: 7174 case Intrinsic::vector_reduce_and: 7175 case Intrinsic::vector_reduce_or: 7176 case Intrinsic::vector_reduce_xor: 7177 case Intrinsic::vector_reduce_smax: 7178 case Intrinsic::vector_reduce_smin: 7179 case Intrinsic::vector_reduce_umax: 7180 case Intrinsic::vector_reduce_umin: 7181 case Intrinsic::vector_reduce_fmax: 7182 case Intrinsic::vector_reduce_fmin: 7183 visitVectorReduce(I, Intrinsic); 7184 return; 7185 7186 case Intrinsic::icall_branch_funnel: { 7187 SmallVector<SDValue, 16> Ops; 7188 Ops.push_back(getValue(I.getArgOperand(0))); 7189 7190 int64_t Offset; 7191 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7192 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7193 if (!Base) 7194 report_fatal_error( 7195 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7196 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7197 7198 struct BranchFunnelTarget { 7199 int64_t Offset; 7200 SDValue Target; 7201 }; 7202 SmallVector<BranchFunnelTarget, 8> Targets; 7203 7204 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7205 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7206 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7207 if (ElemBase != Base) 7208 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7209 "to the same GlobalValue"); 7210 7211 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7212 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7213 if (!GA) 7214 report_fatal_error( 7215 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7216 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7217 GA->getGlobal(), sdl, Val.getValueType(), 7218 GA->getOffset())}); 7219 } 7220 llvm::sort(Targets, 7221 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7222 return T1.Offset < T2.Offset; 7223 }); 7224 7225 for (auto &T : Targets) { 7226 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7227 Ops.push_back(T.Target); 7228 } 7229 7230 Ops.push_back(DAG.getRoot()); // Chain 7231 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7232 MVT::Other, Ops), 7233 0); 7234 DAG.setRoot(N); 7235 setValue(&I, N); 7236 HasTailCall = true; 7237 return; 7238 } 7239 7240 case Intrinsic::wasm_landingpad_index: 7241 // Information this intrinsic contained has been transferred to 7242 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7243 // delete it now. 7244 return; 7245 7246 case Intrinsic::aarch64_settag: 7247 case Intrinsic::aarch64_settag_zero: { 7248 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7249 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7250 SDValue Val = TSI.EmitTargetCodeForSetTag( 7251 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7252 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7253 ZeroMemory); 7254 DAG.setRoot(Val); 7255 setValue(&I, Val); 7256 return; 7257 } 7258 case Intrinsic::ptrmask: { 7259 SDValue Ptr = getValue(I.getOperand(0)); 7260 SDValue Const = getValue(I.getOperand(1)); 7261 7262 EVT PtrVT = Ptr.getValueType(); 7263 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7264 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7265 return; 7266 } 7267 case Intrinsic::threadlocal_address: { 7268 setValue(&I, getValue(I.getOperand(0))); 7269 return; 7270 } 7271 case Intrinsic::get_active_lane_mask: { 7272 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7273 SDValue Index = getValue(I.getOperand(0)); 7274 EVT ElementVT = Index.getValueType(); 7275 7276 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7277 visitTargetIntrinsic(I, Intrinsic); 7278 return; 7279 } 7280 7281 SDValue TripCount = getValue(I.getOperand(1)); 7282 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7283 7284 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7285 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7286 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7287 SDValue VectorInduction = DAG.getNode( 7288 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7289 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7290 VectorTripCount, ISD::CondCode::SETULT); 7291 setValue(&I, SetCC); 7292 return; 7293 } 7294 case Intrinsic::vector_insert: { 7295 SDValue Vec = getValue(I.getOperand(0)); 7296 SDValue SubVec = getValue(I.getOperand(1)); 7297 SDValue Index = getValue(I.getOperand(2)); 7298 7299 // The intrinsic's index type is i64, but the SDNode requires an index type 7300 // suitable for the target. Convert the index as required. 7301 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7302 if (Index.getValueType() != VectorIdxTy) 7303 Index = DAG.getVectorIdxConstant( 7304 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7305 7306 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7307 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7308 Index)); 7309 return; 7310 } 7311 case Intrinsic::vector_extract: { 7312 SDValue Vec = getValue(I.getOperand(0)); 7313 SDValue Index = getValue(I.getOperand(1)); 7314 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7315 7316 // The intrinsic's index type is i64, but the SDNode requires an index type 7317 // suitable for the target. Convert the index as required. 7318 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7319 if (Index.getValueType() != VectorIdxTy) 7320 Index = DAG.getVectorIdxConstant( 7321 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7322 7323 setValue(&I, 7324 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7325 return; 7326 } 7327 case Intrinsic::experimental_vector_reverse: 7328 visitVectorReverse(I); 7329 return; 7330 case Intrinsic::experimental_vector_splice: 7331 visitVectorSplice(I); 7332 return; 7333 case Intrinsic::callbr_landingpad: 7334 visitCallBrLandingPad(I); 7335 return; 7336 case Intrinsic::experimental_vector_interleave2: 7337 visitVectorInterleave(I); 7338 return; 7339 case Intrinsic::experimental_vector_deinterleave2: 7340 visitVectorDeinterleave(I); 7341 return; 7342 } 7343 } 7344 7345 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7346 const ConstrainedFPIntrinsic &FPI) { 7347 SDLoc sdl = getCurSDLoc(); 7348 7349 // We do not need to serialize constrained FP intrinsics against 7350 // each other or against (nonvolatile) loads, so they can be 7351 // chained like loads. 7352 SDValue Chain = DAG.getRoot(); 7353 SmallVector<SDValue, 4> Opers; 7354 Opers.push_back(Chain); 7355 if (FPI.isUnaryOp()) { 7356 Opers.push_back(getValue(FPI.getArgOperand(0))); 7357 } else if (FPI.isTernaryOp()) { 7358 Opers.push_back(getValue(FPI.getArgOperand(0))); 7359 Opers.push_back(getValue(FPI.getArgOperand(1))); 7360 Opers.push_back(getValue(FPI.getArgOperand(2))); 7361 } else { 7362 Opers.push_back(getValue(FPI.getArgOperand(0))); 7363 Opers.push_back(getValue(FPI.getArgOperand(1))); 7364 } 7365 7366 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7367 assert(Result.getNode()->getNumValues() == 2); 7368 7369 // Push node to the appropriate list so that future instructions can be 7370 // chained up correctly. 7371 SDValue OutChain = Result.getValue(1); 7372 switch (EB) { 7373 case fp::ExceptionBehavior::ebIgnore: 7374 // The only reason why ebIgnore nodes still need to be chained is that 7375 // they might depend on the current rounding mode, and therefore must 7376 // not be moved across instruction that may change that mode. 7377 [[fallthrough]]; 7378 case fp::ExceptionBehavior::ebMayTrap: 7379 // These must not be moved across calls or instructions that may change 7380 // floating-point exception masks. 7381 PendingConstrainedFP.push_back(OutChain); 7382 break; 7383 case fp::ExceptionBehavior::ebStrict: 7384 // These must not be moved across calls or instructions that may change 7385 // floating-point exception masks or read floating-point exception flags. 7386 // In addition, they cannot be optimized out even if unused. 7387 PendingConstrainedFPStrict.push_back(OutChain); 7388 break; 7389 } 7390 }; 7391 7392 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7393 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7394 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7395 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7396 7397 SDNodeFlags Flags; 7398 if (EB == fp::ExceptionBehavior::ebIgnore) 7399 Flags.setNoFPExcept(true); 7400 7401 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7402 Flags.copyFMF(*FPOp); 7403 7404 unsigned Opcode; 7405 switch (FPI.getIntrinsicID()) { 7406 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7407 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7408 case Intrinsic::INTRINSIC: \ 7409 Opcode = ISD::STRICT_##DAGN; \ 7410 break; 7411 #include "llvm/IR/ConstrainedOps.def" 7412 case Intrinsic::experimental_constrained_fmuladd: { 7413 Opcode = ISD::STRICT_FMA; 7414 // Break fmuladd into fmul and fadd. 7415 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7416 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7417 Opers.pop_back(); 7418 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7419 pushOutChain(Mul, EB); 7420 Opcode = ISD::STRICT_FADD; 7421 Opers.clear(); 7422 Opers.push_back(Mul.getValue(1)); 7423 Opers.push_back(Mul.getValue(0)); 7424 Opers.push_back(getValue(FPI.getArgOperand(2))); 7425 } 7426 break; 7427 } 7428 } 7429 7430 // A few strict DAG nodes carry additional operands that are not 7431 // set up by the default code above. 7432 switch (Opcode) { 7433 default: break; 7434 case ISD::STRICT_FP_ROUND: 7435 Opers.push_back( 7436 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7437 break; 7438 case ISD::STRICT_FSETCC: 7439 case ISD::STRICT_FSETCCS: { 7440 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7441 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7442 if (TM.Options.NoNaNsFPMath) 7443 Condition = getFCmpCodeWithoutNaN(Condition); 7444 Opers.push_back(DAG.getCondCode(Condition)); 7445 break; 7446 } 7447 } 7448 7449 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7450 pushOutChain(Result, EB); 7451 7452 SDValue FPResult = Result.getValue(0); 7453 setValue(&FPI, FPResult); 7454 } 7455 7456 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7457 std::optional<unsigned> ResOPC; 7458 switch (VPIntrin.getIntrinsicID()) { 7459 case Intrinsic::vp_ctlz: { 7460 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7461 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7462 break; 7463 } 7464 case Intrinsic::vp_cttz: { 7465 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7466 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7467 break; 7468 } 7469 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7470 case Intrinsic::VPID: \ 7471 ResOPC = ISD::VPSD; \ 7472 break; 7473 #include "llvm/IR/VPIntrinsics.def" 7474 } 7475 7476 if (!ResOPC) 7477 llvm_unreachable( 7478 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7479 7480 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7481 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7482 if (VPIntrin.getFastMathFlags().allowReassoc()) 7483 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7484 : ISD::VP_REDUCE_FMUL; 7485 } 7486 7487 return *ResOPC; 7488 } 7489 7490 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7491 SmallVector<SDValue, 7> &OpValues) { 7492 SDLoc DL = getCurSDLoc(); 7493 Value *PtrOperand = VPIntrin.getArgOperand(0); 7494 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7495 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7496 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7497 SDValue LD; 7498 bool AddToChain = true; 7499 // Do not serialize variable-length loads of constant memory with 7500 // anything. 7501 if (!Alignment) 7502 Alignment = DAG.getEVTAlign(VT); 7503 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7504 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7505 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7506 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7507 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7508 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7509 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7510 MMO, false /*IsExpanding */); 7511 if (AddToChain) 7512 PendingLoads.push_back(LD.getValue(1)); 7513 setValue(&VPIntrin, LD); 7514 } 7515 7516 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7517 SmallVector<SDValue, 7> &OpValues) { 7518 SDLoc DL = getCurSDLoc(); 7519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7520 Value *PtrOperand = VPIntrin.getArgOperand(0); 7521 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7522 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7523 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7524 SDValue LD; 7525 if (!Alignment) 7526 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7527 unsigned AS = 7528 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7529 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7530 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7531 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7532 SDValue Base, Index, Scale; 7533 ISD::MemIndexType IndexType; 7534 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7535 this, VPIntrin.getParent(), 7536 VT.getScalarStoreSize()); 7537 if (!UniformBase) { 7538 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7539 Index = getValue(PtrOperand); 7540 IndexType = ISD::SIGNED_SCALED; 7541 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7542 } 7543 EVT IdxVT = Index.getValueType(); 7544 EVT EltTy = IdxVT.getVectorElementType(); 7545 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7546 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7547 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7548 } 7549 LD = DAG.getGatherVP( 7550 DAG.getVTList(VT, MVT::Other), VT, DL, 7551 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7552 IndexType); 7553 PendingLoads.push_back(LD.getValue(1)); 7554 setValue(&VPIntrin, LD); 7555 } 7556 7557 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7558 SmallVector<SDValue, 7> &OpValues) { 7559 SDLoc DL = getCurSDLoc(); 7560 Value *PtrOperand = VPIntrin.getArgOperand(1); 7561 EVT VT = OpValues[0].getValueType(); 7562 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7563 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7564 SDValue ST; 7565 if (!Alignment) 7566 Alignment = DAG.getEVTAlign(VT); 7567 SDValue Ptr = OpValues[1]; 7568 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7569 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7570 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7571 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7572 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7573 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7574 /* IsTruncating */ false, /*IsCompressing*/ false); 7575 DAG.setRoot(ST); 7576 setValue(&VPIntrin, ST); 7577 } 7578 7579 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7580 SmallVector<SDValue, 7> &OpValues) { 7581 SDLoc DL = getCurSDLoc(); 7582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7583 Value *PtrOperand = VPIntrin.getArgOperand(1); 7584 EVT VT = OpValues[0].getValueType(); 7585 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7586 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7587 SDValue ST; 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::MOStore, 7594 MemoryLocation::UnknownSize, *Alignment, AAInfo); 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 = 7605 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7606 } 7607 EVT IdxVT = Index.getValueType(); 7608 EVT EltTy = IdxVT.getVectorElementType(); 7609 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7610 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7611 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7612 } 7613 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7614 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7615 OpValues[2], OpValues[3]}, 7616 MMO, IndexType); 7617 DAG.setRoot(ST); 7618 setValue(&VPIntrin, ST); 7619 } 7620 7621 void SelectionDAGBuilder::visitVPStridedLoad( 7622 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7623 SDLoc DL = getCurSDLoc(); 7624 Value *PtrOperand = VPIntrin.getArgOperand(0); 7625 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7626 if (!Alignment) 7627 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7628 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7629 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7630 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7631 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7632 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7633 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7634 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7635 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7636 7637 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7638 OpValues[2], OpValues[3], MMO, 7639 false /*IsExpanding*/); 7640 7641 if (AddToChain) 7642 PendingLoads.push_back(LD.getValue(1)); 7643 setValue(&VPIntrin, LD); 7644 } 7645 7646 void SelectionDAGBuilder::visitVPStridedStore( 7647 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7648 SDLoc DL = getCurSDLoc(); 7649 Value *PtrOperand = VPIntrin.getArgOperand(1); 7650 EVT VT = OpValues[0].getValueType(); 7651 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7652 if (!Alignment) 7653 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7654 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7655 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7656 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7657 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7658 7659 SDValue ST = DAG.getStridedStoreVP( 7660 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7661 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7662 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7663 /*IsCompressing*/ false); 7664 7665 DAG.setRoot(ST); 7666 setValue(&VPIntrin, ST); 7667 } 7668 7669 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7670 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7671 SDLoc DL = getCurSDLoc(); 7672 7673 ISD::CondCode Condition; 7674 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7675 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7676 if (IsFP) { 7677 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7678 // flags, but calls that don't return floating-point types can't be 7679 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7680 Condition = getFCmpCondCode(CondCode); 7681 if (TM.Options.NoNaNsFPMath) 7682 Condition = getFCmpCodeWithoutNaN(Condition); 7683 } else { 7684 Condition = getICmpCondCode(CondCode); 7685 } 7686 7687 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7688 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7689 // #2 is the condition code 7690 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7691 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7692 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7693 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7694 "Unexpected target EVL type"); 7695 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7696 7697 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7698 VPIntrin.getType()); 7699 setValue(&VPIntrin, 7700 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7701 } 7702 7703 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7704 const VPIntrinsic &VPIntrin) { 7705 SDLoc DL = getCurSDLoc(); 7706 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7707 7708 auto IID = VPIntrin.getIntrinsicID(); 7709 7710 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7711 return visitVPCmp(*CmpI); 7712 7713 SmallVector<EVT, 4> ValueVTs; 7714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7715 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7716 SDVTList VTs = DAG.getVTList(ValueVTs); 7717 7718 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7719 7720 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7721 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7722 "Unexpected target EVL type"); 7723 7724 // Request operands. 7725 SmallVector<SDValue, 7> OpValues; 7726 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7727 auto Op = getValue(VPIntrin.getArgOperand(I)); 7728 if (I == EVLParamPos) 7729 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7730 OpValues.push_back(Op); 7731 } 7732 7733 switch (Opcode) { 7734 default: { 7735 SDNodeFlags SDFlags; 7736 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7737 SDFlags.copyFMF(*FPMO); 7738 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7739 setValue(&VPIntrin, Result); 7740 break; 7741 } 7742 case ISD::VP_LOAD: 7743 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7744 break; 7745 case ISD::VP_GATHER: 7746 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7747 break; 7748 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7749 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7750 break; 7751 case ISD::VP_STORE: 7752 visitVPStore(VPIntrin, OpValues); 7753 break; 7754 case ISD::VP_SCATTER: 7755 visitVPScatter(VPIntrin, OpValues); 7756 break; 7757 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7758 visitVPStridedStore(VPIntrin, OpValues); 7759 break; 7760 case ISD::VP_FMULADD: { 7761 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7762 SDNodeFlags SDFlags; 7763 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7764 SDFlags.copyFMF(*FPMO); 7765 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7766 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7767 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7768 } else { 7769 SDValue Mul = DAG.getNode( 7770 ISD::VP_FMUL, DL, VTs, 7771 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7772 SDValue Add = 7773 DAG.getNode(ISD::VP_FADD, DL, VTs, 7774 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7775 setValue(&VPIntrin, Add); 7776 } 7777 break; 7778 } 7779 case ISD::VP_INTTOPTR: { 7780 SDValue N = OpValues[0]; 7781 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7782 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7783 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7784 OpValues[2]); 7785 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7786 OpValues[2]); 7787 setValue(&VPIntrin, N); 7788 break; 7789 } 7790 case ISD::VP_PTRTOINT: { 7791 SDValue N = OpValues[0]; 7792 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7793 VPIntrin.getType()); 7794 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7795 VPIntrin.getOperand(0)->getType()); 7796 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7797 OpValues[2]); 7798 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7799 OpValues[2]); 7800 setValue(&VPIntrin, N); 7801 break; 7802 } 7803 case ISD::VP_ABS: 7804 case ISD::VP_CTLZ: 7805 case ISD::VP_CTLZ_ZERO_UNDEF: 7806 case ISD::VP_CTTZ: 7807 case ISD::VP_CTTZ_ZERO_UNDEF: { 7808 SDValue Result = 7809 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7810 setValue(&VPIntrin, Result); 7811 break; 7812 } 7813 } 7814 } 7815 7816 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7817 const BasicBlock *EHPadBB, 7818 MCSymbol *&BeginLabel) { 7819 MachineFunction &MF = DAG.getMachineFunction(); 7820 MachineModuleInfo &MMI = MF.getMMI(); 7821 7822 // Insert a label before the invoke call to mark the try range. This can be 7823 // used to detect deletion of the invoke via the MachineModuleInfo. 7824 BeginLabel = MMI.getContext().createTempSymbol(); 7825 7826 // For SjLj, keep track of which landing pads go with which invokes 7827 // so as to maintain the ordering of pads in the LSDA. 7828 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7829 if (CallSiteIndex) { 7830 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7831 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7832 7833 // Now that the call site is handled, stop tracking it. 7834 MMI.setCurrentCallSite(0); 7835 } 7836 7837 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7838 } 7839 7840 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7841 const BasicBlock *EHPadBB, 7842 MCSymbol *BeginLabel) { 7843 assert(BeginLabel && "BeginLabel should've been set"); 7844 7845 MachineFunction &MF = DAG.getMachineFunction(); 7846 MachineModuleInfo &MMI = MF.getMMI(); 7847 7848 // Insert a label at the end of the invoke call to mark the try range. This 7849 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7850 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7851 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7852 7853 // Inform MachineModuleInfo of range. 7854 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7855 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7856 // actually use outlined funclets and their LSDA info style. 7857 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7858 assert(II && "II should've been set"); 7859 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7860 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7861 } else if (!isScopedEHPersonality(Pers)) { 7862 assert(EHPadBB); 7863 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7864 } 7865 7866 return Chain; 7867 } 7868 7869 std::pair<SDValue, SDValue> 7870 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7871 const BasicBlock *EHPadBB) { 7872 MCSymbol *BeginLabel = nullptr; 7873 7874 if (EHPadBB) { 7875 // Both PendingLoads and PendingExports must be flushed here; 7876 // this call might not return. 7877 (void)getRoot(); 7878 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7879 CLI.setChain(getRoot()); 7880 } 7881 7882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7883 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7884 7885 assert((CLI.IsTailCall || Result.second.getNode()) && 7886 "Non-null chain expected with non-tail call!"); 7887 assert((Result.second.getNode() || !Result.first.getNode()) && 7888 "Null value expected with tail call!"); 7889 7890 if (!Result.second.getNode()) { 7891 // As a special case, a null chain means that a tail call has been emitted 7892 // and the DAG root is already updated. 7893 HasTailCall = true; 7894 7895 // Since there's no actual continuation from this block, nothing can be 7896 // relying on us setting vregs for them. 7897 PendingExports.clear(); 7898 } else { 7899 DAG.setRoot(Result.second); 7900 } 7901 7902 if (EHPadBB) { 7903 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7904 BeginLabel)); 7905 } 7906 7907 return Result; 7908 } 7909 7910 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7911 bool isTailCall, 7912 bool isMustTailCall, 7913 const BasicBlock *EHPadBB) { 7914 auto &DL = DAG.getDataLayout(); 7915 FunctionType *FTy = CB.getFunctionType(); 7916 Type *RetTy = CB.getType(); 7917 7918 TargetLowering::ArgListTy Args; 7919 Args.reserve(CB.arg_size()); 7920 7921 const Value *SwiftErrorVal = nullptr; 7922 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7923 7924 if (isTailCall) { 7925 // Avoid emitting tail calls in functions with the disable-tail-calls 7926 // attribute. 7927 auto *Caller = CB.getParent()->getParent(); 7928 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7929 "true" && !isMustTailCall) 7930 isTailCall = false; 7931 7932 // We can't tail call inside a function with a swifterror argument. Lowering 7933 // does not support this yet. It would have to move into the swifterror 7934 // register before the call. 7935 if (TLI.supportSwiftError() && 7936 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7937 isTailCall = false; 7938 } 7939 7940 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7941 TargetLowering::ArgListEntry Entry; 7942 const Value *V = *I; 7943 7944 // Skip empty types 7945 if (V->getType()->isEmptyTy()) 7946 continue; 7947 7948 SDValue ArgNode = getValue(V); 7949 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7950 7951 Entry.setAttributes(&CB, I - CB.arg_begin()); 7952 7953 // Use swifterror virtual register as input to the call. 7954 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7955 SwiftErrorVal = V; 7956 // We find the virtual register for the actual swifterror argument. 7957 // Instead of using the Value, we use the virtual register instead. 7958 Entry.Node = 7959 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7960 EVT(TLI.getPointerTy(DL))); 7961 } 7962 7963 Args.push_back(Entry); 7964 7965 // If we have an explicit sret argument that is an Instruction, (i.e., it 7966 // might point to function-local memory), we can't meaningfully tail-call. 7967 if (Entry.IsSRet && isa<Instruction>(V)) 7968 isTailCall = false; 7969 } 7970 7971 // If call site has a cfguardtarget operand bundle, create and add an 7972 // additional ArgListEntry. 7973 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7974 TargetLowering::ArgListEntry Entry; 7975 Value *V = Bundle->Inputs[0]; 7976 SDValue ArgNode = getValue(V); 7977 Entry.Node = ArgNode; 7978 Entry.Ty = V->getType(); 7979 Entry.IsCFGuardTarget = true; 7980 Args.push_back(Entry); 7981 } 7982 7983 // Check if target-independent constraints permit a tail call here. 7984 // Target-dependent constraints are checked within TLI->LowerCallTo. 7985 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7986 isTailCall = false; 7987 7988 // Disable tail calls if there is an swifterror argument. Targets have not 7989 // been updated to support tail calls. 7990 if (TLI.supportSwiftError() && SwiftErrorVal) 7991 isTailCall = false; 7992 7993 ConstantInt *CFIType = nullptr; 7994 if (CB.isIndirectCall()) { 7995 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7996 if (!TLI.supportKCFIBundles()) 7997 report_fatal_error( 7998 "Target doesn't support calls with kcfi operand bundles."); 7999 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8000 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8001 } 8002 } 8003 8004 TargetLowering::CallLoweringInfo CLI(DAG); 8005 CLI.setDebugLoc(getCurSDLoc()) 8006 .setChain(getRoot()) 8007 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8008 .setTailCall(isTailCall) 8009 .setConvergent(CB.isConvergent()) 8010 .setIsPreallocated( 8011 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8012 .setCFIType(CFIType); 8013 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8014 8015 if (Result.first.getNode()) { 8016 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8017 setValue(&CB, Result.first); 8018 } 8019 8020 // The last element of CLI.InVals has the SDValue for swifterror return. 8021 // Here we copy it to a virtual register and update SwiftErrorMap for 8022 // book-keeping. 8023 if (SwiftErrorVal && TLI.supportSwiftError()) { 8024 // Get the last element of InVals. 8025 SDValue Src = CLI.InVals.back(); 8026 Register VReg = 8027 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8028 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8029 DAG.setRoot(CopyNode); 8030 } 8031 } 8032 8033 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8034 SelectionDAGBuilder &Builder) { 8035 // Check to see if this load can be trivially constant folded, e.g. if the 8036 // input is from a string literal. 8037 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8038 // Cast pointer to the type we really want to load. 8039 Type *LoadTy = 8040 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8041 if (LoadVT.isVector()) 8042 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8043 8044 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8045 PointerType::getUnqual(LoadTy)); 8046 8047 if (const Constant *LoadCst = 8048 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8049 LoadTy, Builder.DAG.getDataLayout())) 8050 return Builder.getValue(LoadCst); 8051 } 8052 8053 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8054 // still constant memory, the input chain can be the entry node. 8055 SDValue Root; 8056 bool ConstantMemory = false; 8057 8058 // Do not serialize (non-volatile) loads of constant memory with anything. 8059 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8060 Root = Builder.DAG.getEntryNode(); 8061 ConstantMemory = true; 8062 } else { 8063 // Do not serialize non-volatile loads against each other. 8064 Root = Builder.DAG.getRoot(); 8065 } 8066 8067 SDValue Ptr = Builder.getValue(PtrVal); 8068 SDValue LoadVal = 8069 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8070 MachinePointerInfo(PtrVal), Align(1)); 8071 8072 if (!ConstantMemory) 8073 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8074 return LoadVal; 8075 } 8076 8077 /// Record the value for an instruction that produces an integer result, 8078 /// converting the type where necessary. 8079 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8080 SDValue Value, 8081 bool IsSigned) { 8082 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8083 I.getType(), true); 8084 if (IsSigned) 8085 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8086 else 8087 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8088 setValue(&I, Value); 8089 } 8090 8091 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8092 /// true and lower it. Otherwise return false, and it will be lowered like a 8093 /// normal call. 8094 /// The caller already checked that \p I calls the appropriate LibFunc with a 8095 /// correct prototype. 8096 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8097 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8098 const Value *Size = I.getArgOperand(2); 8099 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8100 if (CSize && CSize->getZExtValue() == 0) { 8101 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8102 I.getType(), true); 8103 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8104 return true; 8105 } 8106 8107 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8108 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8109 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8110 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8111 if (Res.first.getNode()) { 8112 processIntegerCallValue(I, Res.first, true); 8113 PendingLoads.push_back(Res.second); 8114 return true; 8115 } 8116 8117 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8118 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8119 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8120 return false; 8121 8122 // If the target has a fast compare for the given size, it will return a 8123 // preferred load type for that size. Require that the load VT is legal and 8124 // that the target supports unaligned loads of that type. Otherwise, return 8125 // INVALID. 8126 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8128 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8129 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8130 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8131 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8132 // TODO: Check alignment of src and dest ptrs. 8133 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8134 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8135 if (!TLI.isTypeLegal(LVT) || 8136 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8137 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8138 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8139 } 8140 8141 return LVT; 8142 }; 8143 8144 // This turns into unaligned loads. We only do this if the target natively 8145 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8146 // we'll only produce a small number of byte loads. 8147 MVT LoadVT; 8148 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8149 switch (NumBitsToCompare) { 8150 default: 8151 return false; 8152 case 16: 8153 LoadVT = MVT::i16; 8154 break; 8155 case 32: 8156 LoadVT = MVT::i32; 8157 break; 8158 case 64: 8159 case 128: 8160 case 256: 8161 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8162 break; 8163 } 8164 8165 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8166 return false; 8167 8168 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8169 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8170 8171 // Bitcast to a wide integer type if the loads are vectors. 8172 if (LoadVT.isVector()) { 8173 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8174 LoadL = DAG.getBitcast(CmpVT, LoadL); 8175 LoadR = DAG.getBitcast(CmpVT, LoadR); 8176 } 8177 8178 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8179 processIntegerCallValue(I, Cmp, false); 8180 return true; 8181 } 8182 8183 /// See if we can lower a memchr call into an optimized form. If so, return 8184 /// true and lower it. Otherwise return false, and it will be lowered like a 8185 /// normal call. 8186 /// The caller already checked that \p I calls the appropriate LibFunc with a 8187 /// correct prototype. 8188 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8189 const Value *Src = I.getArgOperand(0); 8190 const Value *Char = I.getArgOperand(1); 8191 const Value *Length = I.getArgOperand(2); 8192 8193 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8194 std::pair<SDValue, SDValue> Res = 8195 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8196 getValue(Src), getValue(Char), getValue(Length), 8197 MachinePointerInfo(Src)); 8198 if (Res.first.getNode()) { 8199 setValue(&I, Res.first); 8200 PendingLoads.push_back(Res.second); 8201 return true; 8202 } 8203 8204 return false; 8205 } 8206 8207 /// See if we can lower a mempcpy call into an optimized form. If so, return 8208 /// true and lower it. Otherwise return false, and it will be lowered like a 8209 /// normal call. 8210 /// The caller already checked that \p I calls the appropriate LibFunc with a 8211 /// correct prototype. 8212 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8213 SDValue Dst = getValue(I.getArgOperand(0)); 8214 SDValue Src = getValue(I.getArgOperand(1)); 8215 SDValue Size = getValue(I.getArgOperand(2)); 8216 8217 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8218 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8219 // DAG::getMemcpy needs Alignment to be defined. 8220 Align Alignment = std::min(DstAlign, SrcAlign); 8221 8222 bool isVol = false; 8223 SDLoc sdl = getCurSDLoc(); 8224 8225 // In the mempcpy context we need to pass in a false value for isTailCall 8226 // because the return pointer needs to be adjusted by the size of 8227 // the copied memory. 8228 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8229 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8230 /*isTailCall=*/false, 8231 MachinePointerInfo(I.getArgOperand(0)), 8232 MachinePointerInfo(I.getArgOperand(1)), 8233 I.getAAMetadata()); 8234 assert(MC.getNode() != nullptr && 8235 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8236 DAG.setRoot(MC); 8237 8238 // Check if Size needs to be truncated or extended. 8239 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8240 8241 // Adjust return pointer to point just past the last dst byte. 8242 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8243 Dst, Size); 8244 setValue(&I, DstPlusSize); 8245 return true; 8246 } 8247 8248 /// See if we can lower a strcpy call into an optimized form. If so, return 8249 /// true and lower it, otherwise return false and it will be lowered like a 8250 /// normal call. 8251 /// The caller already checked that \p I calls the appropriate LibFunc with a 8252 /// correct prototype. 8253 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8254 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8255 8256 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8257 std::pair<SDValue, SDValue> Res = 8258 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8259 getValue(Arg0), getValue(Arg1), 8260 MachinePointerInfo(Arg0), 8261 MachinePointerInfo(Arg1), isStpcpy); 8262 if (Res.first.getNode()) { 8263 setValue(&I, Res.first); 8264 DAG.setRoot(Res.second); 8265 return true; 8266 } 8267 8268 return false; 8269 } 8270 8271 /// See if we can lower a strcmp 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::visitStrCmpCall(const CallInst &I) { 8277 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8278 8279 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8280 std::pair<SDValue, SDValue> Res = 8281 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8282 getValue(Arg0), getValue(Arg1), 8283 MachinePointerInfo(Arg0), 8284 MachinePointerInfo(Arg1)); 8285 if (Res.first.getNode()) { 8286 processIntegerCallValue(I, Res.first, true); 8287 PendingLoads.push_back(Res.second); 8288 return true; 8289 } 8290 8291 return false; 8292 } 8293 8294 /// See if we can lower a strlen call into an optimized form. If so, return 8295 /// true and lower it, otherwise return false and it will be lowered like a 8296 /// normal call. 8297 /// The caller already checked that \p I calls the appropriate LibFunc with a 8298 /// correct prototype. 8299 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8300 const Value *Arg0 = I.getArgOperand(0); 8301 8302 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8303 std::pair<SDValue, SDValue> Res = 8304 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8305 getValue(Arg0), MachinePointerInfo(Arg0)); 8306 if (Res.first.getNode()) { 8307 processIntegerCallValue(I, Res.first, false); 8308 PendingLoads.push_back(Res.second); 8309 return true; 8310 } 8311 8312 return false; 8313 } 8314 8315 /// See if we can lower a strnlen call into an optimized form. If so, return 8316 /// true and lower it, otherwise return false and it will be lowered like a 8317 /// normal call. 8318 /// The caller already checked that \p I calls the appropriate LibFunc with a 8319 /// correct prototype. 8320 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8321 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8322 8323 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8324 std::pair<SDValue, SDValue> Res = 8325 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8326 getValue(Arg0), getValue(Arg1), 8327 MachinePointerInfo(Arg0)); 8328 if (Res.first.getNode()) { 8329 processIntegerCallValue(I, Res.first, false); 8330 PendingLoads.push_back(Res.second); 8331 return true; 8332 } 8333 8334 return false; 8335 } 8336 8337 /// See if we can lower a unary floating-point operation into an SDNode with 8338 /// the specified Opcode. If so, return true and lower it, otherwise return 8339 /// false and it will be lowered like a normal call. 8340 /// The caller already checked that \p I calls the appropriate LibFunc with a 8341 /// correct prototype. 8342 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8343 unsigned Opcode) { 8344 // We already checked this call's prototype; verify it doesn't modify errno. 8345 if (!I.onlyReadsMemory()) 8346 return false; 8347 8348 SDNodeFlags Flags; 8349 Flags.copyFMF(cast<FPMathOperator>(I)); 8350 8351 SDValue Tmp = getValue(I.getArgOperand(0)); 8352 setValue(&I, 8353 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8354 return true; 8355 } 8356 8357 /// See if we can lower a binary floating-point operation into an SDNode with 8358 /// the specified Opcode. If so, return true and lower it. Otherwise return 8359 /// false, and it will be lowered like a normal call. 8360 /// The caller already checked that \p I calls the appropriate LibFunc with a 8361 /// correct prototype. 8362 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8363 unsigned Opcode) { 8364 // We already checked this call's prototype; verify it doesn't modify errno. 8365 if (!I.onlyReadsMemory()) 8366 return false; 8367 8368 SDNodeFlags Flags; 8369 Flags.copyFMF(cast<FPMathOperator>(I)); 8370 8371 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8372 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8373 EVT VT = Tmp0.getValueType(); 8374 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8375 return true; 8376 } 8377 8378 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8379 // Handle inline assembly differently. 8380 if (I.isInlineAsm()) { 8381 visitInlineAsm(I); 8382 return; 8383 } 8384 8385 diagnoseDontCall(I); 8386 8387 if (Function *F = I.getCalledFunction()) { 8388 if (F->isDeclaration()) { 8389 // Is this an LLVM intrinsic or a target-specific intrinsic? 8390 unsigned IID = F->getIntrinsicID(); 8391 if (!IID) 8392 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8393 IID = II->getIntrinsicID(F); 8394 8395 if (IID) { 8396 visitIntrinsicCall(I, IID); 8397 return; 8398 } 8399 } 8400 8401 // Check for well-known libc/libm calls. If the function is internal, it 8402 // can't be a library call. Don't do the check if marked as nobuiltin for 8403 // some reason or the call site requires strict floating point semantics. 8404 LibFunc Func; 8405 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8406 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8407 LibInfo->hasOptimizedCodeGen(Func)) { 8408 switch (Func) { 8409 default: break; 8410 case LibFunc_bcmp: 8411 if (visitMemCmpBCmpCall(I)) 8412 return; 8413 break; 8414 case LibFunc_copysign: 8415 case LibFunc_copysignf: 8416 case LibFunc_copysignl: 8417 // We already checked this call's prototype; verify it doesn't modify 8418 // errno. 8419 if (I.onlyReadsMemory()) { 8420 SDValue LHS = getValue(I.getArgOperand(0)); 8421 SDValue RHS = getValue(I.getArgOperand(1)); 8422 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8423 LHS.getValueType(), LHS, RHS)); 8424 return; 8425 } 8426 break; 8427 case LibFunc_fabs: 8428 case LibFunc_fabsf: 8429 case LibFunc_fabsl: 8430 if (visitUnaryFloatCall(I, ISD::FABS)) 8431 return; 8432 break; 8433 case LibFunc_fmin: 8434 case LibFunc_fminf: 8435 case LibFunc_fminl: 8436 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8437 return; 8438 break; 8439 case LibFunc_fmax: 8440 case LibFunc_fmaxf: 8441 case LibFunc_fmaxl: 8442 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8443 return; 8444 break; 8445 case LibFunc_sin: 8446 case LibFunc_sinf: 8447 case LibFunc_sinl: 8448 if (visitUnaryFloatCall(I, ISD::FSIN)) 8449 return; 8450 break; 8451 case LibFunc_cos: 8452 case LibFunc_cosf: 8453 case LibFunc_cosl: 8454 if (visitUnaryFloatCall(I, ISD::FCOS)) 8455 return; 8456 break; 8457 case LibFunc_sqrt: 8458 case LibFunc_sqrtf: 8459 case LibFunc_sqrtl: 8460 case LibFunc_sqrt_finite: 8461 case LibFunc_sqrtf_finite: 8462 case LibFunc_sqrtl_finite: 8463 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8464 return; 8465 break; 8466 case LibFunc_floor: 8467 case LibFunc_floorf: 8468 case LibFunc_floorl: 8469 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8470 return; 8471 break; 8472 case LibFunc_nearbyint: 8473 case LibFunc_nearbyintf: 8474 case LibFunc_nearbyintl: 8475 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8476 return; 8477 break; 8478 case LibFunc_ceil: 8479 case LibFunc_ceilf: 8480 case LibFunc_ceill: 8481 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8482 return; 8483 break; 8484 case LibFunc_rint: 8485 case LibFunc_rintf: 8486 case LibFunc_rintl: 8487 if (visitUnaryFloatCall(I, ISD::FRINT)) 8488 return; 8489 break; 8490 case LibFunc_round: 8491 case LibFunc_roundf: 8492 case LibFunc_roundl: 8493 if (visitUnaryFloatCall(I, ISD::FROUND)) 8494 return; 8495 break; 8496 case LibFunc_trunc: 8497 case LibFunc_truncf: 8498 case LibFunc_truncl: 8499 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8500 return; 8501 break; 8502 case LibFunc_log2: 8503 case LibFunc_log2f: 8504 case LibFunc_log2l: 8505 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8506 return; 8507 break; 8508 case LibFunc_exp2: 8509 case LibFunc_exp2f: 8510 case LibFunc_exp2l: 8511 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8512 return; 8513 break; 8514 case LibFunc_memcmp: 8515 if (visitMemCmpBCmpCall(I)) 8516 return; 8517 break; 8518 case LibFunc_mempcpy: 8519 if (visitMemPCpyCall(I)) 8520 return; 8521 break; 8522 case LibFunc_memchr: 8523 if (visitMemChrCall(I)) 8524 return; 8525 break; 8526 case LibFunc_strcpy: 8527 if (visitStrCpyCall(I, false)) 8528 return; 8529 break; 8530 case LibFunc_stpcpy: 8531 if (visitStrCpyCall(I, true)) 8532 return; 8533 break; 8534 case LibFunc_strcmp: 8535 if (visitStrCmpCall(I)) 8536 return; 8537 break; 8538 case LibFunc_strlen: 8539 if (visitStrLenCall(I)) 8540 return; 8541 break; 8542 case LibFunc_strnlen: 8543 if (visitStrNLenCall(I)) 8544 return; 8545 break; 8546 } 8547 } 8548 } 8549 8550 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8551 // have to do anything here to lower funclet bundles. 8552 // CFGuardTarget bundles are lowered in LowerCallTo. 8553 assert(!I.hasOperandBundlesOtherThan( 8554 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8555 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8556 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8557 "Cannot lower calls with arbitrary operand bundles!"); 8558 8559 SDValue Callee = getValue(I.getCalledOperand()); 8560 8561 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8562 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8563 else 8564 // Check if we can potentially perform a tail call. More detailed checking 8565 // is be done within LowerCallTo, after more information about the call is 8566 // known. 8567 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8568 } 8569 8570 namespace { 8571 8572 /// AsmOperandInfo - This contains information for each constraint that we are 8573 /// lowering. 8574 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8575 public: 8576 /// CallOperand - If this is the result output operand or a clobber 8577 /// this is null, otherwise it is the incoming operand to the CallInst. 8578 /// This gets modified as the asm is processed. 8579 SDValue CallOperand; 8580 8581 /// AssignedRegs - If this is a register or register class operand, this 8582 /// contains the set of register corresponding to the operand. 8583 RegsForValue AssignedRegs; 8584 8585 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8586 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8587 } 8588 8589 /// Whether or not this operand accesses memory 8590 bool hasMemory(const TargetLowering &TLI) const { 8591 // Indirect operand accesses access memory. 8592 if (isIndirect) 8593 return true; 8594 8595 for (const auto &Code : Codes) 8596 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8597 return true; 8598 8599 return false; 8600 } 8601 }; 8602 8603 8604 } // end anonymous namespace 8605 8606 /// Make sure that the output operand \p OpInfo and its corresponding input 8607 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8608 /// out). 8609 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8610 SDISelAsmOperandInfo &MatchingOpInfo, 8611 SelectionDAG &DAG) { 8612 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8613 return; 8614 8615 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8616 const auto &TLI = DAG.getTargetLoweringInfo(); 8617 8618 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8619 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8620 OpInfo.ConstraintVT); 8621 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8622 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8623 MatchingOpInfo.ConstraintVT); 8624 if ((OpInfo.ConstraintVT.isInteger() != 8625 MatchingOpInfo.ConstraintVT.isInteger()) || 8626 (MatchRC.second != InputRC.second)) { 8627 // FIXME: error out in a more elegant fashion 8628 report_fatal_error("Unsupported asm: input constraint" 8629 " with a matching output constraint of" 8630 " incompatible type!"); 8631 } 8632 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8633 } 8634 8635 /// Get a direct memory input to behave well as an indirect operand. 8636 /// This may introduce stores, hence the need for a \p Chain. 8637 /// \return The (possibly updated) chain. 8638 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8639 SDISelAsmOperandInfo &OpInfo, 8640 SelectionDAG &DAG) { 8641 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8642 8643 // If we don't have an indirect input, put it in the constpool if we can, 8644 // otherwise spill it to a stack slot. 8645 // TODO: This isn't quite right. We need to handle these according to 8646 // the addressing mode that the constraint wants. Also, this may take 8647 // an additional register for the computation and we don't want that 8648 // either. 8649 8650 // If the operand is a float, integer, or vector constant, spill to a 8651 // constant pool entry to get its address. 8652 const Value *OpVal = OpInfo.CallOperandVal; 8653 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8654 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8655 OpInfo.CallOperand = DAG.getConstantPool( 8656 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8657 return Chain; 8658 } 8659 8660 // Otherwise, create a stack slot and emit a store to it before the asm. 8661 Type *Ty = OpVal->getType(); 8662 auto &DL = DAG.getDataLayout(); 8663 uint64_t TySize = DL.getTypeAllocSize(Ty); 8664 MachineFunction &MF = DAG.getMachineFunction(); 8665 int SSFI = MF.getFrameInfo().CreateStackObject( 8666 TySize, DL.getPrefTypeAlign(Ty), false); 8667 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8668 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8669 MachinePointerInfo::getFixedStack(MF, SSFI), 8670 TLI.getMemValueType(DL, Ty)); 8671 OpInfo.CallOperand = StackSlot; 8672 8673 return Chain; 8674 } 8675 8676 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8677 /// specified operand. We prefer to assign virtual registers, to allow the 8678 /// register allocator to handle the assignment process. However, if the asm 8679 /// uses features that we can't model on machineinstrs, we have SDISel do the 8680 /// allocation. This produces generally horrible, but correct, code. 8681 /// 8682 /// OpInfo describes the operand 8683 /// RefOpInfo describes the matching operand if any, the operand otherwise 8684 static std::optional<unsigned> 8685 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8686 SDISelAsmOperandInfo &OpInfo, 8687 SDISelAsmOperandInfo &RefOpInfo) { 8688 LLVMContext &Context = *DAG.getContext(); 8689 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8690 8691 MachineFunction &MF = DAG.getMachineFunction(); 8692 SmallVector<unsigned, 4> Regs; 8693 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8694 8695 // No work to do for memory/address operands. 8696 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8697 OpInfo.ConstraintType == TargetLowering::C_Address) 8698 return std::nullopt; 8699 8700 // If this is a constraint for a single physreg, or a constraint for a 8701 // register class, find it. 8702 unsigned AssignedReg; 8703 const TargetRegisterClass *RC; 8704 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8705 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8706 // RC is unset only on failure. Return immediately. 8707 if (!RC) 8708 return std::nullopt; 8709 8710 // Get the actual register value type. This is important, because the user 8711 // may have asked for (e.g.) the AX register in i32 type. We need to 8712 // remember that AX is actually i16 to get the right extension. 8713 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8714 8715 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8716 // If this is an FP operand in an integer register (or visa versa), or more 8717 // generally if the operand value disagrees with the register class we plan 8718 // to stick it in, fix the operand type. 8719 // 8720 // If this is an input value, the bitcast to the new type is done now. 8721 // Bitcast for output value is done at the end of visitInlineAsm(). 8722 if ((OpInfo.Type == InlineAsm::isOutput || 8723 OpInfo.Type == InlineAsm::isInput) && 8724 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8725 // Try to convert to the first EVT that the reg class contains. If the 8726 // types are identical size, use a bitcast to convert (e.g. two differing 8727 // vector types). Note: output bitcast is done at the end of 8728 // visitInlineAsm(). 8729 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8730 // Exclude indirect inputs while they are unsupported because the code 8731 // to perform the load is missing and thus OpInfo.CallOperand still 8732 // refers to the input address rather than the pointed-to value. 8733 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8734 OpInfo.CallOperand = 8735 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8736 OpInfo.ConstraintVT = RegVT; 8737 // If the operand is an FP value and we want it in integer registers, 8738 // use the corresponding integer type. This turns an f64 value into 8739 // i64, which can be passed with two i32 values on a 32-bit machine. 8740 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8741 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8742 if (OpInfo.Type == InlineAsm::isInput) 8743 OpInfo.CallOperand = 8744 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8745 OpInfo.ConstraintVT = VT; 8746 } 8747 } 8748 } 8749 8750 // No need to allocate a matching input constraint since the constraint it's 8751 // matching to has already been allocated. 8752 if (OpInfo.isMatchingInputConstraint()) 8753 return std::nullopt; 8754 8755 EVT ValueVT = OpInfo.ConstraintVT; 8756 if (OpInfo.ConstraintVT == MVT::Other) 8757 ValueVT = RegVT; 8758 8759 // Initialize NumRegs. 8760 unsigned NumRegs = 1; 8761 if (OpInfo.ConstraintVT != MVT::Other) 8762 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8763 8764 // If this is a constraint for a specific physical register, like {r17}, 8765 // assign it now. 8766 8767 // If this associated to a specific register, initialize iterator to correct 8768 // place. If virtual, make sure we have enough registers 8769 8770 // Initialize iterator if necessary 8771 TargetRegisterClass::iterator I = RC->begin(); 8772 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8773 8774 // Do not check for single registers. 8775 if (AssignedReg) { 8776 I = std::find(I, RC->end(), AssignedReg); 8777 if (I == RC->end()) { 8778 // RC does not contain the selected register, which indicates a 8779 // mismatch between the register and the required type/bitwidth. 8780 return {AssignedReg}; 8781 } 8782 } 8783 8784 for (; NumRegs; --NumRegs, ++I) { 8785 assert(I != RC->end() && "Ran out of registers to allocate!"); 8786 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8787 Regs.push_back(R); 8788 } 8789 8790 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8791 return std::nullopt; 8792 } 8793 8794 static unsigned 8795 findMatchingInlineAsmOperand(unsigned OperandNo, 8796 const std::vector<SDValue> &AsmNodeOperands) { 8797 // Scan until we find the definition we already emitted of this operand. 8798 unsigned CurOp = InlineAsm::Op_FirstOperand; 8799 for (; OperandNo; --OperandNo) { 8800 // Advance to the next operand. 8801 unsigned OpFlag = 8802 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8803 assert((InlineAsm::isRegDefKind(OpFlag) || 8804 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8805 InlineAsm::isMemKind(OpFlag)) && 8806 "Skipped past definitions?"); 8807 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8808 } 8809 return CurOp; 8810 } 8811 8812 namespace { 8813 8814 class ExtraFlags { 8815 unsigned Flags = 0; 8816 8817 public: 8818 explicit ExtraFlags(const CallBase &Call) { 8819 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8820 if (IA->hasSideEffects()) 8821 Flags |= InlineAsm::Extra_HasSideEffects; 8822 if (IA->isAlignStack()) 8823 Flags |= InlineAsm::Extra_IsAlignStack; 8824 if (Call.isConvergent()) 8825 Flags |= InlineAsm::Extra_IsConvergent; 8826 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8827 } 8828 8829 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8830 // Ideally, we would only check against memory constraints. However, the 8831 // meaning of an Other constraint can be target-specific and we can't easily 8832 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8833 // for Other constraints as well. 8834 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8835 OpInfo.ConstraintType == TargetLowering::C_Other) { 8836 if (OpInfo.Type == InlineAsm::isInput) 8837 Flags |= InlineAsm::Extra_MayLoad; 8838 else if (OpInfo.Type == InlineAsm::isOutput) 8839 Flags |= InlineAsm::Extra_MayStore; 8840 else if (OpInfo.Type == InlineAsm::isClobber) 8841 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8842 } 8843 } 8844 8845 unsigned get() const { return Flags; } 8846 }; 8847 8848 } // end anonymous namespace 8849 8850 static bool isFunction(SDValue Op) { 8851 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8852 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8853 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8854 8855 // In normal "call dllimport func" instruction (non-inlineasm) it force 8856 // indirect access by specifing call opcode. And usually specially print 8857 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8858 // not do in this way now. (In fact, this is similar with "Data Access" 8859 // action). So here we ignore dllimport function. 8860 if (Fn && !Fn->hasDLLImportStorageClass()) 8861 return true; 8862 } 8863 } 8864 return false; 8865 } 8866 8867 /// visitInlineAsm - Handle a call to an InlineAsm object. 8868 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8869 const BasicBlock *EHPadBB) { 8870 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8871 8872 /// ConstraintOperands - Information about all of the constraints. 8873 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8874 8875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8876 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8877 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8878 8879 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8880 // AsmDialect, MayLoad, MayStore). 8881 bool HasSideEffect = IA->hasSideEffects(); 8882 ExtraFlags ExtraInfo(Call); 8883 8884 for (auto &T : TargetConstraints) { 8885 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8886 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8887 8888 if (OpInfo.CallOperandVal) 8889 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8890 8891 if (!HasSideEffect) 8892 HasSideEffect = OpInfo.hasMemory(TLI); 8893 8894 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8895 // FIXME: Could we compute this on OpInfo rather than T? 8896 8897 // Compute the constraint code and ConstraintType to use. 8898 TLI.ComputeConstraintToUse(T, SDValue()); 8899 8900 if (T.ConstraintType == TargetLowering::C_Immediate && 8901 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8902 // We've delayed emitting a diagnostic like the "n" constraint because 8903 // inlining could cause an integer showing up. 8904 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8905 "' expects an integer constant " 8906 "expression"); 8907 8908 ExtraInfo.update(T); 8909 } 8910 8911 // We won't need to flush pending loads if this asm doesn't touch 8912 // memory and is nonvolatile. 8913 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8914 8915 bool EmitEHLabels = isa<InvokeInst>(Call); 8916 if (EmitEHLabels) { 8917 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8918 } 8919 bool IsCallBr = isa<CallBrInst>(Call); 8920 8921 if (IsCallBr || EmitEHLabels) { 8922 // If this is a callbr or invoke we need to flush pending exports since 8923 // inlineasm_br and invoke are terminators. 8924 // We need to do this before nodes are glued to the inlineasm_br node. 8925 Chain = getControlRoot(); 8926 } 8927 8928 MCSymbol *BeginLabel = nullptr; 8929 if (EmitEHLabels) { 8930 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8931 } 8932 8933 int OpNo = -1; 8934 SmallVector<StringRef> AsmStrs; 8935 IA->collectAsmStrs(AsmStrs); 8936 8937 // Second pass over the constraints: compute which constraint option to use. 8938 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8939 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8940 OpNo++; 8941 8942 // If this is an output operand with a matching input operand, look up the 8943 // matching input. If their types mismatch, e.g. one is an integer, the 8944 // other is floating point, or their sizes are different, flag it as an 8945 // error. 8946 if (OpInfo.hasMatchingInput()) { 8947 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8948 patchMatchingInput(OpInfo, Input, DAG); 8949 } 8950 8951 // Compute the constraint code and ConstraintType to use. 8952 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8953 8954 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8955 OpInfo.Type == InlineAsm::isClobber) || 8956 OpInfo.ConstraintType == TargetLowering::C_Address) 8957 continue; 8958 8959 // In Linux PIC model, there are 4 cases about value/label addressing: 8960 // 8961 // 1: Function call or Label jmp inside the module. 8962 // 2: Data access (such as global variable, static variable) inside module. 8963 // 3: Function call or Label jmp outside the module. 8964 // 4: Data access (such as global variable) outside the module. 8965 // 8966 // Due to current llvm inline asm architecture designed to not "recognize" 8967 // the asm code, there are quite troubles for us to treat mem addressing 8968 // differently for same value/adress used in different instuctions. 8969 // For example, in pic model, call a func may in plt way or direclty 8970 // pc-related, but lea/mov a function adress may use got. 8971 // 8972 // Here we try to "recognize" function call for the case 1 and case 3 in 8973 // inline asm. And try to adjust the constraint for them. 8974 // 8975 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8976 // label, so here we don't handle jmp function label now, but we need to 8977 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8978 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8979 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8980 TM.getCodeModel() != CodeModel::Large) { 8981 OpInfo.isIndirect = false; 8982 OpInfo.ConstraintType = TargetLowering::C_Address; 8983 } 8984 8985 // If this is a memory input, and if the operand is not indirect, do what we 8986 // need to provide an address for the memory input. 8987 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8988 !OpInfo.isIndirect) { 8989 assert((OpInfo.isMultipleAlternative || 8990 (OpInfo.Type == InlineAsm::isInput)) && 8991 "Can only indirectify direct input operands!"); 8992 8993 // Memory operands really want the address of the value. 8994 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8995 8996 // There is no longer a Value* corresponding to this operand. 8997 OpInfo.CallOperandVal = nullptr; 8998 8999 // It is now an indirect operand. 9000 OpInfo.isIndirect = true; 9001 } 9002 9003 } 9004 9005 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9006 std::vector<SDValue> AsmNodeOperands; 9007 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9008 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9009 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9010 9011 // If we have a !srcloc metadata node associated with it, we want to attach 9012 // this to the ultimately generated inline asm machineinstr. To do this, we 9013 // pass in the third operand as this (potentially null) inline asm MDNode. 9014 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9015 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9016 9017 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9018 // bits as operand 3. 9019 AsmNodeOperands.push_back(DAG.getTargetConstant( 9020 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9021 9022 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9023 // this, assign virtual and physical registers for inputs and otput. 9024 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9025 // Assign Registers. 9026 SDISelAsmOperandInfo &RefOpInfo = 9027 OpInfo.isMatchingInputConstraint() 9028 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9029 : OpInfo; 9030 const auto RegError = 9031 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9032 if (RegError) { 9033 const MachineFunction &MF = DAG.getMachineFunction(); 9034 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9035 const char *RegName = TRI.getName(*RegError); 9036 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9037 "' allocated for constraint '" + 9038 Twine(OpInfo.ConstraintCode) + 9039 "' does not match required type"); 9040 return; 9041 } 9042 9043 auto DetectWriteToReservedRegister = [&]() { 9044 const MachineFunction &MF = DAG.getMachineFunction(); 9045 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9046 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9047 if (Register::isPhysicalRegister(Reg) && 9048 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9049 const char *RegName = TRI.getName(Reg); 9050 emitInlineAsmError(Call, "write to reserved register '" + 9051 Twine(RegName) + "'"); 9052 return true; 9053 } 9054 } 9055 return false; 9056 }; 9057 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9058 (OpInfo.Type == InlineAsm::isInput && 9059 !OpInfo.isMatchingInputConstraint())) && 9060 "Only address as input operand is allowed."); 9061 9062 switch (OpInfo.Type) { 9063 case InlineAsm::isOutput: 9064 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9065 unsigned ConstraintID = 9066 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9067 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9068 "Failed to convert memory constraint code to constraint id."); 9069 9070 // Add information to the INLINEASM node to know about this output. 9071 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9072 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9073 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9074 MVT::i32)); 9075 AsmNodeOperands.push_back(OpInfo.CallOperand); 9076 } else { 9077 // Otherwise, this outputs to a register (directly for C_Register / 9078 // C_RegisterClass, and a target-defined fashion for 9079 // C_Immediate/C_Other). Find a register that we can use. 9080 if (OpInfo.AssignedRegs.Regs.empty()) { 9081 emitInlineAsmError( 9082 Call, "couldn't allocate output register for constraint '" + 9083 Twine(OpInfo.ConstraintCode) + "'"); 9084 return; 9085 } 9086 9087 if (DetectWriteToReservedRegister()) 9088 return; 9089 9090 // Add information to the INLINEASM node to know that this register is 9091 // set. 9092 OpInfo.AssignedRegs.AddInlineAsmOperands( 9093 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9094 : InlineAsm::Kind_RegDef, 9095 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9096 } 9097 break; 9098 9099 case InlineAsm::isInput: 9100 case InlineAsm::isLabel: { 9101 SDValue InOperandVal = OpInfo.CallOperand; 9102 9103 if (OpInfo.isMatchingInputConstraint()) { 9104 // If this is required to match an output register we have already set, 9105 // just use its register. 9106 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9107 AsmNodeOperands); 9108 unsigned OpFlag = 9109 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9110 if (InlineAsm::isRegDefKind(OpFlag) || 9111 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9112 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9113 if (OpInfo.isIndirect) { 9114 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9115 emitInlineAsmError(Call, "inline asm not supported yet: " 9116 "don't know how to handle tied " 9117 "indirect register inputs"); 9118 return; 9119 } 9120 9121 SmallVector<unsigned, 4> Regs; 9122 MachineFunction &MF = DAG.getMachineFunction(); 9123 MachineRegisterInfo &MRI = MF.getRegInfo(); 9124 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9125 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9126 Register TiedReg = R->getReg(); 9127 MVT RegVT = R->getSimpleValueType(0); 9128 const TargetRegisterClass *RC = 9129 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9130 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9131 : TRI.getMinimalPhysRegClass(TiedReg); 9132 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9133 for (unsigned i = 0; i != NumRegs; ++i) 9134 Regs.push_back(MRI.createVirtualRegister(RC)); 9135 9136 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9137 9138 SDLoc dl = getCurSDLoc(); 9139 // Use the produced MatchedRegs object to 9140 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9141 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9142 true, OpInfo.getMatchedOperand(), dl, 9143 DAG, AsmNodeOperands); 9144 break; 9145 } 9146 9147 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9148 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9149 "Unexpected number of operands"); 9150 // Add information to the INLINEASM node to know about this input. 9151 // See InlineAsm.h isUseOperandTiedToDef. 9152 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9153 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9154 OpInfo.getMatchedOperand()); 9155 AsmNodeOperands.push_back(DAG.getTargetConstant( 9156 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9157 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9158 break; 9159 } 9160 9161 // Treat indirect 'X' constraint as memory. 9162 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9163 OpInfo.isIndirect) 9164 OpInfo.ConstraintType = TargetLowering::C_Memory; 9165 9166 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9167 OpInfo.ConstraintType == TargetLowering::C_Other) { 9168 std::vector<SDValue> Ops; 9169 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9170 Ops, DAG); 9171 if (Ops.empty()) { 9172 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9173 if (isa<ConstantSDNode>(InOperandVal)) { 9174 emitInlineAsmError(Call, "value out of range for constraint '" + 9175 Twine(OpInfo.ConstraintCode) + "'"); 9176 return; 9177 } 9178 9179 emitInlineAsmError(Call, 9180 "invalid operand for inline asm constraint '" + 9181 Twine(OpInfo.ConstraintCode) + "'"); 9182 return; 9183 } 9184 9185 // Add information to the INLINEASM node to know about this input. 9186 unsigned ResOpType = 9187 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9188 AsmNodeOperands.push_back(DAG.getTargetConstant( 9189 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9190 llvm::append_range(AsmNodeOperands, Ops); 9191 break; 9192 } 9193 9194 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9195 assert((OpInfo.isIndirect || 9196 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9197 "Operand must be indirect to be a mem!"); 9198 assert(InOperandVal.getValueType() == 9199 TLI.getPointerTy(DAG.getDataLayout()) && 9200 "Memory operands expect pointer values"); 9201 9202 unsigned ConstraintID = 9203 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9204 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9205 "Failed to convert memory constraint code to constraint id."); 9206 9207 // Add information to the INLINEASM node to know about this input. 9208 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9209 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9210 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9211 getCurSDLoc(), 9212 MVT::i32)); 9213 AsmNodeOperands.push_back(InOperandVal); 9214 break; 9215 } 9216 9217 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9218 assert(InOperandVal.getValueType() == 9219 TLI.getPointerTy(DAG.getDataLayout()) && 9220 "Address operands expect pointer values"); 9221 9222 unsigned ConstraintID = 9223 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9224 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9225 "Failed to convert memory constraint code to constraint id."); 9226 9227 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9228 9229 SDValue AsmOp = InOperandVal; 9230 if (isFunction(InOperandVal)) { 9231 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9232 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9233 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9234 InOperandVal.getValueType(), 9235 GA->getOffset()); 9236 } 9237 9238 // Add information to the INLINEASM node to know about this input. 9239 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9240 9241 AsmNodeOperands.push_back( 9242 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9243 9244 AsmNodeOperands.push_back(AsmOp); 9245 break; 9246 } 9247 9248 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9249 OpInfo.ConstraintType == TargetLowering::C_Register) && 9250 "Unknown constraint type!"); 9251 9252 // TODO: Support this. 9253 if (OpInfo.isIndirect) { 9254 emitInlineAsmError( 9255 Call, "Don't know how to handle indirect register inputs yet " 9256 "for constraint '" + 9257 Twine(OpInfo.ConstraintCode) + "'"); 9258 return; 9259 } 9260 9261 // Copy the input into the appropriate registers. 9262 if (OpInfo.AssignedRegs.Regs.empty()) { 9263 emitInlineAsmError(Call, 9264 "couldn't allocate input reg for constraint '" + 9265 Twine(OpInfo.ConstraintCode) + "'"); 9266 return; 9267 } 9268 9269 if (DetectWriteToReservedRegister()) 9270 return; 9271 9272 SDLoc dl = getCurSDLoc(); 9273 9274 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9275 &Call); 9276 9277 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9278 dl, DAG, AsmNodeOperands); 9279 break; 9280 } 9281 case InlineAsm::isClobber: 9282 // Add the clobbered value to the operand list, so that the register 9283 // allocator is aware that the physreg got clobbered. 9284 if (!OpInfo.AssignedRegs.Regs.empty()) 9285 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9286 false, 0, getCurSDLoc(), DAG, 9287 AsmNodeOperands); 9288 break; 9289 } 9290 } 9291 9292 // Finish up input operands. Set the input chain and add the flag last. 9293 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9294 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9295 9296 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9297 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9298 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9299 Flag = Chain.getValue(1); 9300 9301 // Do additional work to generate outputs. 9302 9303 SmallVector<EVT, 1> ResultVTs; 9304 SmallVector<SDValue, 1> ResultValues; 9305 SmallVector<SDValue, 8> OutChains; 9306 9307 llvm::Type *CallResultType = Call.getType(); 9308 ArrayRef<Type *> ResultTypes; 9309 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9310 ResultTypes = StructResult->elements(); 9311 else if (!CallResultType->isVoidTy()) 9312 ResultTypes = ArrayRef(CallResultType); 9313 9314 auto CurResultType = ResultTypes.begin(); 9315 auto handleRegAssign = [&](SDValue V) { 9316 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9317 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9318 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9319 ++CurResultType; 9320 // If the type of the inline asm call site return value is different but has 9321 // same size as the type of the asm output bitcast it. One example of this 9322 // is for vectors with different width / number of elements. This can 9323 // happen for register classes that can contain multiple different value 9324 // types. The preg or vreg allocated may not have the same VT as was 9325 // expected. 9326 // 9327 // This can also happen for a return value that disagrees with the register 9328 // class it is put in, eg. a double in a general-purpose register on a 9329 // 32-bit machine. 9330 if (ResultVT != V.getValueType() && 9331 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9332 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9333 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9334 V.getValueType().isInteger()) { 9335 // If a result value was tied to an input value, the computed result 9336 // may have a wider width than the expected result. Extract the 9337 // relevant portion. 9338 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9339 } 9340 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9341 ResultVTs.push_back(ResultVT); 9342 ResultValues.push_back(V); 9343 }; 9344 9345 // Deal with output operands. 9346 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9347 if (OpInfo.Type == InlineAsm::isOutput) { 9348 SDValue Val; 9349 // Skip trivial output operands. 9350 if (OpInfo.AssignedRegs.Regs.empty()) 9351 continue; 9352 9353 switch (OpInfo.ConstraintType) { 9354 case TargetLowering::C_Register: 9355 case TargetLowering::C_RegisterClass: 9356 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9357 Chain, &Flag, &Call); 9358 break; 9359 case TargetLowering::C_Immediate: 9360 case TargetLowering::C_Other: 9361 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9362 OpInfo, DAG); 9363 break; 9364 case TargetLowering::C_Memory: 9365 break; // Already handled. 9366 case TargetLowering::C_Address: 9367 break; // Silence warning. 9368 case TargetLowering::C_Unknown: 9369 assert(false && "Unexpected unknown constraint"); 9370 } 9371 9372 // Indirect output manifest as stores. Record output chains. 9373 if (OpInfo.isIndirect) { 9374 const Value *Ptr = OpInfo.CallOperandVal; 9375 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9376 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9377 MachinePointerInfo(Ptr)); 9378 OutChains.push_back(Store); 9379 } else { 9380 // generate CopyFromRegs to associated registers. 9381 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9382 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9383 for (const SDValue &V : Val->op_values()) 9384 handleRegAssign(V); 9385 } else 9386 handleRegAssign(Val); 9387 } 9388 } 9389 } 9390 9391 // Set results. 9392 if (!ResultValues.empty()) { 9393 assert(CurResultType == ResultTypes.end() && 9394 "Mismatch in number of ResultTypes"); 9395 assert(ResultValues.size() == ResultTypes.size() && 9396 "Mismatch in number of output operands in asm result"); 9397 9398 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9399 DAG.getVTList(ResultVTs), ResultValues); 9400 setValue(&Call, V); 9401 } 9402 9403 // Collect store chains. 9404 if (!OutChains.empty()) 9405 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9406 9407 if (EmitEHLabels) { 9408 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9409 } 9410 9411 // Only Update Root if inline assembly has a memory effect. 9412 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9413 EmitEHLabels) 9414 DAG.setRoot(Chain); 9415 } 9416 9417 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9418 const Twine &Message) { 9419 LLVMContext &Ctx = *DAG.getContext(); 9420 Ctx.emitError(&Call, Message); 9421 9422 // Make sure we leave the DAG in a valid state 9423 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9424 SmallVector<EVT, 1> ValueVTs; 9425 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9426 9427 if (ValueVTs.empty()) 9428 return; 9429 9430 SmallVector<SDValue, 1> Ops; 9431 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9432 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9433 9434 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9435 } 9436 9437 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9438 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9439 MVT::Other, getRoot(), 9440 getValue(I.getArgOperand(0)), 9441 DAG.getSrcValue(I.getArgOperand(0)))); 9442 } 9443 9444 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9445 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9446 const DataLayout &DL = DAG.getDataLayout(); 9447 SDValue V = DAG.getVAArg( 9448 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9449 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9450 DL.getABITypeAlign(I.getType()).value()); 9451 DAG.setRoot(V.getValue(1)); 9452 9453 if (I.getType()->isPointerTy()) 9454 V = DAG.getPtrExtOrTrunc( 9455 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9456 setValue(&I, V); 9457 } 9458 9459 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9460 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9461 MVT::Other, getRoot(), 9462 getValue(I.getArgOperand(0)), 9463 DAG.getSrcValue(I.getArgOperand(0)))); 9464 } 9465 9466 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9467 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9468 MVT::Other, getRoot(), 9469 getValue(I.getArgOperand(0)), 9470 getValue(I.getArgOperand(1)), 9471 DAG.getSrcValue(I.getArgOperand(0)), 9472 DAG.getSrcValue(I.getArgOperand(1)))); 9473 } 9474 9475 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9476 const Instruction &I, 9477 SDValue Op) { 9478 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9479 if (!Range) 9480 return Op; 9481 9482 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9483 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9484 return Op; 9485 9486 APInt Lo = CR.getUnsignedMin(); 9487 if (!Lo.isMinValue()) 9488 return Op; 9489 9490 APInt Hi = CR.getUnsignedMax(); 9491 unsigned Bits = std::max(Hi.getActiveBits(), 9492 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9493 9494 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9495 9496 SDLoc SL = getCurSDLoc(); 9497 9498 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9499 DAG.getValueType(SmallVT)); 9500 unsigned NumVals = Op.getNode()->getNumValues(); 9501 if (NumVals == 1) 9502 return ZExt; 9503 9504 SmallVector<SDValue, 4> Ops; 9505 9506 Ops.push_back(ZExt); 9507 for (unsigned I = 1; I != NumVals; ++I) 9508 Ops.push_back(Op.getValue(I)); 9509 9510 return DAG.getMergeValues(Ops, SL); 9511 } 9512 9513 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9514 /// the call being lowered. 9515 /// 9516 /// This is a helper for lowering intrinsics that follow a target calling 9517 /// convention or require stack pointer adjustment. Only a subset of the 9518 /// intrinsic's operands need to participate in the calling convention. 9519 void SelectionDAGBuilder::populateCallLoweringInfo( 9520 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9521 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9522 bool IsPatchPoint) { 9523 TargetLowering::ArgListTy Args; 9524 Args.reserve(NumArgs); 9525 9526 // Populate the argument list. 9527 // Attributes for args start at offset 1, after the return attribute. 9528 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9529 ArgI != ArgE; ++ArgI) { 9530 const Value *V = Call->getOperand(ArgI); 9531 9532 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9533 9534 TargetLowering::ArgListEntry Entry; 9535 Entry.Node = getValue(V); 9536 Entry.Ty = V->getType(); 9537 Entry.setAttributes(Call, ArgI); 9538 Args.push_back(Entry); 9539 } 9540 9541 CLI.setDebugLoc(getCurSDLoc()) 9542 .setChain(getRoot()) 9543 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9544 .setDiscardResult(Call->use_empty()) 9545 .setIsPatchPoint(IsPatchPoint) 9546 .setIsPreallocated( 9547 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9548 } 9549 9550 /// Add a stack map intrinsic call's live variable operands to a stackmap 9551 /// or patchpoint target node's operand list. 9552 /// 9553 /// Constants are converted to TargetConstants purely as an optimization to 9554 /// avoid constant materialization and register allocation. 9555 /// 9556 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9557 /// generate addess computation nodes, and so FinalizeISel can convert the 9558 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9559 /// address materialization and register allocation, but may also be required 9560 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9561 /// alloca in the entry block, then the runtime may assume that the alloca's 9562 /// StackMap location can be read immediately after compilation and that the 9563 /// location is valid at any point during execution (this is similar to the 9564 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9565 /// only available in a register, then the runtime would need to trap when 9566 /// execution reaches the StackMap in order to read the alloca's location. 9567 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9568 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9569 SelectionDAGBuilder &Builder) { 9570 SelectionDAG &DAG = Builder.DAG; 9571 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9572 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9573 9574 // Things on the stack are pointer-typed, meaning that they are already 9575 // legal and can be emitted directly to target nodes. 9576 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9577 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9578 } else { 9579 // Otherwise emit a target independent node to be legalised. 9580 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9581 } 9582 } 9583 } 9584 9585 /// Lower llvm.experimental.stackmap. 9586 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9587 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9588 // [live variables...]) 9589 9590 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9591 9592 SDValue Chain, InFlag, Callee; 9593 SmallVector<SDValue, 32> Ops; 9594 9595 SDLoc DL = getCurSDLoc(); 9596 Callee = getValue(CI.getCalledOperand()); 9597 9598 // The stackmap intrinsic only records the live variables (the arguments 9599 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9600 // intrinsic, this won't be lowered to a function call. This means we don't 9601 // have to worry about calling conventions and target specific lowering code. 9602 // Instead we perform the call lowering right here. 9603 // 9604 // chain, flag = CALLSEQ_START(chain, 0, 0) 9605 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9606 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9607 // 9608 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9609 InFlag = Chain.getValue(1); 9610 9611 // Add the STACKMAP operands, starting with DAG house-keeping. 9612 Ops.push_back(Chain); 9613 Ops.push_back(InFlag); 9614 9615 // Add the <id>, <numShadowBytes> operands. 9616 // 9617 // These do not require legalisation, and can be emitted directly to target 9618 // constant nodes. 9619 SDValue ID = getValue(CI.getArgOperand(0)); 9620 assert(ID.getValueType() == MVT::i64); 9621 SDValue IDConst = DAG.getTargetConstant( 9622 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9623 Ops.push_back(IDConst); 9624 9625 SDValue Shad = getValue(CI.getArgOperand(1)); 9626 assert(Shad.getValueType() == MVT::i32); 9627 SDValue ShadConst = DAG.getTargetConstant( 9628 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9629 Ops.push_back(ShadConst); 9630 9631 // Add the live variables. 9632 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9633 9634 // Create the STACKMAP node. 9635 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9636 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9637 InFlag = Chain.getValue(1); 9638 9639 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9640 9641 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9642 9643 // Set the root to the target-lowered call chain. 9644 DAG.setRoot(Chain); 9645 9646 // Inform the Frame Information that we have a stackmap in this function. 9647 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9648 } 9649 9650 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9651 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9652 const BasicBlock *EHPadBB) { 9653 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9654 // i32 <numBytes>, 9655 // i8* <target>, 9656 // i32 <numArgs>, 9657 // [Args...], 9658 // [live variables...]) 9659 9660 CallingConv::ID CC = CB.getCallingConv(); 9661 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9662 bool HasDef = !CB.getType()->isVoidTy(); 9663 SDLoc dl = getCurSDLoc(); 9664 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9665 9666 // Handle immediate and symbolic callees. 9667 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9668 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9669 /*isTarget=*/true); 9670 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9671 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9672 SDLoc(SymbolicCallee), 9673 SymbolicCallee->getValueType(0)); 9674 9675 // Get the real number of arguments participating in the call <numArgs> 9676 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9677 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9678 9679 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9680 // Intrinsics include all meta-operands up to but not including CC. 9681 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9682 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9683 "Not enough arguments provided to the patchpoint intrinsic"); 9684 9685 // For AnyRegCC the arguments are lowered later on manually. 9686 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9687 Type *ReturnTy = 9688 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9689 9690 TargetLowering::CallLoweringInfo CLI(DAG); 9691 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9692 ReturnTy, true); 9693 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9694 9695 SDNode *CallEnd = Result.second.getNode(); 9696 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9697 CallEnd = CallEnd->getOperand(0).getNode(); 9698 9699 /// Get a call instruction from the call sequence chain. 9700 /// Tail calls are not allowed. 9701 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9702 "Expected a callseq node."); 9703 SDNode *Call = CallEnd->getOperand(0).getNode(); 9704 bool HasGlue = Call->getGluedNode(); 9705 9706 // Replace the target specific call node with the patchable intrinsic. 9707 SmallVector<SDValue, 8> Ops; 9708 9709 // Push the chain. 9710 Ops.push_back(*(Call->op_begin())); 9711 9712 // Optionally, push the glue (if any). 9713 if (HasGlue) 9714 Ops.push_back(*(Call->op_end() - 1)); 9715 9716 // Push the register mask info. 9717 if (HasGlue) 9718 Ops.push_back(*(Call->op_end() - 2)); 9719 else 9720 Ops.push_back(*(Call->op_end() - 1)); 9721 9722 // Add the <id> and <numBytes> constants. 9723 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9724 Ops.push_back(DAG.getTargetConstant( 9725 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9726 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9727 Ops.push_back(DAG.getTargetConstant( 9728 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9729 MVT::i32)); 9730 9731 // Add the callee. 9732 Ops.push_back(Callee); 9733 9734 // Adjust <numArgs> to account for any arguments that have been passed on the 9735 // stack instead. 9736 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9737 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9738 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9739 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9740 9741 // Add the calling convention 9742 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9743 9744 // Add the arguments we omitted previously. The register allocator should 9745 // place these in any free register. 9746 if (IsAnyRegCC) 9747 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9748 Ops.push_back(getValue(CB.getArgOperand(i))); 9749 9750 // Push the arguments from the call instruction. 9751 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9752 Ops.append(Call->op_begin() + 2, e); 9753 9754 // Push live variables for the stack map. 9755 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9756 9757 SDVTList NodeTys; 9758 if (IsAnyRegCC && HasDef) { 9759 // Create the return types based on the intrinsic definition 9760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9761 SmallVector<EVT, 3> ValueVTs; 9762 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9763 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9764 9765 // There is always a chain and a glue type at the end 9766 ValueVTs.push_back(MVT::Other); 9767 ValueVTs.push_back(MVT::Glue); 9768 NodeTys = DAG.getVTList(ValueVTs); 9769 } else 9770 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9771 9772 // Replace the target specific call node with a PATCHPOINT node. 9773 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9774 9775 // Update the NodeMap. 9776 if (HasDef) { 9777 if (IsAnyRegCC) 9778 setValue(&CB, SDValue(PPV.getNode(), 0)); 9779 else 9780 setValue(&CB, Result.first); 9781 } 9782 9783 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9784 // call sequence. Furthermore the location of the chain and glue can change 9785 // when the AnyReg calling convention is used and the intrinsic returns a 9786 // value. 9787 if (IsAnyRegCC && HasDef) { 9788 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9789 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9790 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9791 } else 9792 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9793 DAG.DeleteNode(Call); 9794 9795 // Inform the Frame Information that we have a patchpoint in this function. 9796 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9797 } 9798 9799 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9800 unsigned Intrinsic) { 9801 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9802 SDValue Op1 = getValue(I.getArgOperand(0)); 9803 SDValue Op2; 9804 if (I.arg_size() > 1) 9805 Op2 = getValue(I.getArgOperand(1)); 9806 SDLoc dl = getCurSDLoc(); 9807 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9808 SDValue Res; 9809 SDNodeFlags SDFlags; 9810 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9811 SDFlags.copyFMF(*FPMO); 9812 9813 switch (Intrinsic) { 9814 case Intrinsic::vector_reduce_fadd: 9815 if (SDFlags.hasAllowReassociation()) 9816 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9817 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9818 SDFlags); 9819 else 9820 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9821 break; 9822 case Intrinsic::vector_reduce_fmul: 9823 if (SDFlags.hasAllowReassociation()) 9824 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9825 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9826 SDFlags); 9827 else 9828 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9829 break; 9830 case Intrinsic::vector_reduce_add: 9831 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9832 break; 9833 case Intrinsic::vector_reduce_mul: 9834 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9835 break; 9836 case Intrinsic::vector_reduce_and: 9837 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9838 break; 9839 case Intrinsic::vector_reduce_or: 9840 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9841 break; 9842 case Intrinsic::vector_reduce_xor: 9843 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9844 break; 9845 case Intrinsic::vector_reduce_smax: 9846 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9847 break; 9848 case Intrinsic::vector_reduce_smin: 9849 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9850 break; 9851 case Intrinsic::vector_reduce_umax: 9852 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9853 break; 9854 case Intrinsic::vector_reduce_umin: 9855 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9856 break; 9857 case Intrinsic::vector_reduce_fmax: 9858 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9859 break; 9860 case Intrinsic::vector_reduce_fmin: 9861 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9862 break; 9863 default: 9864 llvm_unreachable("Unhandled vector reduce intrinsic"); 9865 } 9866 setValue(&I, Res); 9867 } 9868 9869 /// Returns an AttributeList representing the attributes applied to the return 9870 /// value of the given call. 9871 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9872 SmallVector<Attribute::AttrKind, 2> Attrs; 9873 if (CLI.RetSExt) 9874 Attrs.push_back(Attribute::SExt); 9875 if (CLI.RetZExt) 9876 Attrs.push_back(Attribute::ZExt); 9877 if (CLI.IsInReg) 9878 Attrs.push_back(Attribute::InReg); 9879 9880 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9881 Attrs); 9882 } 9883 9884 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9885 /// implementation, which just calls LowerCall. 9886 /// FIXME: When all targets are 9887 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9888 std::pair<SDValue, SDValue> 9889 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9890 // Handle the incoming return values from the call. 9891 CLI.Ins.clear(); 9892 Type *OrigRetTy = CLI.RetTy; 9893 SmallVector<EVT, 4> RetTys; 9894 SmallVector<uint64_t, 4> Offsets; 9895 auto &DL = CLI.DAG.getDataLayout(); 9896 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9897 9898 if (CLI.IsPostTypeLegalization) { 9899 // If we are lowering a libcall after legalization, split the return type. 9900 SmallVector<EVT, 4> OldRetTys; 9901 SmallVector<uint64_t, 4> OldOffsets; 9902 RetTys.swap(OldRetTys); 9903 Offsets.swap(OldOffsets); 9904 9905 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9906 EVT RetVT = OldRetTys[i]; 9907 uint64_t Offset = OldOffsets[i]; 9908 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9909 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9910 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9911 RetTys.append(NumRegs, RegisterVT); 9912 for (unsigned j = 0; j != NumRegs; ++j) 9913 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9914 } 9915 } 9916 9917 SmallVector<ISD::OutputArg, 4> Outs; 9918 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9919 9920 bool CanLowerReturn = 9921 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9922 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9923 9924 SDValue DemoteStackSlot; 9925 int DemoteStackIdx = -100; 9926 if (!CanLowerReturn) { 9927 // FIXME: equivalent assert? 9928 // assert(!CS.hasInAllocaArgument() && 9929 // "sret demotion is incompatible with inalloca"); 9930 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9931 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9932 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9933 DemoteStackIdx = 9934 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9935 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9936 DL.getAllocaAddrSpace()); 9937 9938 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9939 ArgListEntry Entry; 9940 Entry.Node = DemoteStackSlot; 9941 Entry.Ty = StackSlotPtrType; 9942 Entry.IsSExt = false; 9943 Entry.IsZExt = false; 9944 Entry.IsInReg = false; 9945 Entry.IsSRet = true; 9946 Entry.IsNest = false; 9947 Entry.IsByVal = false; 9948 Entry.IsByRef = false; 9949 Entry.IsReturned = false; 9950 Entry.IsSwiftSelf = false; 9951 Entry.IsSwiftAsync = false; 9952 Entry.IsSwiftError = false; 9953 Entry.IsCFGuardTarget = false; 9954 Entry.Alignment = Alignment; 9955 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9956 CLI.NumFixedArgs += 1; 9957 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9958 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9959 9960 // sret demotion isn't compatible with tail-calls, since the sret argument 9961 // points into the callers stack frame. 9962 CLI.IsTailCall = false; 9963 } else { 9964 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9965 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9966 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9967 ISD::ArgFlagsTy Flags; 9968 if (NeedsRegBlock) { 9969 Flags.setInConsecutiveRegs(); 9970 if (I == RetTys.size() - 1) 9971 Flags.setInConsecutiveRegsLast(); 9972 } 9973 EVT VT = RetTys[I]; 9974 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9975 CLI.CallConv, VT); 9976 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9977 CLI.CallConv, VT); 9978 for (unsigned i = 0; i != NumRegs; ++i) { 9979 ISD::InputArg MyFlags; 9980 MyFlags.Flags = Flags; 9981 MyFlags.VT = RegisterVT; 9982 MyFlags.ArgVT = VT; 9983 MyFlags.Used = CLI.IsReturnValueUsed; 9984 if (CLI.RetTy->isPointerTy()) { 9985 MyFlags.Flags.setPointer(); 9986 MyFlags.Flags.setPointerAddrSpace( 9987 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9988 } 9989 if (CLI.RetSExt) 9990 MyFlags.Flags.setSExt(); 9991 if (CLI.RetZExt) 9992 MyFlags.Flags.setZExt(); 9993 if (CLI.IsInReg) 9994 MyFlags.Flags.setInReg(); 9995 CLI.Ins.push_back(MyFlags); 9996 } 9997 } 9998 } 9999 10000 // We push in swifterror return as the last element of CLI.Ins. 10001 ArgListTy &Args = CLI.getArgs(); 10002 if (supportSwiftError()) { 10003 for (const ArgListEntry &Arg : Args) { 10004 if (Arg.IsSwiftError) { 10005 ISD::InputArg MyFlags; 10006 MyFlags.VT = getPointerTy(DL); 10007 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10008 MyFlags.Flags.setSwiftError(); 10009 CLI.Ins.push_back(MyFlags); 10010 } 10011 } 10012 } 10013 10014 // Handle all of the outgoing arguments. 10015 CLI.Outs.clear(); 10016 CLI.OutVals.clear(); 10017 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10018 SmallVector<EVT, 4> ValueVTs; 10019 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10020 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10021 Type *FinalType = Args[i].Ty; 10022 if (Args[i].IsByVal) 10023 FinalType = Args[i].IndirectType; 10024 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10025 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10026 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10027 ++Value) { 10028 EVT VT = ValueVTs[Value]; 10029 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10030 SDValue Op = SDValue(Args[i].Node.getNode(), 10031 Args[i].Node.getResNo() + Value); 10032 ISD::ArgFlagsTy Flags; 10033 10034 // Certain targets (such as MIPS), may have a different ABI alignment 10035 // for a type depending on the context. Give the target a chance to 10036 // specify the alignment it wants. 10037 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10038 Flags.setOrigAlign(OriginalAlignment); 10039 10040 if (Args[i].Ty->isPointerTy()) { 10041 Flags.setPointer(); 10042 Flags.setPointerAddrSpace( 10043 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10044 } 10045 if (Args[i].IsZExt) 10046 Flags.setZExt(); 10047 if (Args[i].IsSExt) 10048 Flags.setSExt(); 10049 if (Args[i].IsInReg) { 10050 // If we are using vectorcall calling convention, a structure that is 10051 // passed InReg - is surely an HVA 10052 if (CLI.CallConv == CallingConv::X86_VectorCall && 10053 isa<StructType>(FinalType)) { 10054 // The first value of a structure is marked 10055 if (0 == Value) 10056 Flags.setHvaStart(); 10057 Flags.setHva(); 10058 } 10059 // Set InReg Flag 10060 Flags.setInReg(); 10061 } 10062 if (Args[i].IsSRet) 10063 Flags.setSRet(); 10064 if (Args[i].IsSwiftSelf) 10065 Flags.setSwiftSelf(); 10066 if (Args[i].IsSwiftAsync) 10067 Flags.setSwiftAsync(); 10068 if (Args[i].IsSwiftError) 10069 Flags.setSwiftError(); 10070 if (Args[i].IsCFGuardTarget) 10071 Flags.setCFGuardTarget(); 10072 if (Args[i].IsByVal) 10073 Flags.setByVal(); 10074 if (Args[i].IsByRef) 10075 Flags.setByRef(); 10076 if (Args[i].IsPreallocated) { 10077 Flags.setPreallocated(); 10078 // Set the byval flag for CCAssignFn callbacks that don't know about 10079 // preallocated. This way we can know how many bytes we should've 10080 // allocated and how many bytes a callee cleanup function will pop. If 10081 // we port preallocated to more targets, we'll have to add custom 10082 // preallocated handling in the various CC lowering callbacks. 10083 Flags.setByVal(); 10084 } 10085 if (Args[i].IsInAlloca) { 10086 Flags.setInAlloca(); 10087 // Set the byval flag for CCAssignFn callbacks that don't know about 10088 // inalloca. This way we can know how many bytes we should've allocated 10089 // and how many bytes a callee cleanup function will pop. If we port 10090 // inalloca to more targets, we'll have to add custom inalloca handling 10091 // in the various CC lowering callbacks. 10092 Flags.setByVal(); 10093 } 10094 Align MemAlign; 10095 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10096 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10097 Flags.setByValSize(FrameSize); 10098 10099 // info is not there but there are cases it cannot get right. 10100 if (auto MA = Args[i].Alignment) 10101 MemAlign = *MA; 10102 else 10103 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10104 } else if (auto MA = Args[i].Alignment) { 10105 MemAlign = *MA; 10106 } else { 10107 MemAlign = OriginalAlignment; 10108 } 10109 Flags.setMemAlign(MemAlign); 10110 if (Args[i].IsNest) 10111 Flags.setNest(); 10112 if (NeedsRegBlock) 10113 Flags.setInConsecutiveRegs(); 10114 10115 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10116 CLI.CallConv, VT); 10117 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10118 CLI.CallConv, VT); 10119 SmallVector<SDValue, 4> Parts(NumParts); 10120 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10121 10122 if (Args[i].IsSExt) 10123 ExtendKind = ISD::SIGN_EXTEND; 10124 else if (Args[i].IsZExt) 10125 ExtendKind = ISD::ZERO_EXTEND; 10126 10127 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10128 // for now. 10129 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10130 CanLowerReturn) { 10131 assert((CLI.RetTy == Args[i].Ty || 10132 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10133 CLI.RetTy->getPointerAddressSpace() == 10134 Args[i].Ty->getPointerAddressSpace())) && 10135 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10136 // Before passing 'returned' to the target lowering code, ensure that 10137 // either the register MVT and the actual EVT are the same size or that 10138 // the return value and argument are extended in the same way; in these 10139 // cases it's safe to pass the argument register value unchanged as the 10140 // return register value (although it's at the target's option whether 10141 // to do so) 10142 // TODO: allow code generation to take advantage of partially preserved 10143 // registers rather than clobbering the entire register when the 10144 // parameter extension method is not compatible with the return 10145 // extension method 10146 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10147 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10148 CLI.RetZExt == Args[i].IsZExt)) 10149 Flags.setReturned(); 10150 } 10151 10152 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10153 CLI.CallConv, ExtendKind); 10154 10155 for (unsigned j = 0; j != NumParts; ++j) { 10156 // if it isn't first piece, alignment must be 1 10157 // For scalable vectors the scalable part is currently handled 10158 // by individual targets, so we just use the known minimum size here. 10159 ISD::OutputArg MyFlags( 10160 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10161 i < CLI.NumFixedArgs, i, 10162 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10163 if (NumParts > 1 && j == 0) 10164 MyFlags.Flags.setSplit(); 10165 else if (j != 0) { 10166 MyFlags.Flags.setOrigAlign(Align(1)); 10167 if (j == NumParts - 1) 10168 MyFlags.Flags.setSplitEnd(); 10169 } 10170 10171 CLI.Outs.push_back(MyFlags); 10172 CLI.OutVals.push_back(Parts[j]); 10173 } 10174 10175 if (NeedsRegBlock && Value == NumValues - 1) 10176 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10177 } 10178 } 10179 10180 SmallVector<SDValue, 4> InVals; 10181 CLI.Chain = LowerCall(CLI, InVals); 10182 10183 // Update CLI.InVals to use outside of this function. 10184 CLI.InVals = InVals; 10185 10186 // Verify that the target's LowerCall behaved as expected. 10187 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10188 "LowerCall didn't return a valid chain!"); 10189 assert((!CLI.IsTailCall || InVals.empty()) && 10190 "LowerCall emitted a return value for a tail call!"); 10191 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10192 "LowerCall didn't emit the correct number of values!"); 10193 10194 // For a tail call, the return value is merely live-out and there aren't 10195 // any nodes in the DAG representing it. Return a special value to 10196 // indicate that a tail call has been emitted and no more Instructions 10197 // should be processed in the current block. 10198 if (CLI.IsTailCall) { 10199 CLI.DAG.setRoot(CLI.Chain); 10200 return std::make_pair(SDValue(), SDValue()); 10201 } 10202 10203 #ifndef NDEBUG 10204 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10205 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10206 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10207 "LowerCall emitted a value with the wrong type!"); 10208 } 10209 #endif 10210 10211 SmallVector<SDValue, 4> ReturnValues; 10212 if (!CanLowerReturn) { 10213 // The instruction result is the result of loading from the 10214 // hidden sret parameter. 10215 SmallVector<EVT, 1> PVTs; 10216 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10217 10218 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10219 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10220 EVT PtrVT = PVTs[0]; 10221 10222 unsigned NumValues = RetTys.size(); 10223 ReturnValues.resize(NumValues); 10224 SmallVector<SDValue, 4> Chains(NumValues); 10225 10226 // An aggregate return value cannot wrap around the address space, so 10227 // offsets to its parts don't wrap either. 10228 SDNodeFlags Flags; 10229 Flags.setNoUnsignedWrap(true); 10230 10231 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10232 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10233 for (unsigned i = 0; i < NumValues; ++i) { 10234 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10235 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10236 PtrVT), Flags); 10237 SDValue L = CLI.DAG.getLoad( 10238 RetTys[i], CLI.DL, CLI.Chain, Add, 10239 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10240 DemoteStackIdx, Offsets[i]), 10241 HiddenSRetAlign); 10242 ReturnValues[i] = L; 10243 Chains[i] = L.getValue(1); 10244 } 10245 10246 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10247 } else { 10248 // Collect the legal value parts into potentially illegal values 10249 // that correspond to the original function's return values. 10250 std::optional<ISD::NodeType> AssertOp; 10251 if (CLI.RetSExt) 10252 AssertOp = ISD::AssertSext; 10253 else if (CLI.RetZExt) 10254 AssertOp = ISD::AssertZext; 10255 unsigned CurReg = 0; 10256 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10257 EVT VT = RetTys[I]; 10258 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10259 CLI.CallConv, VT); 10260 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10261 CLI.CallConv, VT); 10262 10263 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10264 NumRegs, RegisterVT, VT, nullptr, 10265 CLI.CallConv, AssertOp)); 10266 CurReg += NumRegs; 10267 } 10268 10269 // For a function returning void, there is no return value. We can't create 10270 // such a node, so we just return a null return value in that case. In 10271 // that case, nothing will actually look at the value. 10272 if (ReturnValues.empty()) 10273 return std::make_pair(SDValue(), CLI.Chain); 10274 } 10275 10276 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10277 CLI.DAG.getVTList(RetTys), ReturnValues); 10278 return std::make_pair(Res, CLI.Chain); 10279 } 10280 10281 /// Places new result values for the node in Results (their number 10282 /// and types must exactly match those of the original return values of 10283 /// the node), or leaves Results empty, which indicates that the node is not 10284 /// to be custom lowered after all. 10285 void TargetLowering::LowerOperationWrapper(SDNode *N, 10286 SmallVectorImpl<SDValue> &Results, 10287 SelectionDAG &DAG) const { 10288 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10289 10290 if (!Res.getNode()) 10291 return; 10292 10293 // If the original node has one result, take the return value from 10294 // LowerOperation as is. It might not be result number 0. 10295 if (N->getNumValues() == 1) { 10296 Results.push_back(Res); 10297 return; 10298 } 10299 10300 // If the original node has multiple results, then the return node should 10301 // have the same number of results. 10302 assert((N->getNumValues() == Res->getNumValues()) && 10303 "Lowering returned the wrong number of results!"); 10304 10305 // Places new result values base on N result number. 10306 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10307 Results.push_back(Res.getValue(I)); 10308 } 10309 10310 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10311 llvm_unreachable("LowerOperation not implemented for this target!"); 10312 } 10313 10314 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10315 unsigned Reg, 10316 ISD::NodeType ExtendType) { 10317 SDValue Op = getNonRegisterValue(V); 10318 assert((Op.getOpcode() != ISD::CopyFromReg || 10319 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10320 "Copy from a reg to the same reg!"); 10321 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10322 10323 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10324 // If this is an InlineAsm we have to match the registers required, not the 10325 // notional registers required by the type. 10326 10327 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10328 std::nullopt); // This is not an ABI copy. 10329 SDValue Chain = DAG.getEntryNode(); 10330 10331 if (ExtendType == ISD::ANY_EXTEND) { 10332 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10333 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10334 ExtendType = PreferredExtendIt->second; 10335 } 10336 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10337 PendingExports.push_back(Chain); 10338 } 10339 10340 #include "llvm/CodeGen/SelectionDAGISel.h" 10341 10342 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10343 /// entry block, return true. This includes arguments used by switches, since 10344 /// the switch may expand into multiple basic blocks. 10345 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10346 // With FastISel active, we may be splitting blocks, so force creation 10347 // of virtual registers for all non-dead arguments. 10348 if (FastISel) 10349 return A->use_empty(); 10350 10351 const BasicBlock &Entry = A->getParent()->front(); 10352 for (const User *U : A->users()) 10353 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10354 return false; // Use not in entry block. 10355 10356 return true; 10357 } 10358 10359 using ArgCopyElisionMapTy = 10360 DenseMap<const Argument *, 10361 std::pair<const AllocaInst *, const StoreInst *>>; 10362 10363 /// Scan the entry block of the function in FuncInfo for arguments that look 10364 /// like copies into a local alloca. Record any copied arguments in 10365 /// ArgCopyElisionCandidates. 10366 static void 10367 findArgumentCopyElisionCandidates(const DataLayout &DL, 10368 FunctionLoweringInfo *FuncInfo, 10369 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10370 // Record the state of every static alloca used in the entry block. Argument 10371 // allocas are all used in the entry block, so we need approximately as many 10372 // entries as we have arguments. 10373 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10374 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10375 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10376 StaticAllocas.reserve(NumArgs * 2); 10377 10378 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10379 if (!V) 10380 return nullptr; 10381 V = V->stripPointerCasts(); 10382 const auto *AI = dyn_cast<AllocaInst>(V); 10383 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10384 return nullptr; 10385 auto Iter = StaticAllocas.insert({AI, Unknown}); 10386 return &Iter.first->second; 10387 }; 10388 10389 // Look for stores of arguments to static allocas. Look through bitcasts and 10390 // GEPs to handle type coercions, as long as the alloca is fully initialized 10391 // by the store. Any non-store use of an alloca escapes it and any subsequent 10392 // unanalyzed store might write it. 10393 // FIXME: Handle structs initialized with multiple stores. 10394 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10395 // Look for stores, and handle non-store uses conservatively. 10396 const auto *SI = dyn_cast<StoreInst>(&I); 10397 if (!SI) { 10398 // We will look through cast uses, so ignore them completely. 10399 if (I.isCast()) 10400 continue; 10401 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10402 // to allocas. 10403 if (I.isDebugOrPseudoInst()) 10404 continue; 10405 // This is an unknown instruction. Assume it escapes or writes to all 10406 // static alloca operands. 10407 for (const Use &U : I.operands()) { 10408 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10409 *Info = StaticAllocaInfo::Clobbered; 10410 } 10411 continue; 10412 } 10413 10414 // If the stored value is a static alloca, mark it as escaped. 10415 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10416 *Info = StaticAllocaInfo::Clobbered; 10417 10418 // Check if the destination is a static alloca. 10419 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10420 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10421 if (!Info) 10422 continue; 10423 const AllocaInst *AI = cast<AllocaInst>(Dst); 10424 10425 // Skip allocas that have been initialized or clobbered. 10426 if (*Info != StaticAllocaInfo::Unknown) 10427 continue; 10428 10429 // Check if the stored value is an argument, and that this store fully 10430 // initializes the alloca. 10431 // If the argument type has padding bits we can't directly forward a pointer 10432 // as the upper bits may contain garbage. 10433 // Don't elide copies from the same argument twice. 10434 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10435 const auto *Arg = dyn_cast<Argument>(Val); 10436 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10437 Arg->getType()->isEmptyTy() || 10438 DL.getTypeStoreSize(Arg->getType()) != 10439 DL.getTypeAllocSize(AI->getAllocatedType()) || 10440 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10441 ArgCopyElisionCandidates.count(Arg)) { 10442 *Info = StaticAllocaInfo::Clobbered; 10443 continue; 10444 } 10445 10446 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10447 << '\n'); 10448 10449 // Mark this alloca and store for argument copy elision. 10450 *Info = StaticAllocaInfo::Elidable; 10451 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10452 10453 // Stop scanning if we've seen all arguments. This will happen early in -O0 10454 // builds, which is useful, because -O0 builds have large entry blocks and 10455 // many allocas. 10456 if (ArgCopyElisionCandidates.size() == NumArgs) 10457 break; 10458 } 10459 } 10460 10461 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10462 /// ArgVal is a load from a suitable fixed stack object. 10463 static void tryToElideArgumentCopy( 10464 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10465 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10466 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10467 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10468 SDValue ArgVal, bool &ArgHasUses) { 10469 // Check if this is a load from a fixed stack object. 10470 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10471 if (!LNode) 10472 return; 10473 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10474 if (!FINode) 10475 return; 10476 10477 // Check that the fixed stack object is the right size and alignment. 10478 // Look at the alignment that the user wrote on the alloca instead of looking 10479 // at the stack object. 10480 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10481 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10482 const AllocaInst *AI = ArgCopyIter->second.first; 10483 int FixedIndex = FINode->getIndex(); 10484 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10485 int OldIndex = AllocaIndex; 10486 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10487 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10488 LLVM_DEBUG( 10489 dbgs() << " argument copy elision failed due to bad fixed stack " 10490 "object size\n"); 10491 return; 10492 } 10493 Align RequiredAlignment = AI->getAlign(); 10494 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10495 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10496 "greater than stack argument alignment (" 10497 << DebugStr(RequiredAlignment) << " vs " 10498 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10499 return; 10500 } 10501 10502 // Perform the elision. Delete the old stack object and replace its only use 10503 // in the variable info map. Mark the stack object as mutable. 10504 LLVM_DEBUG({ 10505 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10506 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10507 << '\n'; 10508 }); 10509 MFI.RemoveStackObject(OldIndex); 10510 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10511 AllocaIndex = FixedIndex; 10512 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10513 Chains.push_back(ArgVal.getValue(1)); 10514 10515 // Avoid emitting code for the store implementing the copy. 10516 const StoreInst *SI = ArgCopyIter->second.second; 10517 ElidedArgCopyInstrs.insert(SI); 10518 10519 // Check for uses of the argument again so that we can avoid exporting ArgVal 10520 // if it is't used by anything other than the store. 10521 for (const Value *U : Arg.users()) { 10522 if (U != SI) { 10523 ArgHasUses = true; 10524 break; 10525 } 10526 } 10527 } 10528 10529 void SelectionDAGISel::LowerArguments(const Function &F) { 10530 SelectionDAG &DAG = SDB->DAG; 10531 SDLoc dl = SDB->getCurSDLoc(); 10532 const DataLayout &DL = DAG.getDataLayout(); 10533 SmallVector<ISD::InputArg, 16> Ins; 10534 10535 // In Naked functions we aren't going to save any registers. 10536 if (F.hasFnAttribute(Attribute::Naked)) 10537 return; 10538 10539 if (!FuncInfo->CanLowerReturn) { 10540 // Put in an sret pointer parameter before all the other parameters. 10541 SmallVector<EVT, 1> ValueVTs; 10542 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10543 F.getReturnType()->getPointerTo( 10544 DAG.getDataLayout().getAllocaAddrSpace()), 10545 ValueVTs); 10546 10547 // NOTE: Assuming that a pointer will never break down to more than one VT 10548 // or one register. 10549 ISD::ArgFlagsTy Flags; 10550 Flags.setSRet(); 10551 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10552 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10553 ISD::InputArg::NoArgIndex, 0); 10554 Ins.push_back(RetArg); 10555 } 10556 10557 // Look for stores of arguments to static allocas. Mark such arguments with a 10558 // flag to ask the target to give us the memory location of that argument if 10559 // available. 10560 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10561 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10562 ArgCopyElisionCandidates); 10563 10564 // Set up the incoming argument description vector. 10565 for (const Argument &Arg : F.args()) { 10566 unsigned ArgNo = Arg.getArgNo(); 10567 SmallVector<EVT, 4> ValueVTs; 10568 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10569 bool isArgValueUsed = !Arg.use_empty(); 10570 unsigned PartBase = 0; 10571 Type *FinalType = Arg.getType(); 10572 if (Arg.hasAttribute(Attribute::ByVal)) 10573 FinalType = Arg.getParamByValType(); 10574 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10575 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10576 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10577 Value != NumValues; ++Value) { 10578 EVT VT = ValueVTs[Value]; 10579 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10580 ISD::ArgFlagsTy Flags; 10581 10582 10583 if (Arg.getType()->isPointerTy()) { 10584 Flags.setPointer(); 10585 Flags.setPointerAddrSpace( 10586 cast<PointerType>(Arg.getType())->getAddressSpace()); 10587 } 10588 if (Arg.hasAttribute(Attribute::ZExt)) 10589 Flags.setZExt(); 10590 if (Arg.hasAttribute(Attribute::SExt)) 10591 Flags.setSExt(); 10592 if (Arg.hasAttribute(Attribute::InReg)) { 10593 // If we are using vectorcall calling convention, a structure that is 10594 // passed InReg - is surely an HVA 10595 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10596 isa<StructType>(Arg.getType())) { 10597 // The first value of a structure is marked 10598 if (0 == Value) 10599 Flags.setHvaStart(); 10600 Flags.setHva(); 10601 } 10602 // Set InReg Flag 10603 Flags.setInReg(); 10604 } 10605 if (Arg.hasAttribute(Attribute::StructRet)) 10606 Flags.setSRet(); 10607 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10608 Flags.setSwiftSelf(); 10609 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10610 Flags.setSwiftAsync(); 10611 if (Arg.hasAttribute(Attribute::SwiftError)) 10612 Flags.setSwiftError(); 10613 if (Arg.hasAttribute(Attribute::ByVal)) 10614 Flags.setByVal(); 10615 if (Arg.hasAttribute(Attribute::ByRef)) 10616 Flags.setByRef(); 10617 if (Arg.hasAttribute(Attribute::InAlloca)) { 10618 Flags.setInAlloca(); 10619 // Set the byval flag for CCAssignFn callbacks that don't know about 10620 // inalloca. This way we can know how many bytes we should've allocated 10621 // and how many bytes a callee cleanup function will pop. If we port 10622 // inalloca to more targets, we'll have to add custom inalloca handling 10623 // in the various CC lowering callbacks. 10624 Flags.setByVal(); 10625 } 10626 if (Arg.hasAttribute(Attribute::Preallocated)) { 10627 Flags.setPreallocated(); 10628 // Set the byval flag for CCAssignFn callbacks that don't know about 10629 // preallocated. This way we can know how many bytes we should've 10630 // allocated and how many bytes a callee cleanup function will pop. If 10631 // we port preallocated to more targets, we'll have to add custom 10632 // preallocated handling in the various CC lowering callbacks. 10633 Flags.setByVal(); 10634 } 10635 10636 // Certain targets (such as MIPS), may have a different ABI alignment 10637 // for a type depending on the context. Give the target a chance to 10638 // specify the alignment it wants. 10639 const Align OriginalAlignment( 10640 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10641 Flags.setOrigAlign(OriginalAlignment); 10642 10643 Align MemAlign; 10644 Type *ArgMemTy = nullptr; 10645 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10646 Flags.isByRef()) { 10647 if (!ArgMemTy) 10648 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10649 10650 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10651 10652 // For in-memory arguments, size and alignment should be passed from FE. 10653 // BE will guess if this info is not there but there are cases it cannot 10654 // get right. 10655 if (auto ParamAlign = Arg.getParamStackAlign()) 10656 MemAlign = *ParamAlign; 10657 else if ((ParamAlign = Arg.getParamAlign())) 10658 MemAlign = *ParamAlign; 10659 else 10660 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10661 if (Flags.isByRef()) 10662 Flags.setByRefSize(MemSize); 10663 else 10664 Flags.setByValSize(MemSize); 10665 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10666 MemAlign = *ParamAlign; 10667 } else { 10668 MemAlign = OriginalAlignment; 10669 } 10670 Flags.setMemAlign(MemAlign); 10671 10672 if (Arg.hasAttribute(Attribute::Nest)) 10673 Flags.setNest(); 10674 if (NeedsRegBlock) 10675 Flags.setInConsecutiveRegs(); 10676 if (ArgCopyElisionCandidates.count(&Arg)) 10677 Flags.setCopyElisionCandidate(); 10678 if (Arg.hasAttribute(Attribute::Returned)) 10679 Flags.setReturned(); 10680 10681 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10682 *CurDAG->getContext(), F.getCallingConv(), VT); 10683 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10684 *CurDAG->getContext(), F.getCallingConv(), VT); 10685 for (unsigned i = 0; i != NumRegs; ++i) { 10686 // For scalable vectors, use the minimum size; individual targets 10687 // are responsible for handling scalable vector arguments and 10688 // return values. 10689 ISD::InputArg MyFlags( 10690 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10691 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10692 if (NumRegs > 1 && i == 0) 10693 MyFlags.Flags.setSplit(); 10694 // if it isn't first piece, alignment must be 1 10695 else if (i > 0) { 10696 MyFlags.Flags.setOrigAlign(Align(1)); 10697 if (i == NumRegs - 1) 10698 MyFlags.Flags.setSplitEnd(); 10699 } 10700 Ins.push_back(MyFlags); 10701 } 10702 if (NeedsRegBlock && Value == NumValues - 1) 10703 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10704 PartBase += VT.getStoreSize().getKnownMinValue(); 10705 } 10706 } 10707 10708 // Call the target to set up the argument values. 10709 SmallVector<SDValue, 8> InVals; 10710 SDValue NewRoot = TLI->LowerFormalArguments( 10711 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10712 10713 // Verify that the target's LowerFormalArguments behaved as expected. 10714 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10715 "LowerFormalArguments didn't return a valid chain!"); 10716 assert(InVals.size() == Ins.size() && 10717 "LowerFormalArguments didn't emit the correct number of values!"); 10718 LLVM_DEBUG({ 10719 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10720 assert(InVals[i].getNode() && 10721 "LowerFormalArguments emitted a null value!"); 10722 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10723 "LowerFormalArguments emitted a value with the wrong type!"); 10724 } 10725 }); 10726 10727 // Update the DAG with the new chain value resulting from argument lowering. 10728 DAG.setRoot(NewRoot); 10729 10730 // Set up the argument values. 10731 unsigned i = 0; 10732 if (!FuncInfo->CanLowerReturn) { 10733 // Create a virtual register for the sret pointer, and put in a copy 10734 // from the sret argument into it. 10735 SmallVector<EVT, 1> ValueVTs; 10736 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10737 F.getReturnType()->getPointerTo( 10738 DAG.getDataLayout().getAllocaAddrSpace()), 10739 ValueVTs); 10740 MVT VT = ValueVTs[0].getSimpleVT(); 10741 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10742 std::optional<ISD::NodeType> AssertOp; 10743 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10744 nullptr, F.getCallingConv(), AssertOp); 10745 10746 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10747 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10748 Register SRetReg = 10749 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10750 FuncInfo->DemoteRegister = SRetReg; 10751 NewRoot = 10752 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10753 DAG.setRoot(NewRoot); 10754 10755 // i indexes lowered arguments. Bump it past the hidden sret argument. 10756 ++i; 10757 } 10758 10759 SmallVector<SDValue, 4> Chains; 10760 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10761 for (const Argument &Arg : F.args()) { 10762 SmallVector<SDValue, 4> ArgValues; 10763 SmallVector<EVT, 4> ValueVTs; 10764 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10765 unsigned NumValues = ValueVTs.size(); 10766 if (NumValues == 0) 10767 continue; 10768 10769 bool ArgHasUses = !Arg.use_empty(); 10770 10771 // Elide the copying store if the target loaded this argument from a 10772 // suitable fixed stack object. 10773 if (Ins[i].Flags.isCopyElisionCandidate()) { 10774 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10775 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10776 InVals[i], ArgHasUses); 10777 } 10778 10779 // If this argument is unused then remember its value. It is used to generate 10780 // debugging information. 10781 bool isSwiftErrorArg = 10782 TLI->supportSwiftError() && 10783 Arg.hasAttribute(Attribute::SwiftError); 10784 if (!ArgHasUses && !isSwiftErrorArg) { 10785 SDB->setUnusedArgValue(&Arg, InVals[i]); 10786 10787 // Also remember any frame index for use in FastISel. 10788 if (FrameIndexSDNode *FI = 10789 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10790 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10791 } 10792 10793 for (unsigned Val = 0; Val != NumValues; ++Val) { 10794 EVT VT = ValueVTs[Val]; 10795 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10796 F.getCallingConv(), VT); 10797 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10798 *CurDAG->getContext(), F.getCallingConv(), VT); 10799 10800 // Even an apparent 'unused' swifterror argument needs to be returned. So 10801 // we do generate a copy for it that can be used on return from the 10802 // function. 10803 if (ArgHasUses || isSwiftErrorArg) { 10804 std::optional<ISD::NodeType> AssertOp; 10805 if (Arg.hasAttribute(Attribute::SExt)) 10806 AssertOp = ISD::AssertSext; 10807 else if (Arg.hasAttribute(Attribute::ZExt)) 10808 AssertOp = ISD::AssertZext; 10809 10810 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10811 PartVT, VT, nullptr, 10812 F.getCallingConv(), AssertOp)); 10813 } 10814 10815 i += NumParts; 10816 } 10817 10818 // We don't need to do anything else for unused arguments. 10819 if (ArgValues.empty()) 10820 continue; 10821 10822 // Note down frame index. 10823 if (FrameIndexSDNode *FI = 10824 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10825 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10826 10827 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10828 SDB->getCurSDLoc()); 10829 10830 SDB->setValue(&Arg, Res); 10831 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10832 // We want to associate the argument with the frame index, among 10833 // involved operands, that correspond to the lowest address. The 10834 // getCopyFromParts function, called earlier, is swapping the order of 10835 // the operands to BUILD_PAIR depending on endianness. The result of 10836 // that swapping is that the least significant bits of the argument will 10837 // be in the first operand of the BUILD_PAIR node, and the most 10838 // significant bits will be in the second operand. 10839 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10840 if (LoadSDNode *LNode = 10841 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10842 if (FrameIndexSDNode *FI = 10843 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10844 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10845 } 10846 10847 // Analyses past this point are naive and don't expect an assertion. 10848 if (Res.getOpcode() == ISD::AssertZext) 10849 Res = Res.getOperand(0); 10850 10851 // Update the SwiftErrorVRegDefMap. 10852 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10853 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10854 if (Register::isVirtualRegister(Reg)) 10855 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10856 Reg); 10857 } 10858 10859 // If this argument is live outside of the entry block, insert a copy from 10860 // wherever we got it to the vreg that other BB's will reference it as. 10861 if (Res.getOpcode() == ISD::CopyFromReg) { 10862 // If we can, though, try to skip creating an unnecessary vreg. 10863 // FIXME: This isn't very clean... it would be nice to make this more 10864 // general. 10865 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10866 if (Register::isVirtualRegister(Reg)) { 10867 FuncInfo->ValueMap[&Arg] = Reg; 10868 continue; 10869 } 10870 } 10871 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10872 FuncInfo->InitializeRegForValue(&Arg); 10873 SDB->CopyToExportRegsIfNeeded(&Arg); 10874 } 10875 } 10876 10877 if (!Chains.empty()) { 10878 Chains.push_back(NewRoot); 10879 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10880 } 10881 10882 DAG.setRoot(NewRoot); 10883 10884 assert(i == InVals.size() && "Argument register count mismatch!"); 10885 10886 // If any argument copy elisions occurred and we have debug info, update the 10887 // stale frame indices used in the dbg.declare variable info table. 10888 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10889 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10890 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10891 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10892 if (I != ArgCopyElisionFrameIndexMap.end()) 10893 VI.Slot = I->second; 10894 } 10895 } 10896 10897 // Finally, if the target has anything special to do, allow it to do so. 10898 emitFunctionEntryCode(); 10899 } 10900 10901 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10902 /// ensure constants are generated when needed. Remember the virtual registers 10903 /// that need to be added to the Machine PHI nodes as input. We cannot just 10904 /// directly add them, because expansion might result in multiple MBB's for one 10905 /// BB. As such, the start of the BB might correspond to a different MBB than 10906 /// the end. 10907 void 10908 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10909 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10910 10911 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10912 10913 // Check PHI nodes in successors that expect a value to be available from this 10914 // block. 10915 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10916 if (!isa<PHINode>(SuccBB->begin())) continue; 10917 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10918 10919 // If this terminator has multiple identical successors (common for 10920 // switches), only handle each succ once. 10921 if (!SuccsHandled.insert(SuccMBB).second) 10922 continue; 10923 10924 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10925 10926 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10927 // nodes and Machine PHI nodes, but the incoming operands have not been 10928 // emitted yet. 10929 for (const PHINode &PN : SuccBB->phis()) { 10930 // Ignore dead phi's. 10931 if (PN.use_empty()) 10932 continue; 10933 10934 // Skip empty types 10935 if (PN.getType()->isEmptyTy()) 10936 continue; 10937 10938 unsigned Reg; 10939 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10940 10941 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10942 unsigned &RegOut = ConstantsOut[C]; 10943 if (RegOut == 0) { 10944 RegOut = FuncInfo.CreateRegs(C); 10945 // We need to zero/sign extend ConstantInt phi operands to match 10946 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10947 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10948 if (auto *CI = dyn_cast<ConstantInt>(C)) 10949 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10950 : ISD::ZERO_EXTEND; 10951 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10952 } 10953 Reg = RegOut; 10954 } else { 10955 DenseMap<const Value *, Register>::iterator I = 10956 FuncInfo.ValueMap.find(PHIOp); 10957 if (I != FuncInfo.ValueMap.end()) 10958 Reg = I->second; 10959 else { 10960 assert(isa<AllocaInst>(PHIOp) && 10961 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10962 "Didn't codegen value into a register!??"); 10963 Reg = FuncInfo.CreateRegs(PHIOp); 10964 CopyValueToVirtualRegister(PHIOp, Reg); 10965 } 10966 } 10967 10968 // Remember that this register needs to added to the machine PHI node as 10969 // the input for this MBB. 10970 SmallVector<EVT, 4> ValueVTs; 10971 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10972 for (EVT VT : ValueVTs) { 10973 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10974 for (unsigned i = 0; i != NumRegisters; ++i) 10975 FuncInfo.PHINodesToUpdate.push_back( 10976 std::make_pair(&*MBBI++, Reg + i)); 10977 Reg += NumRegisters; 10978 } 10979 } 10980 } 10981 10982 ConstantsOut.clear(); 10983 } 10984 10985 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10986 MachineFunction::iterator I(MBB); 10987 if (++I == FuncInfo.MF->end()) 10988 return nullptr; 10989 return &*I; 10990 } 10991 10992 /// During lowering new call nodes can be created (such as memset, etc.). 10993 /// Those will become new roots of the current DAG, but complications arise 10994 /// when they are tail calls. In such cases, the call lowering will update 10995 /// the root, but the builder still needs to know that a tail call has been 10996 /// lowered in order to avoid generating an additional return. 10997 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10998 // If the node is null, we do have a tail call. 10999 if (MaybeTC.getNode() != nullptr) 11000 DAG.setRoot(MaybeTC); 11001 else 11002 HasTailCall = true; 11003 } 11004 11005 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11006 MachineBasicBlock *SwitchMBB, 11007 MachineBasicBlock *DefaultMBB) { 11008 MachineFunction *CurMF = FuncInfo.MF; 11009 MachineBasicBlock *NextMBB = nullptr; 11010 MachineFunction::iterator BBI(W.MBB); 11011 if (++BBI != FuncInfo.MF->end()) 11012 NextMBB = &*BBI; 11013 11014 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11015 11016 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11017 11018 if (Size == 2 && W.MBB == SwitchMBB) { 11019 // If any two of the cases has the same destination, and if one value 11020 // is the same as the other, but has one bit unset that the other has set, 11021 // use bit manipulation to do two compares at once. For example: 11022 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11023 // TODO: This could be extended to merge any 2 cases in switches with 3 11024 // cases. 11025 // TODO: Handle cases where W.CaseBB != SwitchBB. 11026 CaseCluster &Small = *W.FirstCluster; 11027 CaseCluster &Big = *W.LastCluster; 11028 11029 if (Small.Low == Small.High && Big.Low == Big.High && 11030 Small.MBB == Big.MBB) { 11031 const APInt &SmallValue = Small.Low->getValue(); 11032 const APInt &BigValue = Big.Low->getValue(); 11033 11034 // Check that there is only one bit different. 11035 APInt CommonBit = BigValue ^ SmallValue; 11036 if (CommonBit.isPowerOf2()) { 11037 SDValue CondLHS = getValue(Cond); 11038 EVT VT = CondLHS.getValueType(); 11039 SDLoc DL = getCurSDLoc(); 11040 11041 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11042 DAG.getConstant(CommonBit, DL, VT)); 11043 SDValue Cond = DAG.getSetCC( 11044 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11045 ISD::SETEQ); 11046 11047 // Update successor info. 11048 // Both Small and Big will jump to Small.BB, so we sum up the 11049 // probabilities. 11050 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11051 if (BPI) 11052 addSuccessorWithProb( 11053 SwitchMBB, DefaultMBB, 11054 // The default destination is the first successor in IR. 11055 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11056 else 11057 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11058 11059 // Insert the true branch. 11060 SDValue BrCond = 11061 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11062 DAG.getBasicBlock(Small.MBB)); 11063 // Insert the false branch. 11064 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11065 DAG.getBasicBlock(DefaultMBB)); 11066 11067 DAG.setRoot(BrCond); 11068 return; 11069 } 11070 } 11071 } 11072 11073 if (TM.getOptLevel() != CodeGenOpt::None) { 11074 // Here, we order cases by probability so the most likely case will be 11075 // checked first. However, two clusters can have the same probability in 11076 // which case their relative ordering is non-deterministic. So we use Low 11077 // as a tie-breaker as clusters are guaranteed to never overlap. 11078 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11079 [](const CaseCluster &a, const CaseCluster &b) { 11080 return a.Prob != b.Prob ? 11081 a.Prob > b.Prob : 11082 a.Low->getValue().slt(b.Low->getValue()); 11083 }); 11084 11085 // Rearrange the case blocks so that the last one falls through if possible 11086 // without changing the order of probabilities. 11087 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11088 --I; 11089 if (I->Prob > W.LastCluster->Prob) 11090 break; 11091 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11092 std::swap(*I, *W.LastCluster); 11093 break; 11094 } 11095 } 11096 } 11097 11098 // Compute total probability. 11099 BranchProbability DefaultProb = W.DefaultProb; 11100 BranchProbability UnhandledProbs = DefaultProb; 11101 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11102 UnhandledProbs += I->Prob; 11103 11104 MachineBasicBlock *CurMBB = W.MBB; 11105 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11106 bool FallthroughUnreachable = false; 11107 MachineBasicBlock *Fallthrough; 11108 if (I == W.LastCluster) { 11109 // For the last cluster, fall through to the default destination. 11110 Fallthrough = DefaultMBB; 11111 FallthroughUnreachable = isa<UnreachableInst>( 11112 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11113 } else { 11114 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11115 CurMF->insert(BBI, Fallthrough); 11116 // Put Cond in a virtual register to make it available from the new blocks. 11117 ExportFromCurrentBlock(Cond); 11118 } 11119 UnhandledProbs -= I->Prob; 11120 11121 switch (I->Kind) { 11122 case CC_JumpTable: { 11123 // FIXME: Optimize away range check based on pivot comparisons. 11124 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11125 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11126 11127 // The jump block hasn't been inserted yet; insert it here. 11128 MachineBasicBlock *JumpMBB = JT->MBB; 11129 CurMF->insert(BBI, JumpMBB); 11130 11131 auto JumpProb = I->Prob; 11132 auto FallthroughProb = UnhandledProbs; 11133 11134 // If the default statement is a target of the jump table, we evenly 11135 // distribute the default probability to successors of CurMBB. Also 11136 // update the probability on the edge from JumpMBB to Fallthrough. 11137 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11138 SE = JumpMBB->succ_end(); 11139 SI != SE; ++SI) { 11140 if (*SI == DefaultMBB) { 11141 JumpProb += DefaultProb / 2; 11142 FallthroughProb -= DefaultProb / 2; 11143 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11144 JumpMBB->normalizeSuccProbs(); 11145 break; 11146 } 11147 } 11148 11149 if (FallthroughUnreachable) 11150 JTH->FallthroughUnreachable = true; 11151 11152 if (!JTH->FallthroughUnreachable) 11153 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11154 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11155 CurMBB->normalizeSuccProbs(); 11156 11157 // The jump table header will be inserted in our current block, do the 11158 // range check, and fall through to our fallthrough block. 11159 JTH->HeaderBB = CurMBB; 11160 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11161 11162 // If we're in the right place, emit the jump table header right now. 11163 if (CurMBB == SwitchMBB) { 11164 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11165 JTH->Emitted = true; 11166 } 11167 break; 11168 } 11169 case CC_BitTests: { 11170 // FIXME: Optimize away range check based on pivot comparisons. 11171 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11172 11173 // The bit test blocks haven't been inserted yet; insert them here. 11174 for (BitTestCase &BTC : BTB->Cases) 11175 CurMF->insert(BBI, BTC.ThisBB); 11176 11177 // Fill in fields of the BitTestBlock. 11178 BTB->Parent = CurMBB; 11179 BTB->Default = Fallthrough; 11180 11181 BTB->DefaultProb = UnhandledProbs; 11182 // If the cases in bit test don't form a contiguous range, we evenly 11183 // distribute the probability on the edge to Fallthrough to two 11184 // successors of CurMBB. 11185 if (!BTB->ContiguousRange) { 11186 BTB->Prob += DefaultProb / 2; 11187 BTB->DefaultProb -= DefaultProb / 2; 11188 } 11189 11190 if (FallthroughUnreachable) 11191 BTB->FallthroughUnreachable = true; 11192 11193 // If we're in the right place, emit the bit test header right now. 11194 if (CurMBB == SwitchMBB) { 11195 visitBitTestHeader(*BTB, SwitchMBB); 11196 BTB->Emitted = true; 11197 } 11198 break; 11199 } 11200 case CC_Range: { 11201 const Value *RHS, *LHS, *MHS; 11202 ISD::CondCode CC; 11203 if (I->Low == I->High) { 11204 // Check Cond == I->Low. 11205 CC = ISD::SETEQ; 11206 LHS = Cond; 11207 RHS=I->Low; 11208 MHS = nullptr; 11209 } else { 11210 // Check I->Low <= Cond <= I->High. 11211 CC = ISD::SETLE; 11212 LHS = I->Low; 11213 MHS = Cond; 11214 RHS = I->High; 11215 } 11216 11217 // If Fallthrough is unreachable, fold away the comparison. 11218 if (FallthroughUnreachable) 11219 CC = ISD::SETTRUE; 11220 11221 // The false probability is the sum of all unhandled cases. 11222 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11223 getCurSDLoc(), I->Prob, UnhandledProbs); 11224 11225 if (CurMBB == SwitchMBB) 11226 visitSwitchCase(CB, SwitchMBB); 11227 else 11228 SL->SwitchCases.push_back(CB); 11229 11230 break; 11231 } 11232 } 11233 CurMBB = Fallthrough; 11234 } 11235 } 11236 11237 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11238 CaseClusterIt First, 11239 CaseClusterIt Last) { 11240 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11241 if (X.Prob != CC.Prob) 11242 return X.Prob > CC.Prob; 11243 11244 // Ties are broken by comparing the case value. 11245 return X.Low->getValue().slt(CC.Low->getValue()); 11246 }); 11247 } 11248 11249 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11250 const SwitchWorkListItem &W, 11251 Value *Cond, 11252 MachineBasicBlock *SwitchMBB) { 11253 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11254 "Clusters not sorted?"); 11255 11256 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11257 11258 // Balance the tree based on branch probabilities to create a near-optimal (in 11259 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11260 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11261 CaseClusterIt LastLeft = W.FirstCluster; 11262 CaseClusterIt FirstRight = W.LastCluster; 11263 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11264 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11265 11266 // Move LastLeft and FirstRight towards each other from opposite directions to 11267 // find a partitioning of the clusters which balances the probability on both 11268 // sides. If LeftProb and RightProb are equal, alternate which side is 11269 // taken to ensure 0-probability nodes are distributed evenly. 11270 unsigned I = 0; 11271 while (LastLeft + 1 < FirstRight) { 11272 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11273 LeftProb += (++LastLeft)->Prob; 11274 else 11275 RightProb += (--FirstRight)->Prob; 11276 I++; 11277 } 11278 11279 while (true) { 11280 // Our binary search tree differs from a typical BST in that ours can have up 11281 // to three values in each leaf. The pivot selection above doesn't take that 11282 // into account, which means the tree might require more nodes and be less 11283 // efficient. We compensate for this here. 11284 11285 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11286 unsigned NumRight = W.LastCluster - FirstRight + 1; 11287 11288 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11289 // If one side has less than 3 clusters, and the other has more than 3, 11290 // consider taking a cluster from the other side. 11291 11292 if (NumLeft < NumRight) { 11293 // Consider moving the first cluster on the right to the left side. 11294 CaseCluster &CC = *FirstRight; 11295 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11296 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11297 if (LeftSideRank <= RightSideRank) { 11298 // Moving the cluster to the left does not demote it. 11299 ++LastLeft; 11300 ++FirstRight; 11301 continue; 11302 } 11303 } else { 11304 assert(NumRight < NumLeft); 11305 // Consider moving the last element on the left to the right side. 11306 CaseCluster &CC = *LastLeft; 11307 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11308 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11309 if (RightSideRank <= LeftSideRank) { 11310 // Moving the cluster to the right does not demot it. 11311 --LastLeft; 11312 --FirstRight; 11313 continue; 11314 } 11315 } 11316 } 11317 break; 11318 } 11319 11320 assert(LastLeft + 1 == FirstRight); 11321 assert(LastLeft >= W.FirstCluster); 11322 assert(FirstRight <= W.LastCluster); 11323 11324 // Use the first element on the right as pivot since we will make less-than 11325 // comparisons against it. 11326 CaseClusterIt PivotCluster = FirstRight; 11327 assert(PivotCluster > W.FirstCluster); 11328 assert(PivotCluster <= W.LastCluster); 11329 11330 CaseClusterIt FirstLeft = W.FirstCluster; 11331 CaseClusterIt LastRight = W.LastCluster; 11332 11333 const ConstantInt *Pivot = PivotCluster->Low; 11334 11335 // New blocks will be inserted immediately after the current one. 11336 MachineFunction::iterator BBI(W.MBB); 11337 ++BBI; 11338 11339 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11340 // we can branch to its destination directly if it's squeezed exactly in 11341 // between the known lower bound and Pivot - 1. 11342 MachineBasicBlock *LeftMBB; 11343 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11344 FirstLeft->Low == W.GE && 11345 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11346 LeftMBB = FirstLeft->MBB; 11347 } else { 11348 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11349 FuncInfo.MF->insert(BBI, LeftMBB); 11350 WorkList.push_back( 11351 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11352 // Put Cond in a virtual register to make it available from the new blocks. 11353 ExportFromCurrentBlock(Cond); 11354 } 11355 11356 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11357 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11358 // directly if RHS.High equals the current upper bound. 11359 MachineBasicBlock *RightMBB; 11360 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11361 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11362 RightMBB = FirstRight->MBB; 11363 } else { 11364 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11365 FuncInfo.MF->insert(BBI, RightMBB); 11366 WorkList.push_back( 11367 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11368 // Put Cond in a virtual register to make it available from the new blocks. 11369 ExportFromCurrentBlock(Cond); 11370 } 11371 11372 // Create the CaseBlock record that will be used to lower the branch. 11373 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11374 getCurSDLoc(), LeftProb, RightProb); 11375 11376 if (W.MBB == SwitchMBB) 11377 visitSwitchCase(CB, SwitchMBB); 11378 else 11379 SL->SwitchCases.push_back(CB); 11380 } 11381 11382 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11383 // from the swith statement. 11384 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11385 BranchProbability PeeledCaseProb) { 11386 if (PeeledCaseProb == BranchProbability::getOne()) 11387 return BranchProbability::getZero(); 11388 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11389 11390 uint32_t Numerator = CaseProb.getNumerator(); 11391 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11392 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11393 } 11394 11395 // Try to peel the top probability case if it exceeds the threshold. 11396 // Return current MachineBasicBlock for the switch statement if the peeling 11397 // does not occur. 11398 // If the peeling is performed, return the newly created MachineBasicBlock 11399 // for the peeled switch statement. Also update Clusters to remove the peeled 11400 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11401 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11402 const SwitchInst &SI, CaseClusterVector &Clusters, 11403 BranchProbability &PeeledCaseProb) { 11404 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11405 // Don't perform if there is only one cluster or optimizing for size. 11406 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11407 TM.getOptLevel() == CodeGenOpt::None || 11408 SwitchMBB->getParent()->getFunction().hasMinSize()) 11409 return SwitchMBB; 11410 11411 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11412 unsigned PeeledCaseIndex = 0; 11413 bool SwitchPeeled = false; 11414 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11415 CaseCluster &CC = Clusters[Index]; 11416 if (CC.Prob < TopCaseProb) 11417 continue; 11418 TopCaseProb = CC.Prob; 11419 PeeledCaseIndex = Index; 11420 SwitchPeeled = true; 11421 } 11422 if (!SwitchPeeled) 11423 return SwitchMBB; 11424 11425 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11426 << TopCaseProb << "\n"); 11427 11428 // Record the MBB for the peeled switch statement. 11429 MachineFunction::iterator BBI(SwitchMBB); 11430 ++BBI; 11431 MachineBasicBlock *PeeledSwitchMBB = 11432 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11433 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11434 11435 ExportFromCurrentBlock(SI.getCondition()); 11436 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11437 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11438 nullptr, nullptr, TopCaseProb.getCompl()}; 11439 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11440 11441 Clusters.erase(PeeledCaseIt); 11442 for (CaseCluster &CC : Clusters) { 11443 LLVM_DEBUG( 11444 dbgs() << "Scale the probablity for one cluster, before scaling: " 11445 << CC.Prob << "\n"); 11446 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11447 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11448 } 11449 PeeledCaseProb = TopCaseProb; 11450 return PeeledSwitchMBB; 11451 } 11452 11453 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11454 // Extract cases from the switch. 11455 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11456 CaseClusterVector Clusters; 11457 Clusters.reserve(SI.getNumCases()); 11458 for (auto I : SI.cases()) { 11459 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11460 const ConstantInt *CaseVal = I.getCaseValue(); 11461 BranchProbability Prob = 11462 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11463 : BranchProbability(1, SI.getNumCases() + 1); 11464 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11465 } 11466 11467 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11468 11469 // Cluster adjacent cases with the same destination. We do this at all 11470 // optimization levels because it's cheap to do and will make codegen faster 11471 // if there are many clusters. 11472 sortAndRangeify(Clusters); 11473 11474 // The branch probablity of the peeled case. 11475 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11476 MachineBasicBlock *PeeledSwitchMBB = 11477 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11478 11479 // If there is only the default destination, jump there directly. 11480 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11481 if (Clusters.empty()) { 11482 assert(PeeledSwitchMBB == SwitchMBB); 11483 SwitchMBB->addSuccessor(DefaultMBB); 11484 if (DefaultMBB != NextBlock(SwitchMBB)) { 11485 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11486 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11487 } 11488 return; 11489 } 11490 11491 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11492 SL->findBitTestClusters(Clusters, &SI); 11493 11494 LLVM_DEBUG({ 11495 dbgs() << "Case clusters: "; 11496 for (const CaseCluster &C : Clusters) { 11497 if (C.Kind == CC_JumpTable) 11498 dbgs() << "JT:"; 11499 if (C.Kind == CC_BitTests) 11500 dbgs() << "BT:"; 11501 11502 C.Low->getValue().print(dbgs(), true); 11503 if (C.Low != C.High) { 11504 dbgs() << '-'; 11505 C.High->getValue().print(dbgs(), true); 11506 } 11507 dbgs() << ' '; 11508 } 11509 dbgs() << '\n'; 11510 }); 11511 11512 assert(!Clusters.empty()); 11513 SwitchWorkList WorkList; 11514 CaseClusterIt First = Clusters.begin(); 11515 CaseClusterIt Last = Clusters.end() - 1; 11516 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11517 // Scale the branchprobability for DefaultMBB if the peel occurs and 11518 // DefaultMBB is not replaced. 11519 if (PeeledCaseProb != BranchProbability::getZero() && 11520 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11521 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11522 WorkList.push_back( 11523 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11524 11525 while (!WorkList.empty()) { 11526 SwitchWorkListItem W = WorkList.pop_back_val(); 11527 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11528 11529 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11530 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11531 // For optimized builds, lower large range as a balanced binary tree. 11532 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11533 continue; 11534 } 11535 11536 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11537 } 11538 } 11539 11540 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11542 auto DL = getCurSDLoc(); 11543 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11544 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11545 } 11546 11547 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11548 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11549 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11550 11551 SDLoc DL = getCurSDLoc(); 11552 SDValue V = getValue(I.getOperand(0)); 11553 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11554 11555 if (VT.isScalableVector()) { 11556 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11557 return; 11558 } 11559 11560 // Use VECTOR_SHUFFLE for the fixed-length vector 11561 // to maintain existing behavior. 11562 SmallVector<int, 8> Mask; 11563 unsigned NumElts = VT.getVectorMinNumElements(); 11564 for (unsigned i = 0; i != NumElts; ++i) 11565 Mask.push_back(NumElts - 1 - i); 11566 11567 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11568 } 11569 11570 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11571 auto DL = getCurSDLoc(); 11572 SDValue InVec = getValue(I.getOperand(0)); 11573 EVT OutVT = 11574 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11575 11576 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11577 11578 // ISD Node needs the input vectors split into two equal parts 11579 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11580 DAG.getVectorIdxConstant(0, DL)); 11581 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11582 DAG.getVectorIdxConstant(OutNumElts, DL)); 11583 11584 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11585 // legalisation and combines. 11586 if (OutVT.isFixedLengthVector()) { 11587 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11588 createStrideMask(0, 2, OutNumElts)); 11589 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11590 createStrideMask(1, 2, OutNumElts)); 11591 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11592 setValue(&I, Res); 11593 return; 11594 } 11595 11596 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11597 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11598 setValue(&I, Res); 11599 return; 11600 } 11601 11602 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11603 auto DL = getCurSDLoc(); 11604 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11605 SDValue InVec0 = getValue(I.getOperand(0)); 11606 SDValue InVec1 = getValue(I.getOperand(1)); 11607 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11608 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11609 11610 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11611 // legalisation and combines. 11612 if (OutVT.isFixedLengthVector()) { 11613 unsigned NumElts = InVT.getVectorMinNumElements(); 11614 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11615 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11616 createInterleaveMask(NumElts, 2))); 11617 return; 11618 } 11619 11620 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11621 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11622 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11623 Res.getValue(1)); 11624 setValue(&I, Res); 11625 return; 11626 } 11627 11628 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11629 SmallVector<EVT, 4> ValueVTs; 11630 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11631 ValueVTs); 11632 unsigned NumValues = ValueVTs.size(); 11633 if (NumValues == 0) return; 11634 11635 SmallVector<SDValue, 4> Values(NumValues); 11636 SDValue Op = getValue(I.getOperand(0)); 11637 11638 for (unsigned i = 0; i != NumValues; ++i) 11639 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11640 SDValue(Op.getNode(), Op.getResNo() + i)); 11641 11642 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11643 DAG.getVTList(ValueVTs), Values)); 11644 } 11645 11646 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11647 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11648 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11649 11650 SDLoc DL = getCurSDLoc(); 11651 SDValue V1 = getValue(I.getOperand(0)); 11652 SDValue V2 = getValue(I.getOperand(1)); 11653 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11654 11655 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11656 if (VT.isScalableVector()) { 11657 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11658 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11659 DAG.getConstant(Imm, DL, IdxVT))); 11660 return; 11661 } 11662 11663 unsigned NumElts = VT.getVectorNumElements(); 11664 11665 uint64_t Idx = (NumElts + Imm) % NumElts; 11666 11667 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11668 SmallVector<int, 8> Mask; 11669 for (unsigned i = 0; i < NumElts; ++i) 11670 Mask.push_back(Idx + i); 11671 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11672 } 11673 11674 // Consider the following MIR after SelectionDAG, which produces output in 11675 // phyregs in the first case or virtregs in the second case. 11676 // 11677 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11678 // %5:gr32 = COPY $ebx 11679 // %6:gr32 = COPY $edx 11680 // %1:gr32 = COPY %6:gr32 11681 // %0:gr32 = COPY %5:gr32 11682 // 11683 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11684 // %1:gr32 = COPY %6:gr32 11685 // %0:gr32 = COPY %5:gr32 11686 // 11687 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11688 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11689 // 11690 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11691 // to a single virtreg (such as %0). The remaining outputs monotonically 11692 // increase in virtreg number from there. If a callbr has no outputs, then it 11693 // should not have a corresponding callbr landingpad; in fact, the callbr 11694 // landingpad would not even be able to refer to such a callbr. 11695 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11696 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11697 // There is definitely at least one copy. 11698 assert(MI->getOpcode() == TargetOpcode::COPY && 11699 "start of copy chain MUST be COPY"); 11700 Reg = MI->getOperand(1).getReg(); 11701 MI = MRI.def_begin(Reg)->getParent(); 11702 // There may be an optional second copy. 11703 if (MI->getOpcode() == TargetOpcode::COPY) { 11704 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11705 Reg = MI->getOperand(1).getReg(); 11706 assert(Reg.isPhysical() && "expected COPY of physical register"); 11707 MI = MRI.def_begin(Reg)->getParent(); 11708 } 11709 // The start of the chain must be an INLINEASM_BR. 11710 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11711 "end of copy chain MUST be INLINEASM_BR"); 11712 return Reg; 11713 } 11714 11715 // We must do this walk rather than the simpler 11716 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11717 // otherwise we will end up with copies of virtregs only valid along direct 11718 // edges. 11719 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11720 SmallVector<EVT, 8> ResultVTs; 11721 SmallVector<SDValue, 8> ResultValues; 11722 const auto *CBR = 11723 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11724 11725 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11726 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11727 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11728 11729 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11730 SDValue Chain = DAG.getRoot(); 11731 11732 // Re-parse the asm constraints string. 11733 TargetLowering::AsmOperandInfoVector TargetConstraints = 11734 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11735 for (auto &T : TargetConstraints) { 11736 SDISelAsmOperandInfo OpInfo(T); 11737 if (OpInfo.Type != InlineAsm::isOutput) 11738 continue; 11739 11740 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11741 // individual constraint. 11742 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11743 11744 switch (OpInfo.ConstraintType) { 11745 case TargetLowering::C_Register: 11746 case TargetLowering::C_RegisterClass: { 11747 // Fill in OpInfo.AssignedRegs.Regs. 11748 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11749 11750 // getRegistersForValue may produce 1 to many registers based on whether 11751 // the OpInfo.ConstraintVT is legal on the target or not. 11752 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11753 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11754 if (Register::isPhysicalRegister(OriginalDef)) 11755 FuncInfo.MBB->addLiveIn(OriginalDef); 11756 // Update the assigned registers to use the original defs. 11757 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11758 } 11759 11760 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11761 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11762 ResultValues.push_back(V); 11763 ResultVTs.push_back(OpInfo.ConstraintVT); 11764 break; 11765 } 11766 case TargetLowering::C_Other: { 11767 SDValue Flag; 11768 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11769 OpInfo, DAG); 11770 ++InitialDef; 11771 ResultValues.push_back(V); 11772 ResultVTs.push_back(OpInfo.ConstraintVT); 11773 break; 11774 } 11775 default: 11776 break; 11777 } 11778 } 11779 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11780 DAG.getVTList(ResultVTs), ResultValues); 11781 setValue(&I, V); 11782 } 11783