1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/MachineBasicBlock.h" 37 #include "llvm/CodeGen/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineOperand.h" 44 #include "llvm/CodeGen/MachineRegisterInfo.h" 45 #include "llvm/CodeGen/RuntimeLibcalls.h" 46 #include "llvm/CodeGen/SelectionDAG.h" 47 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 48 #include "llvm/CodeGen/StackMaps.h" 49 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 50 #include "llvm/CodeGen/TargetFrameLowering.h" 51 #include "llvm/CodeGen/TargetInstrInfo.h" 52 #include "llvm/CodeGen/TargetOpcodes.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/TargetSubtargetInfo.h" 55 #include "llvm/CodeGen/WinEHFuncInfo.h" 56 #include "llvm/IR/Argument.h" 57 #include "llvm/IR/Attributes.h" 58 #include "llvm/IR/BasicBlock.h" 59 #include "llvm/IR/CFG.h" 60 #include "llvm/IR/CallingConv.h" 61 #include "llvm/IR/Constant.h" 62 #include "llvm/IR/ConstantRange.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/DataLayout.h" 65 #include "llvm/IR/DebugInfo.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/DiagnosticInfo.h" 69 #include "llvm/IR/EHPersonalities.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/GetElementPtrTypeIterator.h" 72 #include "llvm/IR/InlineAsm.h" 73 #include "llvm/IR/InstrTypes.h" 74 #include "llvm/IR/Instructions.h" 75 #include "llvm/IR/IntrinsicInst.h" 76 #include "llvm/IR/Intrinsics.h" 77 #include "llvm/IR/IntrinsicsAArch64.h" 78 #include "llvm/IR/IntrinsicsWebAssembly.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Metadata.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/Operator.h" 83 #include "llvm/IR/PatternMatch.h" 84 #include "llvm/IR/Statepoint.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/Support/AtomicOrdering.h" 90 #include "llvm/Support/Casting.h" 91 #include "llvm/Support/CommandLine.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Debug.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetIntrinsicInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include "llvm/TargetParser/Triple.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <iterator> 103 #include <limits> 104 #include <optional> 105 #include <tuple> 106 107 using namespace llvm; 108 using namespace PatternMatch; 109 using namespace SwitchCG; 110 111 #define DEBUG_TYPE "isel" 112 113 /// LimitFloatPrecision - Generate low-precision inline sequences for 114 /// some float libcalls (6, 8 or 12 bits). 115 static unsigned LimitFloatPrecision; 116 117 static cl::opt<bool> 118 InsertAssertAlign("insert-assert-align", cl::init(true), 119 cl::desc("Insert the experimental `assertalign` node."), 120 cl::ReallyHidden); 121 122 static cl::opt<unsigned, true> 123 LimitFPPrecision("limit-float-precision", 124 cl::desc("Generate low-precision inline sequences " 125 "for some float libcalls"), 126 cl::location(LimitFloatPrecision), cl::Hidden, 127 cl::init(0)); 128 129 static cl::opt<unsigned> SwitchPeelThreshold( 130 "switch-peel-threshold", cl::Hidden, cl::init(66), 131 cl::desc("Set the case probability threshold for peeling the case from a " 132 "switch statement. A value greater than 100 will void this " 133 "optimization")); 134 135 // Limit the width of DAG chains. This is important in general to prevent 136 // DAG-based analysis from blowing up. For example, alias analysis and 137 // load clustering may not complete in reasonable time. It is difficult to 138 // recognize and avoid this situation within each individual analysis, and 139 // future analyses are likely to have the same behavior. Limiting DAG width is 140 // the safe approach and will be especially important with global DAGs. 141 // 142 // MaxParallelChains default is arbitrarily high to avoid affecting 143 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 144 // sequence over this should have been converted to llvm.memcpy by the 145 // frontend. It is easy to induce this behavior with .ll code such as: 146 // %buffer = alloca [4096 x i8] 147 // %data = load [4096 x i8]* %argPtr 148 // store [4096 x i8] %data, [4096 x i8]* %buffer 149 static const unsigned MaxParallelChains = 64; 150 151 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 152 const SDValue *Parts, unsigned NumParts, 153 MVT PartVT, EVT ValueVT, const Value *V, 154 std::optional<CallingConv::ID> CC); 155 156 /// getCopyFromParts - Create a value that contains the specified legal parts 157 /// combined into the value they represent. If the parts combine to a type 158 /// larger than ValueVT then AssertOp can be used to specify whether the extra 159 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 160 /// (ISD::AssertSext). 161 static SDValue 162 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 164 std::optional<CallingConv::ID> CC = std::nullopt, 165 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 166 // Let the target assemble the parts if it wants to 167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 169 PartVT, ValueVT, CC)) 170 return Val; 171 172 if (ValueVT.isVector()) 173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 174 CC); 175 176 assert(NumParts > 0 && "No parts to assemble!"); 177 SDValue Val = Parts[0]; 178 179 if (NumParts > 1) { 180 // Assemble the value from multiple parts. 181 if (ValueVT.isInteger()) { 182 unsigned PartBits = PartVT.getSizeInBits(); 183 unsigned ValueBits = ValueVT.getSizeInBits(); 184 185 // Assemble the power of 2 part. 186 unsigned RoundParts = llvm::bit_floor(NumParts); 187 unsigned RoundBits = PartBits * RoundParts; 188 EVT RoundVT = RoundBits == ValueBits ? 189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 190 SDValue Lo, Hi; 191 192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 193 194 if (RoundParts > 2) { 195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 196 PartVT, HalfVT, V); 197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 198 RoundParts / 2, PartVT, HalfVT, V); 199 } else { 200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 202 } 203 204 if (DAG.getDataLayout().isBigEndian()) 205 std::swap(Lo, Hi); 206 207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 208 209 if (RoundParts < NumParts) { 210 // Assemble the trailing non-power-of-2 part. 211 unsigned OddParts = NumParts - RoundParts; 212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 214 OddVT, V, CC); 215 216 // Combine the round and odd parts. 217 Lo = Val; 218 if (DAG.getDataLayout().isBigEndian()) 219 std::swap(Lo, Hi); 220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 223 DAG.getConstant(Lo.getValueSizeInBits(), DL, 224 TLI.getShiftAmountTy( 225 TotalVT, DAG.getDataLayout()))); 226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 228 } 229 } else if (PartVT.isFloatingPoint()) { 230 // FP split into multiple FP parts (for ppcf128) 231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 232 "Unexpected split"); 233 SDValue Lo, Hi; 234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 237 std::swap(Lo, Hi); 238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 239 } else { 240 // FP split into integer parts (soft fp) 241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 242 !PartVT.isVector() && "Unexpected split"); 243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 245 } 246 } 247 248 // There is now one part, held in Val. Correct it to match ValueVT. 249 // PartEVT is the type of the register class that holds the value. 250 // ValueVT is the type of the inline asm operation. 251 EVT PartEVT = Val.getValueType(); 252 253 if (PartEVT == ValueVT) 254 return Val; 255 256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 257 ValueVT.bitsLT(PartEVT)) { 258 // For an FP value in an integer part, we need to truncate to the right 259 // width first. 260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 262 } 263 264 // Handle types that have the same size. 265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 267 268 // Handle types with different sizes. 269 if (PartEVT.isInteger() && ValueVT.isInteger()) { 270 if (ValueVT.bitsLT(PartEVT)) { 271 // For a truncate, see if we have any information to 272 // indicate whether the truncated bits will always be 273 // zero or sign-extension. 274 if (AssertOp) 275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 276 DAG.getValueType(ValueVT)); 277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 278 } 279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 280 } 281 282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 283 // FP_ROUND's are always exact here. 284 if (ValueVT.bitsLT(Val.getValueType())) 285 return DAG.getNode( 286 ISD::FP_ROUND, DL, ValueVT, Val, 287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 288 289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 290 } 291 292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 293 // then truncating. 294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 295 ValueVT.bitsLT(PartEVT)) { 296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 298 } 299 300 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 301 } 302 303 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 304 const Twine &ErrMsg) { 305 const Instruction *I = dyn_cast_or_null<Instruction>(V); 306 if (!V) 307 return Ctx.emitError(ErrMsg); 308 309 const char *AsmError = ", possible invalid constraint for vector type"; 310 if (const CallInst *CI = dyn_cast<CallInst>(I)) 311 if (CI->isInlineAsm()) 312 return Ctx.emitError(I, ErrMsg + AsmError); 313 314 return Ctx.emitError(I, ErrMsg); 315 } 316 317 /// getCopyFromPartsVector - Create a value that contains the specified legal 318 /// parts combined into the value they represent. If the parts combine to a 319 /// type larger than ValueVT then AssertOp can be used to specify whether the 320 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 321 /// ValueVT (ISD::AssertSext). 322 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 323 const SDValue *Parts, unsigned NumParts, 324 MVT PartVT, EVT ValueVT, const Value *V, 325 std::optional<CallingConv::ID> CallConv) { 326 assert(ValueVT.isVector() && "Not a vector value"); 327 assert(NumParts > 0 && "No parts to assemble!"); 328 const bool IsABIRegCopy = CallConv.has_value(); 329 330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 331 SDValue Val = Parts[0]; 332 333 // Handle a multi-element vector. 334 if (NumParts > 1) { 335 EVT IntermediateVT; 336 MVT RegisterVT; 337 unsigned NumIntermediates; 338 unsigned NumRegs; 339 340 if (IsABIRegCopy) { 341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 343 NumIntermediates, RegisterVT); 344 } else { 345 NumRegs = 346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } 349 350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 351 NumParts = NumRegs; // Silence a compiler warning. 352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 353 assert(RegisterVT.getSizeInBits() == 354 Parts[0].getSimpleValueType().getSizeInBits() && 355 "Part type sizes don't match!"); 356 357 // Assemble the parts into intermediate operands. 358 SmallVector<SDValue, 8> Ops(NumIntermediates); 359 if (NumIntermediates == NumParts) { 360 // If the register was not expanded, truncate or copy the value, 361 // as appropriate. 362 for (unsigned i = 0; i != NumParts; ++i) 363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 364 PartVT, IntermediateVT, V, CallConv); 365 } else if (NumParts > 0) { 366 // If the intermediate type was expanded, build the intermediate 367 // operands from the parts. 368 assert(NumParts % NumIntermediates == 0 && 369 "Must expand into a divisible number of parts!"); 370 unsigned Factor = NumParts / NumIntermediates; 371 for (unsigned i = 0; i != NumIntermediates; ++i) 372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 373 PartVT, IntermediateVT, V, CallConv); 374 } 375 376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 377 // intermediate operands. 378 EVT BuiltVectorTy = 379 IntermediateVT.isVector() 380 ? EVT::getVectorVT( 381 *DAG.getContext(), IntermediateVT.getScalarType(), 382 IntermediateVT.getVectorElementCount() * NumParts) 383 : EVT::getVectorVT(*DAG.getContext(), 384 IntermediateVT.getScalarType(), 385 NumIntermediates); 386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 387 : ISD::BUILD_VECTOR, 388 DL, BuiltVectorTy, Ops); 389 } 390 391 // There is now one part, held in Val. Correct it to match ValueVT. 392 EVT PartEVT = Val.getValueType(); 393 394 if (PartEVT == ValueVT) 395 return Val; 396 397 if (PartEVT.isVector()) { 398 // Vector/Vector bitcast. 399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 401 402 // If the parts vector has more elements than the value vector, then we 403 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 404 // Extract the elements we want. 405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 406 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 407 ValueVT.getVectorElementCount().getKnownMinValue()) && 408 (PartEVT.getVectorElementCount().isScalable() == 409 ValueVT.getVectorElementCount().isScalable()) && 410 "Cannot narrow, it would be a lossy transformation"); 411 PartEVT = 412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 413 ValueVT.getVectorElementCount()); 414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 415 DAG.getVectorIdxConstant(0, DL)); 416 if (PartEVT == ValueVT) 417 return Val; 418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 420 } 421 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 } 425 426 // Trivial bitcast if the types are the same size and the destination 427 // vector type is legal. 428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 429 TLI.isTypeLegal(ValueVT)) 430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 431 432 if (ValueVT.getVectorNumElements() != 1) { 433 // Certain ABIs require that vectors are passed as integers. For vectors 434 // are the same size, this is an obvious bitcast. 435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 437 } else if (ValueVT.bitsLT(PartEVT)) { 438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 440 // Drop the extra bits. 441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 442 return DAG.getBitcast(ValueVT, Val); 443 } 444 445 diagnosePossiblyInvalidConstraint( 446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 447 return DAG.getUNDEF(ValueVT); 448 } 449 450 // Handle cases such as i8 -> <1 x i1> 451 EVT ValueSVT = ValueVT.getVectorElementType(); 452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 453 unsigned ValueSize = ValueSVT.getSizeInBits(); 454 if (ValueSize == PartEVT.getSizeInBits()) { 455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 457 // It's possible a scalar floating point type gets softened to integer and 458 // then promoted to a larger integer. If PartEVT is the larger integer 459 // we need to truncate it and then bitcast to the FP type. 460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 463 Val = DAG.getBitcast(ValueSVT, Val); 464 } else { 465 Val = ValueVT.isFloatingPoint() 466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 468 } 469 } 470 471 return DAG.getBuildVector(ValueVT, DL, Val); 472 } 473 474 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 475 SDValue Val, SDValue *Parts, unsigned NumParts, 476 MVT PartVT, const Value *V, 477 std::optional<CallingConv::ID> CallConv); 478 479 /// getCopyToParts - Create a series of nodes that contain the specified value 480 /// split into legal parts. If the parts contain more bits than Val, then, for 481 /// integers, ExtendKind can be used to specify how to generate the extra bits. 482 static void 483 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 484 unsigned NumParts, MVT PartVT, const Value *V, 485 std::optional<CallingConv::ID> CallConv = std::nullopt, 486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 487 // Let the target split the parts if it wants to 488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 490 CallConv)) 491 return; 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned OrigNumParts = NumParts; 500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 501 "Copying to an illegal type!"); 502 503 if (NumParts == 0) 504 return; 505 506 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 507 EVT PartEVT = PartVT; 508 if (PartEVT == ValueVT) { 509 assert(NumParts == 1 && "No-op copy with multiple parts!"); 510 Parts[0] = Val; 511 return; 512 } 513 514 unsigned PartBits = PartVT.getSizeInBits(); 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = llvm::bit_floor(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 576 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 620 const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 ElementCount PartNumElts = PartVT.getVectorElementCount(); 626 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 627 628 // We only support widening vectors with equivalent element types and 629 // fixed/scalable properties. If a target needs to widen a fixed-length type 630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 632 PartNumElts.isScalable() != ValueNumElts.isScalable() || 633 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 634 return SDValue(); 635 636 // Widening a scalable vector to another scalable vector is done by inserting 637 // the vector into a larger undef one. 638 if (PartNumElts.isScalable()) 639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 640 Val, DAG.getVectorIdxConstant(0, DL)); 641 642 EVT ElementVT = PartVT.getVectorElementType(); 643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 644 // undef elements. 645 SmallVector<SDValue, 16> Ops; 646 DAG.ExtractVectorElements(Val, Ops); 647 SDValue EltUndef = DAG.getUNDEF(ElementVT); 648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 649 650 // FIXME: Use CONCAT for 2x -> 4x. 651 return DAG.getBuildVector(PartVT, DL, Ops); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 std::optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.has_value(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorElementCount() == 678 ValueVT.getVectorElementCount()) { 679 680 // Promoted vector extract 681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 682 } else if (PartEVT.isVector() && 683 PartEVT.getVectorElementType() != 684 ValueVT.getVectorElementType() && 685 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 686 TargetLowering::TypeWidenVector) { 687 // Combination of widening and promotion. 688 EVT WidenVT = 689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 690 PartVT.getVectorElementCount()); 691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 693 } else { 694 // Don't extract an integer from a float vector. This can happen if the 695 // FP type gets softened to integer and then promoted. The promotion 696 // prevents it from being picked up by the earlier bitcast case. 697 if (ValueVT.getVectorElementCount().isScalar() && 698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 700 DAG.getVectorIdxConstant(0, DL)); 701 } else { 702 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 703 assert(PartVT.getFixedSizeInBits() > ValueSize && 704 "lossy conversion of vector to scalar type"); 705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 706 Val = DAG.getBitcast(IntermediateType, Val); 707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 708 } 709 } 710 711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 712 Parts[0] = Val; 713 return; 714 } 715 716 // Handle a multi-element vector. 717 EVT IntermediateVT; 718 MVT RegisterVT; 719 unsigned NumIntermediates; 720 unsigned NumRegs; 721 if (IsABIRegCopy) { 722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 724 RegisterVT); 725 } else { 726 NumRegs = 727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 728 NumIntermediates, RegisterVT); 729 } 730 731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 732 NumParts = NumRegs; // Silence a compiler warning. 733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 734 735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 736 "Mixing scalable and fixed vectors when copying in parts"); 737 738 std::optional<ElementCount> DestEltCnt; 739 740 if (IntermediateVT.isVector()) 741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 742 else 743 DestEltCnt = ElementCount::getFixed(NumIntermediates); 744 745 EVT BuiltVectorTy = EVT::getVectorVT( 746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 747 748 if (ValueVT == BuiltVectorTy) { 749 // Nothing to do. 750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 751 // Bitconvert vector->vector case. 752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 753 } else { 754 if (BuiltVectorTy.getVectorElementType().bitsGT( 755 ValueVT.getVectorElementType())) { 756 // Integer promotion. 757 ValueVT = EVT::getVectorVT(*DAG.getContext(), 758 BuiltVectorTy.getVectorElementType(), 759 ValueVT.getVectorElementCount()); 760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 761 } 762 763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 764 Val = Widened; 765 } 766 } 767 768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 769 770 // Split the vector into intermediate operands. 771 SmallVector<SDValue, 8> Ops(NumIntermediates); 772 for (unsigned i = 0; i != NumIntermediates; ++i) { 773 if (IntermediateVT.isVector()) { 774 // This does something sensible for scalable vectors - see the 775 // definition of EXTRACT_SUBVECTOR for further details. 776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 777 Ops[i] = 778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 780 } else { 781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 782 DAG.getVectorIdxConstant(i, DL)); 783 } 784 } 785 786 // Split the intermediate operands into legal parts. 787 if (NumParts == NumIntermediates) { 788 // If the register was not expanded, promote or copy the value, 789 // as appropriate. 790 for (unsigned i = 0; i != NumParts; ++i) 791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 792 } else if (NumParts > 0) { 793 // If the intermediate type was expanded, split each the value into 794 // legal parts. 795 assert(NumIntermediates != 0 && "division by zero"); 796 assert(NumParts % NumIntermediates == 0 && 797 "Must expand into a divisible number of parts!"); 798 unsigned Factor = NumParts / NumIntermediates; 799 for (unsigned i = 0; i != NumIntermediates; ++i) 800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 801 CallConv); 802 } 803 } 804 805 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 806 EVT valuevt, std::optional<CallingConv::ID> CC) 807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 808 RegCount(1, regs.size()), CallConv(CC) {} 809 810 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 811 const DataLayout &DL, unsigned Reg, Type *Ty, 812 std::optional<CallingConv::ID> CC) { 813 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 814 815 CallConv = CC; 816 817 for (EVT ValueVT : ValueVTs) { 818 unsigned NumRegs = 819 isABIMangled() 820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 821 : TLI.getNumRegisters(Context, ValueVT); 822 MVT RegisterVT = 823 isABIMangled() 824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 825 : TLI.getRegisterType(Context, ValueVT); 826 for (unsigned i = 0; i != NumRegs; ++i) 827 Regs.push_back(Reg + i); 828 RegVTs.push_back(RegisterVT); 829 RegCount.push_back(NumRegs); 830 Reg += NumRegs; 831 } 832 } 833 834 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 835 FunctionLoweringInfo &FuncInfo, 836 const SDLoc &dl, SDValue &Chain, 837 SDValue *Glue, const Value *V) const { 838 // A Value with type {} or [0 x %t] needs no registers. 839 if (ValueVTs.empty()) 840 return SDValue(); 841 842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 843 844 // Assemble the legal parts into the final values. 845 SmallVector<SDValue, 4> Values(ValueVTs.size()); 846 SmallVector<SDValue, 8> Parts; 847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 848 // Copy the legal parts from the registers. 849 EVT ValueVT = ValueVTs[Value]; 850 unsigned NumRegs = RegCount[Value]; 851 MVT RegisterVT = isABIMangled() 852 ? TLI.getRegisterTypeForCallingConv( 853 *DAG.getContext(), *CallConv, RegVTs[Value]) 854 : RegVTs[Value]; 855 856 Parts.resize(NumRegs); 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 SDValue P; 859 if (!Glue) { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 861 } else { 862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 863 *Glue = P.getValue(2); 864 } 865 866 Chain = P.getValue(1); 867 Parts[i] = P; 868 869 // If the source register was virtual and if we know something about it, 870 // add an assert node. 871 if (!Register::isVirtualRegister(Regs[Part + i]) || 872 !RegisterVT.isInteger()) 873 continue; 874 875 const FunctionLoweringInfo::LiveOutInfo *LOI = 876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 877 if (!LOI) 878 continue; 879 880 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 881 unsigned NumSignBits = LOI->NumSignBits; 882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 883 884 if (NumZeroBits == RegSize) { 885 // The current value is a zero. 886 // Explicitly express that as it would be easier for 887 // optimizations to kick in. 888 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 889 continue; 890 } 891 892 // FIXME: We capture more information than the dag can represent. For 893 // now, just use the tightest assertzext/assertsext possible. 894 bool isSExt; 895 EVT FromVT(MVT::Other); 896 if (NumZeroBits) { 897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 898 isSExt = false; 899 } else if (NumSignBits > 1) { 900 FromVT = 901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 902 isSExt = true; 903 } else { 904 continue; 905 } 906 // Add an assertion node. 907 assert(FromVT != MVT::Other); 908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 909 RegisterVT, P, DAG.getValueType(FromVT)); 910 } 911 912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 913 RegisterVT, ValueVT, V, CallConv); 914 Part += NumRegs; 915 Parts.clear(); 916 } 917 918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 919 } 920 921 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 922 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 923 const Value *V, 924 ISD::NodeType PreferredExtendType) const { 925 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 926 ISD::NodeType ExtendKind = PreferredExtendType; 927 928 // Get the list of the values's legal parts. 929 unsigned NumRegs = Regs.size(); 930 SmallVector<SDValue, 8> Parts(NumRegs); 931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 932 unsigned NumParts = RegCount[Value]; 933 934 MVT RegisterVT = isABIMangled() 935 ? TLI.getRegisterTypeForCallingConv( 936 *DAG.getContext(), *CallConv, RegVTs[Value]) 937 : RegVTs[Value]; 938 939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 940 ExtendKind = ISD::ZERO_EXTEND; 941 942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 943 NumParts, RegisterVT, V, CallConv, ExtendKind); 944 Part += NumParts; 945 } 946 947 // Copy the parts into the registers. 948 SmallVector<SDValue, 8> Chains(NumRegs); 949 for (unsigned i = 0; i != NumRegs; ++i) { 950 SDValue Part; 951 if (!Glue) { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 953 } else { 954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 955 *Glue = Part.getValue(1); 956 } 957 958 Chains[i] = Part.getValue(0); 959 } 960 961 if (NumRegs == 1 || Glue) 962 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 963 // flagged to it. That is the CopyToReg nodes and the user are considered 964 // a single scheduling unit. If we create a TokenFactor and return it as 965 // chain, then the TokenFactor is both a predecessor (operand) of the 966 // user as well as a successor (the TF operands are flagged to the user). 967 // c1, f1 = CopyToReg 968 // c2, f2 = CopyToReg 969 // c3 = TokenFactor c1, c2 970 // ... 971 // = op c3, ..., f2 972 Chain = Chains[NumRegs-1]; 973 else 974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 975 } 976 977 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 978 unsigned MatchingIdx, const SDLoc &dl, 979 SelectionDAG &DAG, 980 std::vector<SDValue> &Ops) const { 981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 982 983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 984 if (HasMatching) 985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 987 // Put the register class of the virtual registers in the flag word. That 988 // way, later passes can recompute register class constraints for inline 989 // assembly as well as normal instructions. 990 // Don't do this for tied operands that can use the regclass information 991 // from the def. 992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 995 } 996 997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 998 Ops.push_back(Res); 999 1000 if (Code == InlineAsm::Kind_Clobber) { 1001 // Clobbers should always have a 1:1 mapping with registers, and may 1002 // reference registers that have illegal (e.g. vector) types. Hence, we 1003 // shouldn't try to apply any sort of splitting logic to them. 1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1005 "No 1:1 mapping from clobbers to regs?"); 1006 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1007 (void)SP; 1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1010 assert( 1011 (Regs[I] != SP || 1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1013 "If we clobbered the stack pointer, MFI should know about it."); 1014 } 1015 return; 1016 } 1017 1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1019 MVT RegisterVT = RegVTs[Value]; 1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1021 RegisterVT); 1022 for (unsigned i = 0; i != NumRegs; ++i) { 1023 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1024 unsigned TheReg = Regs[Reg++]; 1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1026 } 1027 } 1028 } 1029 1030 SmallVector<std::pair<unsigned, TypeSize>, 4> 1031 RegsForValue::getRegsAndSizes() const { 1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1033 unsigned I = 0; 1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1035 unsigned RegCount = std::get<0>(CountAndVT); 1036 MVT RegisterVT = std::get<1>(CountAndVT); 1037 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1038 for (unsigned E = I + RegCount; I != E; ++I) 1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1040 } 1041 return OutVec; 1042 } 1043 1044 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1045 AssumptionCache *ac, 1046 const TargetLibraryInfo *li) { 1047 AA = aa; 1048 AC = ac; 1049 GFI = gfi; 1050 LibInfo = li; 1051 Context = DAG.getContext(); 1052 LPadToCallSiteMap.clear(); 1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1054 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1055 *DAG.getMachineFunction().getFunction().getParent()); 1056 } 1057 1058 void SelectionDAGBuilder::clear() { 1059 NodeMap.clear(); 1060 UnusedArgNodeMap.clear(); 1061 PendingLoads.clear(); 1062 PendingExports.clear(); 1063 PendingConstrainedFP.clear(); 1064 PendingConstrainedFPStrict.clear(); 1065 CurInst = nullptr; 1066 HasTailCall = false; 1067 SDNodeOrder = LowestSDNodeOrder; 1068 StatepointLowering.clear(); 1069 } 1070 1071 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1072 DanglingDebugInfoMap.clear(); 1073 } 1074 1075 // Update DAG root to include dependencies on Pending chains. 1076 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1077 SDValue Root = DAG.getRoot(); 1078 1079 if (Pending.empty()) 1080 return Root; 1081 1082 // Add current root to PendingChains, unless we already indirectly 1083 // depend on it. 1084 if (Root.getOpcode() != ISD::EntryToken) { 1085 unsigned i = 0, e = Pending.size(); 1086 for (; i != e; ++i) { 1087 assert(Pending[i].getNode()->getNumOperands() > 1); 1088 if (Pending[i].getNode()->getOperand(0) == Root) 1089 break; // Don't add the root if we already indirectly depend on it. 1090 } 1091 1092 if (i == e) 1093 Pending.push_back(Root); 1094 } 1095 1096 if (Pending.size() == 1) 1097 Root = Pending[0]; 1098 else 1099 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1100 1101 DAG.setRoot(Root); 1102 Pending.clear(); 1103 return Root; 1104 } 1105 1106 SDValue SelectionDAGBuilder::getMemoryRoot() { 1107 return updateRoot(PendingLoads); 1108 } 1109 1110 SDValue SelectionDAGBuilder::getRoot() { 1111 // Chain up all pending constrained intrinsics together with all 1112 // pending loads, by simply appending them to PendingLoads and 1113 // then calling getMemoryRoot(). 1114 PendingLoads.reserve(PendingLoads.size() + 1115 PendingConstrainedFP.size() + 1116 PendingConstrainedFPStrict.size()); 1117 PendingLoads.append(PendingConstrainedFP.begin(), 1118 PendingConstrainedFP.end()); 1119 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1120 PendingConstrainedFPStrict.end()); 1121 PendingConstrainedFP.clear(); 1122 PendingConstrainedFPStrict.clear(); 1123 return getMemoryRoot(); 1124 } 1125 1126 SDValue SelectionDAGBuilder::getControlRoot() { 1127 // We need to emit pending fpexcept.strict constrained intrinsics, 1128 // so append them to the PendingExports list. 1129 PendingExports.append(PendingConstrainedFPStrict.begin(), 1130 PendingConstrainedFPStrict.end()); 1131 PendingConstrainedFPStrict.clear(); 1132 return updateRoot(PendingExports); 1133 } 1134 1135 void SelectionDAGBuilder::visit(const Instruction &I) { 1136 // Set up outgoing PHI node register values before emitting the terminator. 1137 if (I.isTerminator()) { 1138 HandlePHINodesInSuccessorBlocks(I.getParent()); 1139 } 1140 1141 // Add SDDbgValue nodes for any var locs here. Do so before updating 1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1143 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1144 // Add SDDbgValue nodes for any var locs here. Do so before updating 1145 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1146 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1147 It != End; ++It) { 1148 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1149 dropDanglingDebugInfo(Var, It->Expr); 1150 SmallVector<Value *> Values(It->Values.location_ops()); 1151 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1152 It->Values.hasArgList())) 1153 addDanglingDebugInfo(It, SDNodeOrder); 1154 } 1155 } 1156 1157 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1158 if (!isa<DbgInfoIntrinsic>(I)) 1159 ++SDNodeOrder; 1160 1161 CurInst = &I; 1162 1163 // Set inserted listener only if required. 1164 bool NodeInserted = false; 1165 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1166 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1167 if (PCSectionsMD) { 1168 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1169 DAG, [&](SDNode *) { NodeInserted = true; }); 1170 } 1171 1172 visit(I.getOpcode(), I); 1173 1174 if (!I.isTerminator() && !HasTailCall && 1175 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1176 CopyToExportRegsIfNeeded(&I); 1177 1178 // Handle metadata. 1179 if (PCSectionsMD) { 1180 auto It = NodeMap.find(&I); 1181 if (It != NodeMap.end()) { 1182 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1183 } else if (NodeInserted) { 1184 // This should not happen; if it does, don't let it go unnoticed so we can 1185 // fix it. Relevant visit*() function is probably missing a setValue(). 1186 errs() << "warning: loosing !pcsections metadata [" 1187 << I.getModule()->getName() << "]\n"; 1188 LLVM_DEBUG(I.dump()); 1189 assert(false); 1190 } 1191 } 1192 1193 CurInst = nullptr; 1194 } 1195 1196 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1197 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1198 } 1199 1200 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1201 // Note: this doesn't use InstVisitor, because it has to work with 1202 // ConstantExpr's in addition to instructions. 1203 switch (Opcode) { 1204 default: llvm_unreachable("Unknown instruction type encountered!"); 1205 // Build the switch statement using the Instruction.def file. 1206 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1207 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1208 #include "llvm/IR/Instruction.def" 1209 } 1210 } 1211 1212 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1213 DILocalVariable *Variable, 1214 DebugLoc DL, unsigned Order, 1215 RawLocationWrapper Values, 1216 DIExpression *Expression) { 1217 if (!Values.hasArgList()) 1218 return false; 1219 // For variadic dbg_values we will now insert an undef. 1220 // FIXME: We can potentially recover these! 1221 SmallVector<SDDbgOperand, 2> Locs; 1222 for (const Value *V : Values.location_ops()) { 1223 auto *Undef = UndefValue::get(V->getType()); 1224 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1225 } 1226 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1227 /*IsIndirect=*/false, DL, Order, 1228 /*IsVariadic=*/true); 1229 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1230 return true; 1231 } 1232 1233 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1234 unsigned Order) { 1235 if (!handleDanglingVariadicDebugInfo( 1236 DAG, 1237 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1238 ->getVariable(VarLoc->VariableID) 1239 .getVariable()), 1240 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1241 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1242 VarLoc, Order); 1243 } 1244 } 1245 1246 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1247 unsigned Order) { 1248 // We treat variadic dbg_values differently at this stage. 1249 if (!handleDanglingVariadicDebugInfo( 1250 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1251 DI->getWrappedLocation(), DI->getExpression())) { 1252 // TODO: Dangling debug info will eventually either be resolved or produce 1253 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1254 // between the original dbg.value location and its resolved DBG_VALUE, 1255 // which we should ideally fill with an extra Undef DBG_VALUE. 1256 assert(DI->getNumVariableLocationOps() == 1 && 1257 "DbgValueInst without an ArgList should have a single location " 1258 "operand."); 1259 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1260 } 1261 } 1262 1263 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1264 const DIExpression *Expr) { 1265 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1266 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1267 DIExpression *DanglingExpr = DDI.getExpression(); 1268 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1269 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1270 << "\n"); 1271 return true; 1272 } 1273 return false; 1274 }; 1275 1276 for (auto &DDIMI : DanglingDebugInfoMap) { 1277 DanglingDebugInfoVector &DDIV = DDIMI.second; 1278 1279 // If debug info is to be dropped, run it through final checks to see 1280 // whether it can be salvaged. 1281 for (auto &DDI : DDIV) 1282 if (isMatchingDbgValue(DDI)) 1283 salvageUnresolvedDbgValue(DDI); 1284 1285 erase_if(DDIV, isMatchingDbgValue); 1286 } 1287 } 1288 1289 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1290 // generate the debug data structures now that we've seen its definition. 1291 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1292 SDValue Val) { 1293 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1294 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1295 return; 1296 1297 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1298 for (auto &DDI : DDIV) { 1299 DebugLoc DL = DDI.getDebugLoc(); 1300 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1301 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1302 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1303 DIExpression *Expr = DDI.getExpression(); 1304 assert(Variable->isValidLocationForIntrinsic(DL) && 1305 "Expected inlined-at fields to agree"); 1306 SDDbgValue *SDV; 1307 if (Val.getNode()) { 1308 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1309 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1310 // we couldn't resolve it directly when examining the DbgValue intrinsic 1311 // in the first place we should not be more successful here). Unless we 1312 // have some test case that prove this to be correct we should avoid 1313 // calling EmitFuncArgumentDbgValue here. 1314 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1315 FuncArgumentDbgValueKind::Value, Val)) { 1316 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1317 << "\n"); 1318 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1319 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1320 // inserted after the definition of Val when emitting the instructions 1321 // after ISel. An alternative could be to teach 1322 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1323 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1324 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1325 << ValSDNodeOrder << "\n"); 1326 SDV = getDbgValue(Val, Variable, Expr, DL, 1327 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1328 DAG.AddDbgValue(SDV, false); 1329 } else 1330 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1331 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1332 } else { 1333 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1334 auto Undef = UndefValue::get(V->getType()); 1335 auto SDV = 1336 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1337 DAG.AddDbgValue(SDV, false); 1338 } 1339 } 1340 DDIV.clear(); 1341 } 1342 1343 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1344 // TODO: For the variadic implementation, instead of only checking the fail 1345 // state of `handleDebugValue`, we need know specifically which values were 1346 // invalid, so that we attempt to salvage only those values when processing 1347 // a DIArgList. 1348 Value *V = DDI.getVariableLocationOp(0); 1349 Value *OrigV = V; 1350 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1351 DIExpression *Expr = DDI.getExpression(); 1352 DebugLoc DL = DDI.getDebugLoc(); 1353 unsigned SDOrder = DDI.getSDNodeOrder(); 1354 1355 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1356 // that DW_OP_stack_value is desired. 1357 bool StackValue = true; 1358 1359 // Can this Value can be encoded without any further work? 1360 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1361 return; 1362 1363 // Attempt to salvage back through as many instructions as possible. Bail if 1364 // a non-instruction is seen, such as a constant expression or global 1365 // variable. FIXME: Further work could recover those too. 1366 while (isa<Instruction>(V)) { 1367 Instruction &VAsInst = *cast<Instruction>(V); 1368 // Temporary "0", awaiting real implementation. 1369 SmallVector<uint64_t, 16> Ops; 1370 SmallVector<Value *, 4> AdditionalValues; 1371 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1372 AdditionalValues); 1373 // If we cannot salvage any further, and haven't yet found a suitable debug 1374 // expression, bail out. 1375 if (!V) 1376 break; 1377 1378 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1379 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1380 // here for variadic dbg_values, remove that condition. 1381 if (!AdditionalValues.empty()) 1382 break; 1383 1384 // New value and expr now represent this debuginfo. 1385 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1386 1387 // Some kind of simplification occurred: check whether the operand of the 1388 // salvaged debug expression can be encoded in this DAG. 1389 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1390 LLVM_DEBUG( 1391 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1392 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1393 return; 1394 } 1395 } 1396 1397 // This was the final opportunity to salvage this debug information, and it 1398 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1399 // any earlier variable location. 1400 assert(OrigV && "V shouldn't be null"); 1401 auto *Undef = UndefValue::get(OrigV->getType()); 1402 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1403 DAG.AddDbgValue(SDV, false); 1404 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1405 << "\n"); 1406 } 1407 1408 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1409 DILocalVariable *Var, 1410 DIExpression *Expr, DebugLoc DbgLoc, 1411 unsigned Order, bool IsVariadic) { 1412 if (Values.empty()) 1413 return true; 1414 SmallVector<SDDbgOperand> LocationOps; 1415 SmallVector<SDNode *> Dependencies; 1416 for (const Value *V : Values) { 1417 // Constant value. 1418 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1419 isa<ConstantPointerNull>(V)) { 1420 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1421 continue; 1422 } 1423 1424 // Look through IntToPtr constants. 1425 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1426 if (CE->getOpcode() == Instruction::IntToPtr) { 1427 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1428 continue; 1429 } 1430 1431 // If the Value is a frame index, we can create a FrameIndex debug value 1432 // without relying on the DAG at all. 1433 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1434 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1435 if (SI != FuncInfo.StaticAllocaMap.end()) { 1436 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1437 continue; 1438 } 1439 } 1440 1441 // Do not use getValue() in here; we don't want to generate code at 1442 // this point if it hasn't been done yet. 1443 SDValue N = NodeMap[V]; 1444 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1445 N = UnusedArgNodeMap[V]; 1446 if (N.getNode()) { 1447 // Only emit func arg dbg value for non-variadic dbg.values for now. 1448 if (!IsVariadic && 1449 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1450 FuncArgumentDbgValueKind::Value, N)) 1451 return true; 1452 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1453 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1454 // describe stack slot locations. 1455 // 1456 // Consider "int x = 0; int *px = &x;". There are two kinds of 1457 // interesting debug values here after optimization: 1458 // 1459 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1460 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1461 // 1462 // Both describe the direct values of their associated variables. 1463 Dependencies.push_back(N.getNode()); 1464 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1465 continue; 1466 } 1467 LocationOps.emplace_back( 1468 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1469 continue; 1470 } 1471 1472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1473 // Special rules apply for the first dbg.values of parameter variables in a 1474 // function. Identify them by the fact they reference Argument Values, that 1475 // they're parameters, and they are parameters of the current function. We 1476 // need to let them dangle until they get an SDNode. 1477 bool IsParamOfFunc = 1478 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1479 if (IsParamOfFunc) 1480 return false; 1481 1482 // The value is not used in this block yet (or it would have an SDNode). 1483 // We still want the value to appear for the user if possible -- if it has 1484 // an associated VReg, we can refer to that instead. 1485 auto VMI = FuncInfo.ValueMap.find(V); 1486 if (VMI != FuncInfo.ValueMap.end()) { 1487 unsigned Reg = VMI->second; 1488 // If this is a PHI node, it may be split up into several MI PHI nodes 1489 // (in FunctionLoweringInfo::set). 1490 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1491 V->getType(), std::nullopt); 1492 if (RFV.occupiesMultipleRegs()) { 1493 // FIXME: We could potentially support variadic dbg_values here. 1494 if (IsVariadic) 1495 return false; 1496 unsigned Offset = 0; 1497 unsigned BitsToDescribe = 0; 1498 if (auto VarSize = Var->getSizeInBits()) 1499 BitsToDescribe = *VarSize; 1500 if (auto Fragment = Expr->getFragmentInfo()) 1501 BitsToDescribe = Fragment->SizeInBits; 1502 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1503 // Bail out if all bits are described already. 1504 if (Offset >= BitsToDescribe) 1505 break; 1506 // TODO: handle scalable vectors. 1507 unsigned RegisterSize = RegAndSize.second; 1508 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1509 ? BitsToDescribe - Offset 1510 : RegisterSize; 1511 auto FragmentExpr = DIExpression::createFragmentExpression( 1512 Expr, Offset, FragmentSize); 1513 if (!FragmentExpr) 1514 continue; 1515 SDDbgValue *SDV = DAG.getVRegDbgValue( 1516 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1517 DAG.AddDbgValue(SDV, false); 1518 Offset += RegisterSize; 1519 } 1520 return true; 1521 } 1522 // We can use simple vreg locations for variadic dbg_values as well. 1523 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1524 continue; 1525 } 1526 // We failed to create a SDDbgOperand for V. 1527 return false; 1528 } 1529 1530 // We have created a SDDbgOperand for each Value in Values. 1531 // Should use Order instead of SDNodeOrder? 1532 assert(!LocationOps.empty()); 1533 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1534 /*IsIndirect=*/false, DbgLoc, 1535 SDNodeOrder, IsVariadic); 1536 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1537 return true; 1538 } 1539 1540 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1541 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1542 for (auto &Pair : DanglingDebugInfoMap) 1543 for (auto &DDI : Pair.second) 1544 salvageUnresolvedDbgValue(DDI); 1545 clearDanglingDebugInfo(); 1546 } 1547 1548 /// getCopyFromRegs - If there was virtual register allocated for the value V 1549 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1550 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1551 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1552 SDValue Result; 1553 1554 if (It != FuncInfo.ValueMap.end()) { 1555 Register InReg = It->second; 1556 1557 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1558 DAG.getDataLayout(), InReg, Ty, 1559 std::nullopt); // This is not an ABI copy. 1560 SDValue Chain = DAG.getEntryNode(); 1561 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1562 V); 1563 resolveDanglingDebugInfo(V, Result); 1564 } 1565 1566 return Result; 1567 } 1568 1569 /// getValue - Return an SDValue for the given Value. 1570 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1571 // If we already have an SDValue for this value, use it. It's important 1572 // to do this first, so that we don't create a CopyFromReg if we already 1573 // have a regular SDValue. 1574 SDValue &N = NodeMap[V]; 1575 if (N.getNode()) return N; 1576 1577 // If there's a virtual register allocated and initialized for this 1578 // value, use it. 1579 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1580 return copyFromReg; 1581 1582 // Otherwise create a new SDValue and remember it. 1583 SDValue Val = getValueImpl(V); 1584 NodeMap[V] = Val; 1585 resolveDanglingDebugInfo(V, Val); 1586 return Val; 1587 } 1588 1589 /// getNonRegisterValue - Return an SDValue for the given Value, but 1590 /// don't look in FuncInfo.ValueMap for a virtual register. 1591 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1592 // If we already have an SDValue for this value, use it. 1593 SDValue &N = NodeMap[V]; 1594 if (N.getNode()) { 1595 if (isIntOrFPConstant(N)) { 1596 // Remove the debug location from the node as the node is about to be used 1597 // in a location which may differ from the original debug location. This 1598 // is relevant to Constant and ConstantFP nodes because they can appear 1599 // as constant expressions inside PHI nodes. 1600 N->setDebugLoc(DebugLoc()); 1601 } 1602 return N; 1603 } 1604 1605 // Otherwise create a new SDValue and remember it. 1606 SDValue Val = getValueImpl(V); 1607 NodeMap[V] = Val; 1608 resolveDanglingDebugInfo(V, Val); 1609 return Val; 1610 } 1611 1612 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1613 /// Create an SDValue for the given value. 1614 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1616 1617 if (const Constant *C = dyn_cast<Constant>(V)) { 1618 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1619 1620 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1621 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1622 1623 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1624 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1625 1626 if (isa<ConstantPointerNull>(C)) { 1627 unsigned AS = V->getType()->getPointerAddressSpace(); 1628 return DAG.getConstant(0, getCurSDLoc(), 1629 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1630 } 1631 1632 if (match(C, m_VScale())) 1633 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1634 1635 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1636 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1637 1638 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1639 return DAG.getUNDEF(VT); 1640 1641 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1642 visit(CE->getOpcode(), *CE); 1643 SDValue N1 = NodeMap[V]; 1644 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1645 return N1; 1646 } 1647 1648 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1649 SmallVector<SDValue, 4> Constants; 1650 for (const Use &U : C->operands()) { 1651 SDNode *Val = getValue(U).getNode(); 1652 // If the operand is an empty aggregate, there are no values. 1653 if (!Val) continue; 1654 // Add each leaf value from the operand to the Constants list 1655 // to form a flattened list of all the values. 1656 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1657 Constants.push_back(SDValue(Val, i)); 1658 } 1659 1660 return DAG.getMergeValues(Constants, getCurSDLoc()); 1661 } 1662 1663 if (const ConstantDataSequential *CDS = 1664 dyn_cast<ConstantDataSequential>(C)) { 1665 SmallVector<SDValue, 4> Ops; 1666 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1667 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1668 // Add each leaf value from the operand to the Constants list 1669 // to form a flattened list of all the values. 1670 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1671 Ops.push_back(SDValue(Val, i)); 1672 } 1673 1674 if (isa<ArrayType>(CDS->getType())) 1675 return DAG.getMergeValues(Ops, getCurSDLoc()); 1676 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1677 } 1678 1679 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1680 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1681 "Unknown struct or array constant!"); 1682 1683 SmallVector<EVT, 4> ValueVTs; 1684 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1685 unsigned NumElts = ValueVTs.size(); 1686 if (NumElts == 0) 1687 return SDValue(); // empty struct 1688 SmallVector<SDValue, 4> Constants(NumElts); 1689 for (unsigned i = 0; i != NumElts; ++i) { 1690 EVT EltVT = ValueVTs[i]; 1691 if (isa<UndefValue>(C)) 1692 Constants[i] = DAG.getUNDEF(EltVT); 1693 else if (EltVT.isFloatingPoint()) 1694 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1695 else 1696 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1697 } 1698 1699 return DAG.getMergeValues(Constants, getCurSDLoc()); 1700 } 1701 1702 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1703 return DAG.getBlockAddress(BA, VT); 1704 1705 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1706 return getValue(Equiv->getGlobalValue()); 1707 1708 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1709 return getValue(NC->getGlobalValue()); 1710 1711 VectorType *VecTy = cast<VectorType>(V->getType()); 1712 1713 // Now that we know the number and type of the elements, get that number of 1714 // elements into the Ops array based on what kind of constant it is. 1715 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1716 SmallVector<SDValue, 16> Ops; 1717 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1718 for (unsigned i = 0; i != NumElements; ++i) 1719 Ops.push_back(getValue(CV->getOperand(i))); 1720 1721 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1722 } 1723 1724 if (isa<ConstantAggregateZero>(C)) { 1725 EVT EltVT = 1726 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1727 1728 SDValue Op; 1729 if (EltVT.isFloatingPoint()) 1730 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1731 else 1732 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1733 1734 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1735 } 1736 1737 llvm_unreachable("Unknown vector constant"); 1738 } 1739 1740 // If this is a static alloca, generate it as the frameindex instead of 1741 // computation. 1742 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1743 DenseMap<const AllocaInst*, int>::iterator SI = 1744 FuncInfo.StaticAllocaMap.find(AI); 1745 if (SI != FuncInfo.StaticAllocaMap.end()) 1746 return DAG.getFrameIndex( 1747 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1748 } 1749 1750 // If this is an instruction which fast-isel has deferred, select it now. 1751 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1752 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1753 1754 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1755 Inst->getType(), std::nullopt); 1756 SDValue Chain = DAG.getEntryNode(); 1757 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1758 } 1759 1760 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1761 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1762 1763 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1764 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1765 1766 llvm_unreachable("Can't get register for value!"); 1767 } 1768 1769 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1770 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1771 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1772 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1773 bool IsSEH = isAsynchronousEHPersonality(Pers); 1774 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1775 if (!IsSEH) 1776 CatchPadMBB->setIsEHScopeEntry(); 1777 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1778 if (IsMSVCCXX || IsCoreCLR) 1779 CatchPadMBB->setIsEHFuncletEntry(); 1780 } 1781 1782 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1783 // Update machine-CFG edge. 1784 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1785 FuncInfo.MBB->addSuccessor(TargetMBB); 1786 TargetMBB->setIsEHCatchretTarget(true); 1787 DAG.getMachineFunction().setHasEHCatchret(true); 1788 1789 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1790 bool IsSEH = isAsynchronousEHPersonality(Pers); 1791 if (IsSEH) { 1792 // If this is not a fall-through branch or optimizations are switched off, 1793 // emit the branch. 1794 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1795 TM.getOptLevel() == CodeGenOpt::None) 1796 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1797 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1798 return; 1799 } 1800 1801 // Figure out the funclet membership for the catchret's successor. 1802 // This will be used by the FuncletLayout pass to determine how to order the 1803 // BB's. 1804 // A 'catchret' returns to the outer scope's color. 1805 Value *ParentPad = I.getCatchSwitchParentPad(); 1806 const BasicBlock *SuccessorColor; 1807 if (isa<ConstantTokenNone>(ParentPad)) 1808 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1809 else 1810 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1811 assert(SuccessorColor && "No parent funclet for catchret!"); 1812 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1813 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1814 1815 // Create the terminator node. 1816 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1817 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1818 DAG.getBasicBlock(SuccessorColorMBB)); 1819 DAG.setRoot(Ret); 1820 } 1821 1822 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1823 // Don't emit any special code for the cleanuppad instruction. It just marks 1824 // the start of an EH scope/funclet. 1825 FuncInfo.MBB->setIsEHScopeEntry(); 1826 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1827 if (Pers != EHPersonality::Wasm_CXX) { 1828 FuncInfo.MBB->setIsEHFuncletEntry(); 1829 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1830 } 1831 } 1832 1833 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1834 // not match, it is OK to add only the first unwind destination catchpad to the 1835 // successors, because there will be at least one invoke instruction within the 1836 // catch scope that points to the next unwind destination, if one exists, so 1837 // CFGSort cannot mess up with BB sorting order. 1838 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1839 // call within them, and catchpads only consisting of 'catch (...)' have a 1840 // '__cxa_end_catch' call within them, both of which generate invokes in case 1841 // the next unwind destination exists, i.e., the next unwind destination is not 1842 // the caller.) 1843 // 1844 // Having at most one EH pad successor is also simpler and helps later 1845 // transformations. 1846 // 1847 // For example, 1848 // current: 1849 // invoke void @foo to ... unwind label %catch.dispatch 1850 // catch.dispatch: 1851 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1852 // catch.start: 1853 // ... 1854 // ... in this BB or some other child BB dominated by this BB there will be an 1855 // invoke that points to 'next' BB as an unwind destination 1856 // 1857 // next: ; We don't need to add this to 'current' BB's successor 1858 // ... 1859 static void findWasmUnwindDestinations( 1860 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1861 BranchProbability Prob, 1862 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1863 &UnwindDests) { 1864 while (EHPadBB) { 1865 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1866 if (isa<CleanupPadInst>(Pad)) { 1867 // Stop on cleanup pads. 1868 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1869 UnwindDests.back().first->setIsEHScopeEntry(); 1870 break; 1871 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1872 // Add the catchpad handlers to the possible destinations. We don't 1873 // continue to the unwind destination of the catchswitch for wasm. 1874 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1875 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1876 UnwindDests.back().first->setIsEHScopeEntry(); 1877 } 1878 break; 1879 } else { 1880 continue; 1881 } 1882 } 1883 } 1884 1885 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1886 /// many places it could ultimately go. In the IR, we have a single unwind 1887 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1888 /// This function skips over imaginary basic blocks that hold catchswitch 1889 /// instructions, and finds all the "real" machine 1890 /// basic block destinations. As those destinations may not be successors of 1891 /// EHPadBB, here we also calculate the edge probability to those destinations. 1892 /// The passed-in Prob is the edge probability to EHPadBB. 1893 static void findUnwindDestinations( 1894 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1895 BranchProbability Prob, 1896 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1897 &UnwindDests) { 1898 EHPersonality Personality = 1899 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1900 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1901 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1902 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1903 bool IsSEH = isAsynchronousEHPersonality(Personality); 1904 1905 if (IsWasmCXX) { 1906 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1907 assert(UnwindDests.size() <= 1 && 1908 "There should be at most one unwind destination for wasm"); 1909 return; 1910 } 1911 1912 while (EHPadBB) { 1913 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1914 BasicBlock *NewEHPadBB = nullptr; 1915 if (isa<LandingPadInst>(Pad)) { 1916 // Stop on landingpads. They are not funclets. 1917 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1918 break; 1919 } else if (isa<CleanupPadInst>(Pad)) { 1920 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1921 // personalities. 1922 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1923 UnwindDests.back().first->setIsEHScopeEntry(); 1924 UnwindDests.back().first->setIsEHFuncletEntry(); 1925 break; 1926 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1927 // Add the catchpad handlers to the possible destinations. 1928 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1929 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1930 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1931 if (IsMSVCCXX || IsCoreCLR) 1932 UnwindDests.back().first->setIsEHFuncletEntry(); 1933 if (!IsSEH) 1934 UnwindDests.back().first->setIsEHScopeEntry(); 1935 } 1936 NewEHPadBB = CatchSwitch->getUnwindDest(); 1937 } else { 1938 continue; 1939 } 1940 1941 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1942 if (BPI && NewEHPadBB) 1943 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1944 EHPadBB = NewEHPadBB; 1945 } 1946 } 1947 1948 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1949 // Update successor info. 1950 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1951 auto UnwindDest = I.getUnwindDest(); 1952 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1953 BranchProbability UnwindDestProb = 1954 (BPI && UnwindDest) 1955 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1956 : BranchProbability::getZero(); 1957 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1958 for (auto &UnwindDest : UnwindDests) { 1959 UnwindDest.first->setIsEHPad(); 1960 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1961 } 1962 FuncInfo.MBB->normalizeSuccProbs(); 1963 1964 // Create the terminator node. 1965 SDValue Ret = 1966 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1967 DAG.setRoot(Ret); 1968 } 1969 1970 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1971 report_fatal_error("visitCatchSwitch not yet implemented!"); 1972 } 1973 1974 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1975 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1976 auto &DL = DAG.getDataLayout(); 1977 SDValue Chain = getControlRoot(); 1978 SmallVector<ISD::OutputArg, 8> Outs; 1979 SmallVector<SDValue, 8> OutVals; 1980 1981 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1982 // lower 1983 // 1984 // %val = call <ty> @llvm.experimental.deoptimize() 1985 // ret <ty> %val 1986 // 1987 // differently. 1988 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1989 LowerDeoptimizingReturn(); 1990 return; 1991 } 1992 1993 if (!FuncInfo.CanLowerReturn) { 1994 unsigned DemoteReg = FuncInfo.DemoteRegister; 1995 const Function *F = I.getParent()->getParent(); 1996 1997 // Emit a store of the return value through the virtual register. 1998 // Leave Outs empty so that LowerReturn won't try to load return 1999 // registers the usual way. 2000 SmallVector<EVT, 1> PtrValueVTs; 2001 ComputeValueVTs(TLI, DL, 2002 F->getReturnType()->getPointerTo( 2003 DAG.getDataLayout().getAllocaAddrSpace()), 2004 PtrValueVTs); 2005 2006 SDValue RetPtr = 2007 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2008 SDValue RetOp = getValue(I.getOperand(0)); 2009 2010 SmallVector<EVT, 4> ValueVTs, MemVTs; 2011 SmallVector<uint64_t, 4> Offsets; 2012 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2013 &Offsets); 2014 unsigned NumValues = ValueVTs.size(); 2015 2016 SmallVector<SDValue, 4> Chains(NumValues); 2017 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2018 for (unsigned i = 0; i != NumValues; ++i) { 2019 // An aggregate return value cannot wrap around the address space, so 2020 // offsets to its parts don't wrap either. 2021 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2022 TypeSize::Fixed(Offsets[i])); 2023 2024 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2025 if (MemVTs[i] != ValueVTs[i]) 2026 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2027 Chains[i] = DAG.getStore( 2028 Chain, getCurSDLoc(), Val, 2029 // FIXME: better loc info would be nice. 2030 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2031 commonAlignment(BaseAlign, Offsets[i])); 2032 } 2033 2034 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2035 MVT::Other, Chains); 2036 } else if (I.getNumOperands() != 0) { 2037 SmallVector<EVT, 4> ValueVTs; 2038 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2039 unsigned NumValues = ValueVTs.size(); 2040 if (NumValues) { 2041 SDValue RetOp = getValue(I.getOperand(0)); 2042 2043 const Function *F = I.getParent()->getParent(); 2044 2045 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2046 I.getOperand(0)->getType(), F->getCallingConv(), 2047 /*IsVarArg*/ false, DL); 2048 2049 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2050 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2051 ExtendKind = ISD::SIGN_EXTEND; 2052 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2053 ExtendKind = ISD::ZERO_EXTEND; 2054 2055 LLVMContext &Context = F->getContext(); 2056 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2057 2058 for (unsigned j = 0; j != NumValues; ++j) { 2059 EVT VT = ValueVTs[j]; 2060 2061 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2062 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2063 2064 CallingConv::ID CC = F->getCallingConv(); 2065 2066 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2067 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2068 SmallVector<SDValue, 4> Parts(NumParts); 2069 getCopyToParts(DAG, getCurSDLoc(), 2070 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2071 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2072 2073 // 'inreg' on function refers to return value 2074 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2075 if (RetInReg) 2076 Flags.setInReg(); 2077 2078 if (I.getOperand(0)->getType()->isPointerTy()) { 2079 Flags.setPointer(); 2080 Flags.setPointerAddrSpace( 2081 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2082 } 2083 2084 if (NeedsRegBlock) { 2085 Flags.setInConsecutiveRegs(); 2086 if (j == NumValues - 1) 2087 Flags.setInConsecutiveRegsLast(); 2088 } 2089 2090 // Propagate extension type if any 2091 if (ExtendKind == ISD::SIGN_EXTEND) 2092 Flags.setSExt(); 2093 else if (ExtendKind == ISD::ZERO_EXTEND) 2094 Flags.setZExt(); 2095 2096 for (unsigned i = 0; i < NumParts; ++i) { 2097 Outs.push_back(ISD::OutputArg(Flags, 2098 Parts[i].getValueType().getSimpleVT(), 2099 VT, /*isfixed=*/true, 0, 0)); 2100 OutVals.push_back(Parts[i]); 2101 } 2102 } 2103 } 2104 } 2105 2106 // Push in swifterror virtual register as the last element of Outs. This makes 2107 // sure swifterror virtual register will be returned in the swifterror 2108 // physical register. 2109 const Function *F = I.getParent()->getParent(); 2110 if (TLI.supportSwiftError() && 2111 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2112 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2113 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2114 Flags.setSwiftError(); 2115 Outs.push_back(ISD::OutputArg( 2116 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2117 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2118 // Create SDNode for the swifterror virtual register. 2119 OutVals.push_back( 2120 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2121 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2122 EVT(TLI.getPointerTy(DL)))); 2123 } 2124 2125 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2126 CallingConv::ID CallConv = 2127 DAG.getMachineFunction().getFunction().getCallingConv(); 2128 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2129 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2130 2131 // Verify that the target's LowerReturn behaved as expected. 2132 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2133 "LowerReturn didn't return a valid chain!"); 2134 2135 // Update the DAG with the new chain value resulting from return lowering. 2136 DAG.setRoot(Chain); 2137 } 2138 2139 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2140 /// created for it, emit nodes to copy the value into the virtual 2141 /// registers. 2142 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2143 // Skip empty types 2144 if (V->getType()->isEmptyTy()) 2145 return; 2146 2147 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2148 if (VMI != FuncInfo.ValueMap.end()) { 2149 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2150 "Unused value assigned virtual registers!"); 2151 CopyValueToVirtualRegister(V, VMI->second); 2152 } 2153 } 2154 2155 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2156 /// the current basic block, add it to ValueMap now so that we'll get a 2157 /// CopyTo/FromReg. 2158 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2159 // No need to export constants. 2160 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2161 2162 // Already exported? 2163 if (FuncInfo.isExportedInst(V)) return; 2164 2165 Register Reg = FuncInfo.InitializeRegForValue(V); 2166 CopyValueToVirtualRegister(V, Reg); 2167 } 2168 2169 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2170 const BasicBlock *FromBB) { 2171 // The operands of the setcc have to be in this block. We don't know 2172 // how to export them from some other block. 2173 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2174 // Can export from current BB. 2175 if (VI->getParent() == FromBB) 2176 return true; 2177 2178 // Is already exported, noop. 2179 return FuncInfo.isExportedInst(V); 2180 } 2181 2182 // If this is an argument, we can export it if the BB is the entry block or 2183 // if it is already exported. 2184 if (isa<Argument>(V)) { 2185 if (FromBB->isEntryBlock()) 2186 return true; 2187 2188 // Otherwise, can only export this if it is already exported. 2189 return FuncInfo.isExportedInst(V); 2190 } 2191 2192 // Otherwise, constants can always be exported. 2193 return true; 2194 } 2195 2196 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2197 BranchProbability 2198 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2199 const MachineBasicBlock *Dst) const { 2200 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2201 const BasicBlock *SrcBB = Src->getBasicBlock(); 2202 const BasicBlock *DstBB = Dst->getBasicBlock(); 2203 if (!BPI) { 2204 // If BPI is not available, set the default probability as 1 / N, where N is 2205 // the number of successors. 2206 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2207 return BranchProbability(1, SuccSize); 2208 } 2209 return BPI->getEdgeProbability(SrcBB, DstBB); 2210 } 2211 2212 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2213 MachineBasicBlock *Dst, 2214 BranchProbability Prob) { 2215 if (!FuncInfo.BPI) 2216 Src->addSuccessorWithoutProb(Dst); 2217 else { 2218 if (Prob.isUnknown()) 2219 Prob = getEdgeProbability(Src, Dst); 2220 Src->addSuccessor(Dst, Prob); 2221 } 2222 } 2223 2224 static bool InBlock(const Value *V, const BasicBlock *BB) { 2225 if (const Instruction *I = dyn_cast<Instruction>(V)) 2226 return I->getParent() == BB; 2227 return true; 2228 } 2229 2230 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2231 /// This function emits a branch and is used at the leaves of an OR or an 2232 /// AND operator tree. 2233 void 2234 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2235 MachineBasicBlock *TBB, 2236 MachineBasicBlock *FBB, 2237 MachineBasicBlock *CurBB, 2238 MachineBasicBlock *SwitchBB, 2239 BranchProbability TProb, 2240 BranchProbability FProb, 2241 bool InvertCond) { 2242 const BasicBlock *BB = CurBB->getBasicBlock(); 2243 2244 // If the leaf of the tree is a comparison, merge the condition into 2245 // the caseblock. 2246 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2247 // The operands of the cmp have to be in this block. We don't know 2248 // how to export them from some other block. If this is the first block 2249 // of the sequence, no exporting is needed. 2250 if (CurBB == SwitchBB || 2251 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2252 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2253 ISD::CondCode Condition; 2254 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2255 ICmpInst::Predicate Pred = 2256 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2257 Condition = getICmpCondCode(Pred); 2258 } else { 2259 const FCmpInst *FC = cast<FCmpInst>(Cond); 2260 FCmpInst::Predicate Pred = 2261 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2262 Condition = getFCmpCondCode(Pred); 2263 if (TM.Options.NoNaNsFPMath) 2264 Condition = getFCmpCodeWithoutNaN(Condition); 2265 } 2266 2267 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2268 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2269 SL->SwitchCases.push_back(CB); 2270 return; 2271 } 2272 } 2273 2274 // Create a CaseBlock record representing this branch. 2275 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2276 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2277 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2278 SL->SwitchCases.push_back(CB); 2279 } 2280 2281 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2282 MachineBasicBlock *TBB, 2283 MachineBasicBlock *FBB, 2284 MachineBasicBlock *CurBB, 2285 MachineBasicBlock *SwitchBB, 2286 Instruction::BinaryOps Opc, 2287 BranchProbability TProb, 2288 BranchProbability FProb, 2289 bool InvertCond) { 2290 // Skip over not part of the tree and remember to invert op and operands at 2291 // next level. 2292 Value *NotCond; 2293 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2294 InBlock(NotCond, CurBB->getBasicBlock())) { 2295 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2296 !InvertCond); 2297 return; 2298 } 2299 2300 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2301 const Value *BOpOp0, *BOpOp1; 2302 // Compute the effective opcode for Cond, taking into account whether it needs 2303 // to be inverted, e.g. 2304 // and (not (or A, B)), C 2305 // gets lowered as 2306 // and (and (not A, not B), C) 2307 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2308 if (BOp) { 2309 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2310 ? Instruction::And 2311 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2312 ? Instruction::Or 2313 : (Instruction::BinaryOps)0); 2314 if (InvertCond) { 2315 if (BOpc == Instruction::And) 2316 BOpc = Instruction::Or; 2317 else if (BOpc == Instruction::Or) 2318 BOpc = Instruction::And; 2319 } 2320 } 2321 2322 // If this node is not part of the or/and tree, emit it as a branch. 2323 // Note that all nodes in the tree should have same opcode. 2324 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2325 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2326 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2327 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2328 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2329 TProb, FProb, InvertCond); 2330 return; 2331 } 2332 2333 // Create TmpBB after CurBB. 2334 MachineFunction::iterator BBI(CurBB); 2335 MachineFunction &MF = DAG.getMachineFunction(); 2336 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2337 CurBB->getParent()->insert(++BBI, TmpBB); 2338 2339 if (Opc == Instruction::Or) { 2340 // Codegen X | Y as: 2341 // BB1: 2342 // jmp_if_X TBB 2343 // jmp TmpBB 2344 // TmpBB: 2345 // jmp_if_Y TBB 2346 // jmp FBB 2347 // 2348 2349 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2350 // The requirement is that 2351 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2352 // = TrueProb for original BB. 2353 // Assuming the original probabilities are A and B, one choice is to set 2354 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2355 // A/(1+B) and 2B/(1+B). This choice assumes that 2356 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2357 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2358 // TmpBB, but the math is more complicated. 2359 2360 auto NewTrueProb = TProb / 2; 2361 auto NewFalseProb = TProb / 2 + FProb; 2362 // Emit the LHS condition. 2363 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2364 NewFalseProb, InvertCond); 2365 2366 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2367 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2368 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2369 // Emit the RHS condition into TmpBB. 2370 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2371 Probs[1], InvertCond); 2372 } else { 2373 assert(Opc == Instruction::And && "Unknown merge op!"); 2374 // Codegen X & Y as: 2375 // BB1: 2376 // jmp_if_X TmpBB 2377 // jmp FBB 2378 // TmpBB: 2379 // jmp_if_Y TBB 2380 // jmp FBB 2381 // 2382 // This requires creation of TmpBB after CurBB. 2383 2384 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2385 // The requirement is that 2386 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2387 // = FalseProb for original BB. 2388 // Assuming the original probabilities are A and B, one choice is to set 2389 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2390 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2391 // TrueProb for BB1 * FalseProb for TmpBB. 2392 2393 auto NewTrueProb = TProb + FProb / 2; 2394 auto NewFalseProb = FProb / 2; 2395 // Emit the LHS condition. 2396 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2397 NewFalseProb, InvertCond); 2398 2399 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2400 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2401 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2402 // Emit the RHS condition into TmpBB. 2403 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2404 Probs[1], InvertCond); 2405 } 2406 } 2407 2408 /// If the set of cases should be emitted as a series of branches, return true. 2409 /// If we should emit this as a bunch of and/or'd together conditions, return 2410 /// false. 2411 bool 2412 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2413 if (Cases.size() != 2) return true; 2414 2415 // If this is two comparisons of the same values or'd or and'd together, they 2416 // will get folded into a single comparison, so don't emit two blocks. 2417 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2418 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2419 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2420 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2421 return false; 2422 } 2423 2424 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2425 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2426 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2427 Cases[0].CC == Cases[1].CC && 2428 isa<Constant>(Cases[0].CmpRHS) && 2429 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2430 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2431 return false; 2432 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2433 return false; 2434 } 2435 2436 return true; 2437 } 2438 2439 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2440 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2441 2442 // Update machine-CFG edges. 2443 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2444 2445 if (I.isUnconditional()) { 2446 // Update machine-CFG edges. 2447 BrMBB->addSuccessor(Succ0MBB); 2448 2449 // If this is not a fall-through branch or optimizations are switched off, 2450 // emit the branch. 2451 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2452 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2453 MVT::Other, getControlRoot(), 2454 DAG.getBasicBlock(Succ0MBB))); 2455 2456 return; 2457 } 2458 2459 // If this condition is one of the special cases we handle, do special stuff 2460 // now. 2461 const Value *CondVal = I.getCondition(); 2462 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2463 2464 // If this is a series of conditions that are or'd or and'd together, emit 2465 // this as a sequence of branches instead of setcc's with and/or operations. 2466 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2467 // unpredictable branches, and vector extracts because those jumps are likely 2468 // expensive for any target), this should improve performance. 2469 // For example, instead of something like: 2470 // cmp A, B 2471 // C = seteq 2472 // cmp D, E 2473 // F = setle 2474 // or C, F 2475 // jnz foo 2476 // Emit: 2477 // cmp A, B 2478 // je foo 2479 // cmp D, E 2480 // jle foo 2481 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2482 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2483 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2484 Value *Vec; 2485 const Value *BOp0, *BOp1; 2486 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2487 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2488 Opcode = Instruction::And; 2489 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2490 Opcode = Instruction::Or; 2491 2492 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2493 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2494 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2495 getEdgeProbability(BrMBB, Succ0MBB), 2496 getEdgeProbability(BrMBB, Succ1MBB), 2497 /*InvertCond=*/false); 2498 // If the compares in later blocks need to use values not currently 2499 // exported from this block, export them now. This block should always 2500 // be the first entry. 2501 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2502 2503 // Allow some cases to be rejected. 2504 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2505 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2506 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2507 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2508 } 2509 2510 // Emit the branch for this block. 2511 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2512 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2513 return; 2514 } 2515 2516 // Okay, we decided not to do this, remove any inserted MBB's and clear 2517 // SwitchCases. 2518 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2519 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2520 2521 SL->SwitchCases.clear(); 2522 } 2523 } 2524 2525 // Create a CaseBlock record representing this branch. 2526 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2527 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2528 2529 // Use visitSwitchCase to actually insert the fast branch sequence for this 2530 // cond branch. 2531 visitSwitchCase(CB, BrMBB); 2532 } 2533 2534 /// visitSwitchCase - Emits the necessary code to represent a single node in 2535 /// the binary search tree resulting from lowering a switch instruction. 2536 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2537 MachineBasicBlock *SwitchBB) { 2538 SDValue Cond; 2539 SDValue CondLHS = getValue(CB.CmpLHS); 2540 SDLoc dl = CB.DL; 2541 2542 if (CB.CC == ISD::SETTRUE) { 2543 // Branch or fall through to TrueBB. 2544 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2545 SwitchBB->normalizeSuccProbs(); 2546 if (CB.TrueBB != NextBlock(SwitchBB)) { 2547 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2548 DAG.getBasicBlock(CB.TrueBB))); 2549 } 2550 return; 2551 } 2552 2553 auto &TLI = DAG.getTargetLoweringInfo(); 2554 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2555 2556 // Build the setcc now. 2557 if (!CB.CmpMHS) { 2558 // Fold "(X == true)" to X and "(X == false)" to !X to 2559 // handle common cases produced by branch lowering. 2560 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2561 CB.CC == ISD::SETEQ) 2562 Cond = CondLHS; 2563 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2564 CB.CC == ISD::SETEQ) { 2565 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2566 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2567 } else { 2568 SDValue CondRHS = getValue(CB.CmpRHS); 2569 2570 // If a pointer's DAG type is larger than its memory type then the DAG 2571 // values are zero-extended. This breaks signed comparisons so truncate 2572 // back to the underlying type before doing the compare. 2573 if (CondLHS.getValueType() != MemVT) { 2574 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2575 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2576 } 2577 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2578 } 2579 } else { 2580 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2581 2582 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2583 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2584 2585 SDValue CmpOp = getValue(CB.CmpMHS); 2586 EVT VT = CmpOp.getValueType(); 2587 2588 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2589 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2590 ISD::SETLE); 2591 } else { 2592 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2593 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2594 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2595 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2596 } 2597 } 2598 2599 // Update successor info 2600 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2601 // TrueBB and FalseBB are always different unless the incoming IR is 2602 // degenerate. This only happens when running llc on weird IR. 2603 if (CB.TrueBB != CB.FalseBB) 2604 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2605 SwitchBB->normalizeSuccProbs(); 2606 2607 // If the lhs block is the next block, invert the condition so that we can 2608 // fall through to the lhs instead of the rhs block. 2609 if (CB.TrueBB == NextBlock(SwitchBB)) { 2610 std::swap(CB.TrueBB, CB.FalseBB); 2611 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2612 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2613 } 2614 2615 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2616 MVT::Other, getControlRoot(), Cond, 2617 DAG.getBasicBlock(CB.TrueBB)); 2618 2619 setValue(CurInst, BrCond); 2620 2621 // Insert the false branch. Do this even if it's a fall through branch, 2622 // this makes it easier to do DAG optimizations which require inverting 2623 // the branch condition. 2624 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2625 DAG.getBasicBlock(CB.FalseBB)); 2626 2627 DAG.setRoot(BrCond); 2628 } 2629 2630 /// visitJumpTable - Emit JumpTable node in the current MBB 2631 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2632 // Emit the code for the jump table 2633 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2634 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2635 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2636 JT.Reg, PTy); 2637 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2638 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2639 MVT::Other, Index.getValue(1), 2640 Table, Index); 2641 DAG.setRoot(BrJumpTable); 2642 } 2643 2644 /// visitJumpTableHeader - This function emits necessary code to produce index 2645 /// in the JumpTable from switch case. 2646 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2647 JumpTableHeader &JTH, 2648 MachineBasicBlock *SwitchBB) { 2649 SDLoc dl = getCurSDLoc(); 2650 2651 // Subtract the lowest switch case value from the value being switched on. 2652 SDValue SwitchOp = getValue(JTH.SValue); 2653 EVT VT = SwitchOp.getValueType(); 2654 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2655 DAG.getConstant(JTH.First, dl, VT)); 2656 2657 // The SDNode we just created, which holds the value being switched on minus 2658 // the smallest case value, needs to be copied to a virtual register so it 2659 // can be used as an index into the jump table in a subsequent basic block. 2660 // This value may be smaller or larger than the target's pointer type, and 2661 // therefore require extension or truncating. 2662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2663 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2664 2665 unsigned JumpTableReg = 2666 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2667 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2668 JumpTableReg, SwitchOp); 2669 JT.Reg = JumpTableReg; 2670 2671 if (!JTH.FallthroughUnreachable) { 2672 // Emit the range check for the jump table, and branch to the default block 2673 // for the switch statement if the value being switched on exceeds the 2674 // largest case in the switch. 2675 SDValue CMP = DAG.getSetCC( 2676 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2677 Sub.getValueType()), 2678 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2679 2680 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2681 MVT::Other, CopyTo, CMP, 2682 DAG.getBasicBlock(JT.Default)); 2683 2684 // Avoid emitting unnecessary branches to the next block. 2685 if (JT.MBB != NextBlock(SwitchBB)) 2686 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2687 DAG.getBasicBlock(JT.MBB)); 2688 2689 DAG.setRoot(BrCond); 2690 } else { 2691 // Avoid emitting unnecessary branches to the next block. 2692 if (JT.MBB != NextBlock(SwitchBB)) 2693 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2694 DAG.getBasicBlock(JT.MBB))); 2695 else 2696 DAG.setRoot(CopyTo); 2697 } 2698 } 2699 2700 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2701 /// variable if there exists one. 2702 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2703 SDValue &Chain) { 2704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2705 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2706 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2707 MachineFunction &MF = DAG.getMachineFunction(); 2708 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2709 MachineSDNode *Node = 2710 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2711 if (Global) { 2712 MachinePointerInfo MPInfo(Global); 2713 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2714 MachineMemOperand::MODereferenceable; 2715 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2716 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2717 DAG.setNodeMemRefs(Node, {MemRef}); 2718 } 2719 if (PtrTy != PtrMemTy) 2720 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2721 return SDValue(Node, 0); 2722 } 2723 2724 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2725 /// tail spliced into a stack protector check success bb. 2726 /// 2727 /// For a high level explanation of how this fits into the stack protector 2728 /// generation see the comment on the declaration of class 2729 /// StackProtectorDescriptor. 2730 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2731 MachineBasicBlock *ParentBB) { 2732 2733 // First create the loads to the guard/stack slot for the comparison. 2734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2735 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2736 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2737 2738 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2739 int FI = MFI.getStackProtectorIndex(); 2740 2741 SDValue Guard; 2742 SDLoc dl = getCurSDLoc(); 2743 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2744 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2745 Align Align = 2746 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2747 2748 // Generate code to load the content of the guard slot. 2749 SDValue GuardVal = DAG.getLoad( 2750 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2751 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2752 MachineMemOperand::MOVolatile); 2753 2754 if (TLI.useStackGuardXorFP()) 2755 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2756 2757 // Retrieve guard check function, nullptr if instrumentation is inlined. 2758 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2759 // The target provides a guard check function to validate the guard value. 2760 // Generate a call to that function with the content of the guard slot as 2761 // argument. 2762 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2763 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2764 2765 TargetLowering::ArgListTy Args; 2766 TargetLowering::ArgListEntry Entry; 2767 Entry.Node = GuardVal; 2768 Entry.Ty = FnTy->getParamType(0); 2769 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2770 Entry.IsInReg = true; 2771 Args.push_back(Entry); 2772 2773 TargetLowering::CallLoweringInfo CLI(DAG); 2774 CLI.setDebugLoc(getCurSDLoc()) 2775 .setChain(DAG.getEntryNode()) 2776 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2777 getValue(GuardCheckFn), std::move(Args)); 2778 2779 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2780 DAG.setRoot(Result.second); 2781 return; 2782 } 2783 2784 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2785 // Otherwise, emit a volatile load to retrieve the stack guard value. 2786 SDValue Chain = DAG.getEntryNode(); 2787 if (TLI.useLoadStackGuardNode()) { 2788 Guard = getLoadStackGuard(DAG, dl, Chain); 2789 } else { 2790 const Value *IRGuard = TLI.getSDagStackGuard(M); 2791 SDValue GuardPtr = getValue(IRGuard); 2792 2793 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2794 MachinePointerInfo(IRGuard, 0), Align, 2795 MachineMemOperand::MOVolatile); 2796 } 2797 2798 // Perform the comparison via a getsetcc. 2799 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2800 *DAG.getContext(), 2801 Guard.getValueType()), 2802 Guard, GuardVal, ISD::SETNE); 2803 2804 // If the guard/stackslot do not equal, branch to failure MBB. 2805 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2806 MVT::Other, GuardVal.getOperand(0), 2807 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2808 // Otherwise branch to success MBB. 2809 SDValue Br = DAG.getNode(ISD::BR, dl, 2810 MVT::Other, BrCond, 2811 DAG.getBasicBlock(SPD.getSuccessMBB())); 2812 2813 DAG.setRoot(Br); 2814 } 2815 2816 /// Codegen the failure basic block for a stack protector check. 2817 /// 2818 /// A failure stack protector machine basic block consists simply of a call to 2819 /// __stack_chk_fail(). 2820 /// 2821 /// For a high level explanation of how this fits into the stack protector 2822 /// generation see the comment on the declaration of class 2823 /// StackProtectorDescriptor. 2824 void 2825 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2827 TargetLowering::MakeLibCallOptions CallOptions; 2828 CallOptions.setDiscardResult(true); 2829 SDValue Chain = 2830 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2831 std::nullopt, CallOptions, getCurSDLoc()) 2832 .second; 2833 // On PS4/PS5, the "return address" must still be within the calling 2834 // function, even if it's at the very end, so emit an explicit TRAP here. 2835 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2836 if (TM.getTargetTriple().isPS()) 2837 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2838 // WebAssembly needs an unreachable instruction after a non-returning call, 2839 // because the function return type can be different from __stack_chk_fail's 2840 // return type (void). 2841 if (TM.getTargetTriple().isWasm()) 2842 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2843 2844 DAG.setRoot(Chain); 2845 } 2846 2847 /// visitBitTestHeader - This function emits necessary code to produce value 2848 /// suitable for "bit tests" 2849 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2850 MachineBasicBlock *SwitchBB) { 2851 SDLoc dl = getCurSDLoc(); 2852 2853 // Subtract the minimum value. 2854 SDValue SwitchOp = getValue(B.SValue); 2855 EVT VT = SwitchOp.getValueType(); 2856 SDValue RangeSub = 2857 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2858 2859 // Determine the type of the test operands. 2860 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2861 bool UsePtrType = false; 2862 if (!TLI.isTypeLegal(VT)) { 2863 UsePtrType = true; 2864 } else { 2865 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2866 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2867 // Switch table case range are encoded into series of masks. 2868 // Just use pointer type, it's guaranteed to fit. 2869 UsePtrType = true; 2870 break; 2871 } 2872 } 2873 SDValue Sub = RangeSub; 2874 if (UsePtrType) { 2875 VT = TLI.getPointerTy(DAG.getDataLayout()); 2876 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2877 } 2878 2879 B.RegVT = VT.getSimpleVT(); 2880 B.Reg = FuncInfo.CreateReg(B.RegVT); 2881 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2882 2883 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2884 2885 if (!B.FallthroughUnreachable) 2886 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2887 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2888 SwitchBB->normalizeSuccProbs(); 2889 2890 SDValue Root = CopyTo; 2891 if (!B.FallthroughUnreachable) { 2892 // Conditional branch to the default block. 2893 SDValue RangeCmp = DAG.getSetCC(dl, 2894 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2895 RangeSub.getValueType()), 2896 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2897 ISD::SETUGT); 2898 2899 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2900 DAG.getBasicBlock(B.Default)); 2901 } 2902 2903 // Avoid emitting unnecessary branches to the next block. 2904 if (MBB != NextBlock(SwitchBB)) 2905 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2906 2907 DAG.setRoot(Root); 2908 } 2909 2910 /// visitBitTestCase - this function produces one "bit test" 2911 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2912 MachineBasicBlock* NextMBB, 2913 BranchProbability BranchProbToNext, 2914 unsigned Reg, 2915 BitTestCase &B, 2916 MachineBasicBlock *SwitchBB) { 2917 SDLoc dl = getCurSDLoc(); 2918 MVT VT = BB.RegVT; 2919 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2920 SDValue Cmp; 2921 unsigned PopCount = llvm::popcount(B.Mask); 2922 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2923 if (PopCount == 1) { 2924 // Testing for a single bit; just compare the shift count with what it 2925 // would need to be to shift a 1 bit in that position. 2926 Cmp = DAG.getSetCC( 2927 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2928 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2929 ISD::SETEQ); 2930 } else if (PopCount == BB.Range) { 2931 // There is only one zero bit in the range, test for it directly. 2932 Cmp = DAG.getSetCC( 2933 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2934 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2935 } else { 2936 // Make desired shift 2937 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2938 DAG.getConstant(1, dl, VT), ShiftOp); 2939 2940 // Emit bit tests and jumps 2941 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2942 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2943 Cmp = DAG.getSetCC( 2944 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2945 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2946 } 2947 2948 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2949 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2950 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2951 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2952 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2953 // one as they are relative probabilities (and thus work more like weights), 2954 // and hence we need to normalize them to let the sum of them become one. 2955 SwitchBB->normalizeSuccProbs(); 2956 2957 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2958 MVT::Other, getControlRoot(), 2959 Cmp, DAG.getBasicBlock(B.TargetBB)); 2960 2961 // Avoid emitting unnecessary branches to the next block. 2962 if (NextMBB != NextBlock(SwitchBB)) 2963 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2964 DAG.getBasicBlock(NextMBB)); 2965 2966 DAG.setRoot(BrAnd); 2967 } 2968 2969 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2970 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2971 2972 // Retrieve successors. Look through artificial IR level blocks like 2973 // catchswitch for successors. 2974 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2975 const BasicBlock *EHPadBB = I.getSuccessor(1); 2976 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 2977 2978 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2979 // have to do anything here to lower funclet bundles. 2980 assert(!I.hasOperandBundlesOtherThan( 2981 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2982 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2983 LLVMContext::OB_cfguardtarget, 2984 LLVMContext::OB_clang_arc_attachedcall}) && 2985 "Cannot lower invokes with arbitrary operand bundles yet!"); 2986 2987 const Value *Callee(I.getCalledOperand()); 2988 const Function *Fn = dyn_cast<Function>(Callee); 2989 if (isa<InlineAsm>(Callee)) 2990 visitInlineAsm(I, EHPadBB); 2991 else if (Fn && Fn->isIntrinsic()) { 2992 switch (Fn->getIntrinsicID()) { 2993 default: 2994 llvm_unreachable("Cannot invoke this intrinsic"); 2995 case Intrinsic::donothing: 2996 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2997 case Intrinsic::seh_try_begin: 2998 case Intrinsic::seh_scope_begin: 2999 case Intrinsic::seh_try_end: 3000 case Intrinsic::seh_scope_end: 3001 if (EHPadMBB) 3002 // a block referenced by EH table 3003 // so dtor-funclet not removed by opts 3004 EHPadMBB->setMachineBlockAddressTaken(); 3005 break; 3006 case Intrinsic::experimental_patchpoint_void: 3007 case Intrinsic::experimental_patchpoint_i64: 3008 visitPatchpoint(I, EHPadBB); 3009 break; 3010 case Intrinsic::experimental_gc_statepoint: 3011 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3012 break; 3013 case Intrinsic::wasm_rethrow: { 3014 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3015 // special because it can be invoked, so we manually lower it to a DAG 3016 // node here. 3017 SmallVector<SDValue, 8> Ops; 3018 Ops.push_back(getRoot()); // inchain 3019 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3020 Ops.push_back( 3021 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3022 TLI.getPointerTy(DAG.getDataLayout()))); 3023 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3024 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3025 break; 3026 } 3027 } 3028 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3029 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3030 // Eventually we will support lowering the @llvm.experimental.deoptimize 3031 // intrinsic, and right now there are no plans to support other intrinsics 3032 // with deopt state. 3033 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3034 } else { 3035 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3036 } 3037 3038 // If the value of the invoke is used outside of its defining block, make it 3039 // available as a virtual register. 3040 // We already took care of the exported value for the statepoint instruction 3041 // during call to the LowerStatepoint. 3042 if (!isa<GCStatepointInst>(I)) { 3043 CopyToExportRegsIfNeeded(&I); 3044 } 3045 3046 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3047 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3048 BranchProbability EHPadBBProb = 3049 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3050 : BranchProbability::getZero(); 3051 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3052 3053 // Update successor info. 3054 addSuccessorWithProb(InvokeMBB, Return); 3055 for (auto &UnwindDest : UnwindDests) { 3056 UnwindDest.first->setIsEHPad(); 3057 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3058 } 3059 InvokeMBB->normalizeSuccProbs(); 3060 3061 // Drop into normal successor. 3062 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3063 DAG.getBasicBlock(Return))); 3064 } 3065 3066 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3067 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3068 3069 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3070 // have to do anything here to lower funclet bundles. 3071 assert(!I.hasOperandBundlesOtherThan( 3072 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3073 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3074 3075 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3076 visitInlineAsm(I); 3077 CopyToExportRegsIfNeeded(&I); 3078 3079 // Retrieve successors. 3080 SmallPtrSet<BasicBlock *, 8> Dests; 3081 Dests.insert(I.getDefaultDest()); 3082 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3083 3084 // Update successor info. 3085 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3086 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3087 BasicBlock *Dest = I.getIndirectDest(i); 3088 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3089 Target->setIsInlineAsmBrIndirectTarget(); 3090 Target->setMachineBlockAddressTaken(); 3091 Target->setLabelMustBeEmitted(); 3092 // Don't add duplicate machine successors. 3093 if (Dests.insert(Dest).second) 3094 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3095 } 3096 CallBrMBB->normalizeSuccProbs(); 3097 3098 // Drop into default successor. 3099 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3100 MVT::Other, getControlRoot(), 3101 DAG.getBasicBlock(Return))); 3102 } 3103 3104 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3105 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3106 } 3107 3108 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3109 assert(FuncInfo.MBB->isEHPad() && 3110 "Call to landingpad not in landing pad!"); 3111 3112 // If there aren't registers to copy the values into (e.g., during SjLj 3113 // exceptions), then don't bother to create these DAG nodes. 3114 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3115 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3116 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3117 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3118 return; 3119 3120 // If landingpad's return type is token type, we don't create DAG nodes 3121 // for its exception pointer and selector value. The extraction of exception 3122 // pointer or selector value from token type landingpads is not currently 3123 // supported. 3124 if (LP.getType()->isTokenTy()) 3125 return; 3126 3127 SmallVector<EVT, 2> ValueVTs; 3128 SDLoc dl = getCurSDLoc(); 3129 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3130 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3131 3132 // Get the two live-in registers as SDValues. The physregs have already been 3133 // copied into virtual registers. 3134 SDValue Ops[2]; 3135 if (FuncInfo.ExceptionPointerVirtReg) { 3136 Ops[0] = DAG.getZExtOrTrunc( 3137 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3138 FuncInfo.ExceptionPointerVirtReg, 3139 TLI.getPointerTy(DAG.getDataLayout())), 3140 dl, ValueVTs[0]); 3141 } else { 3142 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3143 } 3144 Ops[1] = DAG.getZExtOrTrunc( 3145 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3146 FuncInfo.ExceptionSelectorVirtReg, 3147 TLI.getPointerTy(DAG.getDataLayout())), 3148 dl, ValueVTs[1]); 3149 3150 // Merge into one. 3151 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3152 DAG.getVTList(ValueVTs), Ops); 3153 setValue(&LP, Res); 3154 } 3155 3156 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3157 MachineBasicBlock *Last) { 3158 // Update JTCases. 3159 for (JumpTableBlock &JTB : SL->JTCases) 3160 if (JTB.first.HeaderBB == First) 3161 JTB.first.HeaderBB = Last; 3162 3163 // Update BitTestCases. 3164 for (BitTestBlock &BTB : SL->BitTestCases) 3165 if (BTB.Parent == First) 3166 BTB.Parent = Last; 3167 } 3168 3169 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3170 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3171 3172 // Update machine-CFG edges with unique successors. 3173 SmallSet<BasicBlock*, 32> Done; 3174 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3175 BasicBlock *BB = I.getSuccessor(i); 3176 bool Inserted = Done.insert(BB).second; 3177 if (!Inserted) 3178 continue; 3179 3180 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3181 addSuccessorWithProb(IndirectBrMBB, Succ); 3182 } 3183 IndirectBrMBB->normalizeSuccProbs(); 3184 3185 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3186 MVT::Other, getControlRoot(), 3187 getValue(I.getAddress()))); 3188 } 3189 3190 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3191 if (!DAG.getTarget().Options.TrapUnreachable) 3192 return; 3193 3194 // We may be able to ignore unreachable behind a noreturn call. 3195 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3196 const BasicBlock &BB = *I.getParent(); 3197 if (&I != &BB.front()) { 3198 BasicBlock::const_iterator PredI = 3199 std::prev(BasicBlock::const_iterator(&I)); 3200 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3201 if (Call->doesNotReturn()) 3202 return; 3203 } 3204 } 3205 } 3206 3207 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3208 } 3209 3210 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3211 SDNodeFlags Flags; 3212 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3213 Flags.copyFMF(*FPOp); 3214 3215 SDValue Op = getValue(I.getOperand(0)); 3216 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3217 Op, Flags); 3218 setValue(&I, UnNodeValue); 3219 } 3220 3221 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3222 SDNodeFlags Flags; 3223 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3224 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3225 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3226 } 3227 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3228 Flags.setExact(ExactOp->isExact()); 3229 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3230 Flags.copyFMF(*FPOp); 3231 3232 SDValue Op1 = getValue(I.getOperand(0)); 3233 SDValue Op2 = getValue(I.getOperand(1)); 3234 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3235 Op1, Op2, Flags); 3236 setValue(&I, BinNodeValue); 3237 } 3238 3239 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3240 SDValue Op1 = getValue(I.getOperand(0)); 3241 SDValue Op2 = getValue(I.getOperand(1)); 3242 3243 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3244 Op1.getValueType(), DAG.getDataLayout()); 3245 3246 // Coerce the shift amount to the right type if we can. This exposes the 3247 // truncate or zext to optimization early. 3248 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3249 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3250 "Unexpected shift type"); 3251 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3252 } 3253 3254 bool nuw = false; 3255 bool nsw = false; 3256 bool exact = false; 3257 3258 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3259 3260 if (const OverflowingBinaryOperator *OFBinOp = 3261 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3262 nuw = OFBinOp->hasNoUnsignedWrap(); 3263 nsw = OFBinOp->hasNoSignedWrap(); 3264 } 3265 if (const PossiblyExactOperator *ExactOp = 3266 dyn_cast<const PossiblyExactOperator>(&I)) 3267 exact = ExactOp->isExact(); 3268 } 3269 SDNodeFlags Flags; 3270 Flags.setExact(exact); 3271 Flags.setNoSignedWrap(nsw); 3272 Flags.setNoUnsignedWrap(nuw); 3273 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3274 Flags); 3275 setValue(&I, Res); 3276 } 3277 3278 void SelectionDAGBuilder::visitSDiv(const User &I) { 3279 SDValue Op1 = getValue(I.getOperand(0)); 3280 SDValue Op2 = getValue(I.getOperand(1)); 3281 3282 SDNodeFlags Flags; 3283 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3284 cast<PossiblyExactOperator>(&I)->isExact()); 3285 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3286 Op2, Flags)); 3287 } 3288 3289 void SelectionDAGBuilder::visitICmp(const User &I) { 3290 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3291 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3292 predicate = IC->getPredicate(); 3293 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3294 predicate = ICmpInst::Predicate(IC->getPredicate()); 3295 SDValue Op1 = getValue(I.getOperand(0)); 3296 SDValue Op2 = getValue(I.getOperand(1)); 3297 ISD::CondCode Opcode = getICmpCondCode(predicate); 3298 3299 auto &TLI = DAG.getTargetLoweringInfo(); 3300 EVT MemVT = 3301 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3302 3303 // If a pointer's DAG type is larger than its memory type then the DAG values 3304 // are zero-extended. This breaks signed comparisons so truncate back to the 3305 // underlying type before doing the compare. 3306 if (Op1.getValueType() != MemVT) { 3307 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3308 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3309 } 3310 3311 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3312 I.getType()); 3313 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3314 } 3315 3316 void SelectionDAGBuilder::visitFCmp(const User &I) { 3317 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3318 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3319 predicate = FC->getPredicate(); 3320 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3321 predicate = FCmpInst::Predicate(FC->getPredicate()); 3322 SDValue Op1 = getValue(I.getOperand(0)); 3323 SDValue Op2 = getValue(I.getOperand(1)); 3324 3325 ISD::CondCode Condition = getFCmpCondCode(predicate); 3326 auto *FPMO = cast<FPMathOperator>(&I); 3327 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3328 Condition = getFCmpCodeWithoutNaN(Condition); 3329 3330 SDNodeFlags Flags; 3331 Flags.copyFMF(*FPMO); 3332 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3333 3334 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3335 I.getType()); 3336 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3337 } 3338 3339 // Check if the condition of the select has one use or two users that are both 3340 // selects with the same condition. 3341 static bool hasOnlySelectUsers(const Value *Cond) { 3342 return llvm::all_of(Cond->users(), [](const Value *V) { 3343 return isa<SelectInst>(V); 3344 }); 3345 } 3346 3347 void SelectionDAGBuilder::visitSelect(const User &I) { 3348 SmallVector<EVT, 4> ValueVTs; 3349 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3350 ValueVTs); 3351 unsigned NumValues = ValueVTs.size(); 3352 if (NumValues == 0) return; 3353 3354 SmallVector<SDValue, 4> Values(NumValues); 3355 SDValue Cond = getValue(I.getOperand(0)); 3356 SDValue LHSVal = getValue(I.getOperand(1)); 3357 SDValue RHSVal = getValue(I.getOperand(2)); 3358 SmallVector<SDValue, 1> BaseOps(1, Cond); 3359 ISD::NodeType OpCode = 3360 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3361 3362 bool IsUnaryAbs = false; 3363 bool Negate = false; 3364 3365 SDNodeFlags Flags; 3366 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3367 Flags.copyFMF(*FPOp); 3368 3369 // Min/max matching is only viable if all output VTs are the same. 3370 if (all_equal(ValueVTs)) { 3371 EVT VT = ValueVTs[0]; 3372 LLVMContext &Ctx = *DAG.getContext(); 3373 auto &TLI = DAG.getTargetLoweringInfo(); 3374 3375 // We care about the legality of the operation after it has been type 3376 // legalized. 3377 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3378 VT = TLI.getTypeToTransformTo(Ctx, VT); 3379 3380 // If the vselect is legal, assume we want to leave this as a vector setcc + 3381 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3382 // min/max is legal on the scalar type. 3383 bool UseScalarMinMax = VT.isVector() && 3384 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3385 3386 // ValueTracking's select pattern matching does not account for -0.0, 3387 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3388 // -0.0 is less than +0.0. 3389 Value *LHS, *RHS; 3390 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3391 ISD::NodeType Opc = ISD::DELETED_NODE; 3392 switch (SPR.Flavor) { 3393 case SPF_UMAX: Opc = ISD::UMAX; break; 3394 case SPF_UMIN: Opc = ISD::UMIN; break; 3395 case SPF_SMAX: Opc = ISD::SMAX; break; 3396 case SPF_SMIN: Opc = ISD::SMIN; break; 3397 case SPF_FMINNUM: 3398 switch (SPR.NaNBehavior) { 3399 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3400 case SPNB_RETURNS_NAN: break; 3401 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3402 case SPNB_RETURNS_ANY: 3403 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3404 (UseScalarMinMax && 3405 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3406 Opc = ISD::FMINNUM; 3407 break; 3408 } 3409 break; 3410 case SPF_FMAXNUM: 3411 switch (SPR.NaNBehavior) { 3412 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3413 case SPNB_RETURNS_NAN: break; 3414 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3415 case SPNB_RETURNS_ANY: 3416 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3417 (UseScalarMinMax && 3418 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3419 Opc = ISD::FMAXNUM; 3420 break; 3421 } 3422 break; 3423 case SPF_NABS: 3424 Negate = true; 3425 [[fallthrough]]; 3426 case SPF_ABS: 3427 IsUnaryAbs = true; 3428 Opc = ISD::ABS; 3429 break; 3430 default: break; 3431 } 3432 3433 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3434 (TLI.isOperationLegalOrCustom(Opc, VT) || 3435 (UseScalarMinMax && 3436 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3437 // If the underlying comparison instruction is used by any other 3438 // instruction, the consumed instructions won't be destroyed, so it is 3439 // not profitable to convert to a min/max. 3440 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3441 OpCode = Opc; 3442 LHSVal = getValue(LHS); 3443 RHSVal = getValue(RHS); 3444 BaseOps.clear(); 3445 } 3446 3447 if (IsUnaryAbs) { 3448 OpCode = Opc; 3449 LHSVal = getValue(LHS); 3450 BaseOps.clear(); 3451 } 3452 } 3453 3454 if (IsUnaryAbs) { 3455 for (unsigned i = 0; i != NumValues; ++i) { 3456 SDLoc dl = getCurSDLoc(); 3457 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3458 Values[i] = 3459 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3460 if (Negate) 3461 Values[i] = DAG.getNegative(Values[i], dl, VT); 3462 } 3463 } else { 3464 for (unsigned i = 0; i != NumValues; ++i) { 3465 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3466 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3467 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3468 Values[i] = DAG.getNode( 3469 OpCode, getCurSDLoc(), 3470 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3471 } 3472 } 3473 3474 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3475 DAG.getVTList(ValueVTs), Values)); 3476 } 3477 3478 void SelectionDAGBuilder::visitTrunc(const User &I) { 3479 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3480 SDValue N = getValue(I.getOperand(0)); 3481 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3482 I.getType()); 3483 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3484 } 3485 3486 void SelectionDAGBuilder::visitZExt(const User &I) { 3487 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3488 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3489 SDValue N = getValue(I.getOperand(0)); 3490 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3491 I.getType()); 3492 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3493 } 3494 3495 void SelectionDAGBuilder::visitSExt(const User &I) { 3496 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3497 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3498 SDValue N = getValue(I.getOperand(0)); 3499 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3500 I.getType()); 3501 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3502 } 3503 3504 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3505 // FPTrunc is never a no-op cast, no need to check 3506 SDValue N = getValue(I.getOperand(0)); 3507 SDLoc dl = getCurSDLoc(); 3508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3509 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3510 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3511 DAG.getTargetConstant( 3512 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3513 } 3514 3515 void SelectionDAGBuilder::visitFPExt(const User &I) { 3516 // FPExt is never a no-op cast, no need to check 3517 SDValue N = getValue(I.getOperand(0)); 3518 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3519 I.getType()); 3520 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3521 } 3522 3523 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3524 // FPToUI is never a no-op cast, no need to check 3525 SDValue N = getValue(I.getOperand(0)); 3526 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3527 I.getType()); 3528 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3529 } 3530 3531 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3532 // FPToSI is never a no-op cast, no need to check 3533 SDValue N = getValue(I.getOperand(0)); 3534 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3535 I.getType()); 3536 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3537 } 3538 3539 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3540 // UIToFP is never a no-op cast, no need to check 3541 SDValue N = getValue(I.getOperand(0)); 3542 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3543 I.getType()); 3544 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3545 } 3546 3547 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3548 // SIToFP is never a no-op cast, no need to check 3549 SDValue N = getValue(I.getOperand(0)); 3550 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3551 I.getType()); 3552 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3553 } 3554 3555 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3556 // What to do depends on the size of the integer and the size of the pointer. 3557 // We can either truncate, zero extend, or no-op, accordingly. 3558 SDValue N = getValue(I.getOperand(0)); 3559 auto &TLI = DAG.getTargetLoweringInfo(); 3560 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3561 I.getType()); 3562 EVT PtrMemVT = 3563 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3564 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3565 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3566 setValue(&I, N); 3567 } 3568 3569 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3570 // What to do depends on the size of the integer and the size of the pointer. 3571 // We can either truncate, zero extend, or no-op, accordingly. 3572 SDValue N = getValue(I.getOperand(0)); 3573 auto &TLI = DAG.getTargetLoweringInfo(); 3574 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3575 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3576 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3577 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3578 setValue(&I, N); 3579 } 3580 3581 void SelectionDAGBuilder::visitBitCast(const User &I) { 3582 SDValue N = getValue(I.getOperand(0)); 3583 SDLoc dl = getCurSDLoc(); 3584 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3585 I.getType()); 3586 3587 // BitCast assures us that source and destination are the same size so this is 3588 // either a BITCAST or a no-op. 3589 if (DestVT != N.getValueType()) 3590 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3591 DestVT, N)); // convert types. 3592 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3593 // might fold any kind of constant expression to an integer constant and that 3594 // is not what we are looking for. Only recognize a bitcast of a genuine 3595 // constant integer as an opaque constant. 3596 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3597 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3598 /*isOpaque*/true)); 3599 else 3600 setValue(&I, N); // noop cast. 3601 } 3602 3603 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3605 const Value *SV = I.getOperand(0); 3606 SDValue N = getValue(SV); 3607 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3608 3609 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3610 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3611 3612 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3613 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3614 3615 setValue(&I, N); 3616 } 3617 3618 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3619 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3620 SDValue InVec = getValue(I.getOperand(0)); 3621 SDValue InVal = getValue(I.getOperand(1)); 3622 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3623 TLI.getVectorIdxTy(DAG.getDataLayout())); 3624 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3625 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3626 InVec, InVal, InIdx)); 3627 } 3628 3629 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3631 SDValue InVec = getValue(I.getOperand(0)); 3632 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3633 TLI.getVectorIdxTy(DAG.getDataLayout())); 3634 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3635 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3636 InVec, InIdx)); 3637 } 3638 3639 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3640 SDValue Src1 = getValue(I.getOperand(0)); 3641 SDValue Src2 = getValue(I.getOperand(1)); 3642 ArrayRef<int> Mask; 3643 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3644 Mask = SVI->getShuffleMask(); 3645 else 3646 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3647 SDLoc DL = getCurSDLoc(); 3648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3649 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3650 EVT SrcVT = Src1.getValueType(); 3651 3652 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3653 VT.isScalableVector()) { 3654 // Canonical splat form of first element of first input vector. 3655 SDValue FirstElt = 3656 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3657 DAG.getVectorIdxConstant(0, DL)); 3658 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3659 return; 3660 } 3661 3662 // For now, we only handle splats for scalable vectors. 3663 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3664 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3665 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3666 3667 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3668 unsigned MaskNumElts = Mask.size(); 3669 3670 if (SrcNumElts == MaskNumElts) { 3671 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3672 return; 3673 } 3674 3675 // Normalize the shuffle vector since mask and vector length don't match. 3676 if (SrcNumElts < MaskNumElts) { 3677 // Mask is longer than the source vectors. We can use concatenate vector to 3678 // make the mask and vectors lengths match. 3679 3680 if (MaskNumElts % SrcNumElts == 0) { 3681 // Mask length is a multiple of the source vector length. 3682 // Check if the shuffle is some kind of concatenation of the input 3683 // vectors. 3684 unsigned NumConcat = MaskNumElts / SrcNumElts; 3685 bool IsConcat = true; 3686 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3687 for (unsigned i = 0; i != MaskNumElts; ++i) { 3688 int Idx = Mask[i]; 3689 if (Idx < 0) 3690 continue; 3691 // Ensure the indices in each SrcVT sized piece are sequential and that 3692 // the same source is used for the whole piece. 3693 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3694 (ConcatSrcs[i / SrcNumElts] >= 0 && 3695 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3696 IsConcat = false; 3697 break; 3698 } 3699 // Remember which source this index came from. 3700 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3701 } 3702 3703 // The shuffle is concatenating multiple vectors together. Just emit 3704 // a CONCAT_VECTORS operation. 3705 if (IsConcat) { 3706 SmallVector<SDValue, 8> ConcatOps; 3707 for (auto Src : ConcatSrcs) { 3708 if (Src < 0) 3709 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3710 else if (Src == 0) 3711 ConcatOps.push_back(Src1); 3712 else 3713 ConcatOps.push_back(Src2); 3714 } 3715 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3716 return; 3717 } 3718 } 3719 3720 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3721 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3722 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3723 PaddedMaskNumElts); 3724 3725 // Pad both vectors with undefs to make them the same length as the mask. 3726 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3727 3728 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3729 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3730 MOps1[0] = Src1; 3731 MOps2[0] = Src2; 3732 3733 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3734 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3735 3736 // Readjust mask for new input vector length. 3737 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3738 for (unsigned i = 0; i != MaskNumElts; ++i) { 3739 int Idx = Mask[i]; 3740 if (Idx >= (int)SrcNumElts) 3741 Idx -= SrcNumElts - PaddedMaskNumElts; 3742 MappedOps[i] = Idx; 3743 } 3744 3745 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3746 3747 // If the concatenated vector was padded, extract a subvector with the 3748 // correct number of elements. 3749 if (MaskNumElts != PaddedMaskNumElts) 3750 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3751 DAG.getVectorIdxConstant(0, DL)); 3752 3753 setValue(&I, Result); 3754 return; 3755 } 3756 3757 if (SrcNumElts > MaskNumElts) { 3758 // Analyze the access pattern of the vector to see if we can extract 3759 // two subvectors and do the shuffle. 3760 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3761 bool CanExtract = true; 3762 for (int Idx : Mask) { 3763 unsigned Input = 0; 3764 if (Idx < 0) 3765 continue; 3766 3767 if (Idx >= (int)SrcNumElts) { 3768 Input = 1; 3769 Idx -= SrcNumElts; 3770 } 3771 3772 // If all the indices come from the same MaskNumElts sized portion of 3773 // the sources we can use extract. Also make sure the extract wouldn't 3774 // extract past the end of the source. 3775 int NewStartIdx = alignDown(Idx, MaskNumElts); 3776 if (NewStartIdx + MaskNumElts > SrcNumElts || 3777 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3778 CanExtract = false; 3779 // Make sure we always update StartIdx as we use it to track if all 3780 // elements are undef. 3781 StartIdx[Input] = NewStartIdx; 3782 } 3783 3784 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3785 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3786 return; 3787 } 3788 if (CanExtract) { 3789 // Extract appropriate subvector and generate a vector shuffle 3790 for (unsigned Input = 0; Input < 2; ++Input) { 3791 SDValue &Src = Input == 0 ? Src1 : Src2; 3792 if (StartIdx[Input] < 0) 3793 Src = DAG.getUNDEF(VT); 3794 else { 3795 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3796 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3797 } 3798 } 3799 3800 // Calculate new mask. 3801 SmallVector<int, 8> MappedOps(Mask); 3802 for (int &Idx : MappedOps) { 3803 if (Idx >= (int)SrcNumElts) 3804 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3805 else if (Idx >= 0) 3806 Idx -= StartIdx[0]; 3807 } 3808 3809 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3810 return; 3811 } 3812 } 3813 3814 // We can't use either concat vectors or extract subvectors so fall back to 3815 // replacing the shuffle with extract and build vector. 3816 // to insert and build vector. 3817 EVT EltVT = VT.getVectorElementType(); 3818 SmallVector<SDValue,8> Ops; 3819 for (int Idx : Mask) { 3820 SDValue Res; 3821 3822 if (Idx < 0) { 3823 Res = DAG.getUNDEF(EltVT); 3824 } else { 3825 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3826 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3827 3828 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3829 DAG.getVectorIdxConstant(Idx, DL)); 3830 } 3831 3832 Ops.push_back(Res); 3833 } 3834 3835 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3836 } 3837 3838 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3839 ArrayRef<unsigned> Indices = I.getIndices(); 3840 const Value *Op0 = I.getOperand(0); 3841 const Value *Op1 = I.getOperand(1); 3842 Type *AggTy = I.getType(); 3843 Type *ValTy = Op1->getType(); 3844 bool IntoUndef = isa<UndefValue>(Op0); 3845 bool FromUndef = isa<UndefValue>(Op1); 3846 3847 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3848 3849 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3850 SmallVector<EVT, 4> AggValueVTs; 3851 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3852 SmallVector<EVT, 4> ValValueVTs; 3853 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3854 3855 unsigned NumAggValues = AggValueVTs.size(); 3856 unsigned NumValValues = ValValueVTs.size(); 3857 SmallVector<SDValue, 4> Values(NumAggValues); 3858 3859 // Ignore an insertvalue that produces an empty object 3860 if (!NumAggValues) { 3861 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3862 return; 3863 } 3864 3865 SDValue Agg = getValue(Op0); 3866 unsigned i = 0; 3867 // Copy the beginning value(s) from the original aggregate. 3868 for (; i != LinearIndex; ++i) 3869 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3870 SDValue(Agg.getNode(), Agg.getResNo() + i); 3871 // Copy values from the inserted value(s). 3872 if (NumValValues) { 3873 SDValue Val = getValue(Op1); 3874 for (; i != LinearIndex + NumValValues; ++i) 3875 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3876 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3877 } 3878 // Copy remaining value(s) from the original aggregate. 3879 for (; i != NumAggValues; ++i) 3880 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3881 SDValue(Agg.getNode(), Agg.getResNo() + i); 3882 3883 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3884 DAG.getVTList(AggValueVTs), Values)); 3885 } 3886 3887 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3888 ArrayRef<unsigned> Indices = I.getIndices(); 3889 const Value *Op0 = I.getOperand(0); 3890 Type *AggTy = Op0->getType(); 3891 Type *ValTy = I.getType(); 3892 bool OutOfUndef = isa<UndefValue>(Op0); 3893 3894 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3895 3896 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3897 SmallVector<EVT, 4> ValValueVTs; 3898 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3899 3900 unsigned NumValValues = ValValueVTs.size(); 3901 3902 // Ignore a extractvalue that produces an empty object 3903 if (!NumValValues) { 3904 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3905 return; 3906 } 3907 3908 SmallVector<SDValue, 4> Values(NumValValues); 3909 3910 SDValue Agg = getValue(Op0); 3911 // Copy out the selected value(s). 3912 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3913 Values[i - LinearIndex] = 3914 OutOfUndef ? 3915 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3916 SDValue(Agg.getNode(), Agg.getResNo() + i); 3917 3918 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3919 DAG.getVTList(ValValueVTs), Values)); 3920 } 3921 3922 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3923 Value *Op0 = I.getOperand(0); 3924 // Note that the pointer operand may be a vector of pointers. Take the scalar 3925 // element which holds a pointer. 3926 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3927 SDValue N = getValue(Op0); 3928 SDLoc dl = getCurSDLoc(); 3929 auto &TLI = DAG.getTargetLoweringInfo(); 3930 3931 // Normalize Vector GEP - all scalar operands should be converted to the 3932 // splat vector. 3933 bool IsVectorGEP = I.getType()->isVectorTy(); 3934 ElementCount VectorElementCount = 3935 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3936 : ElementCount::getFixed(0); 3937 3938 if (IsVectorGEP && !N.getValueType().isVector()) { 3939 LLVMContext &Context = *DAG.getContext(); 3940 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3941 N = DAG.getSplat(VT, dl, N); 3942 } 3943 3944 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3945 GTI != E; ++GTI) { 3946 const Value *Idx = GTI.getOperand(); 3947 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3948 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3949 if (Field) { 3950 // N = N + Offset 3951 uint64_t Offset = 3952 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3953 3954 // In an inbounds GEP with an offset that is nonnegative even when 3955 // interpreted as signed, assume there is no unsigned overflow. 3956 SDNodeFlags Flags; 3957 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3958 Flags.setNoUnsignedWrap(true); 3959 3960 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3961 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3962 } 3963 } else { 3964 // IdxSize is the width of the arithmetic according to IR semantics. 3965 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3966 // (and fix up the result later). 3967 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3968 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3969 TypeSize ElementSize = 3970 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3971 // We intentionally mask away the high bits here; ElementSize may not 3972 // fit in IdxTy. 3973 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3974 bool ElementScalable = ElementSize.isScalable(); 3975 3976 // If this is a scalar constant or a splat vector of constants, 3977 // handle it quickly. 3978 const auto *C = dyn_cast<Constant>(Idx); 3979 if (C && isa<VectorType>(C->getType())) 3980 C = C->getSplatValue(); 3981 3982 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3983 if (CI && CI->isZero()) 3984 continue; 3985 if (CI && !ElementScalable) { 3986 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3987 LLVMContext &Context = *DAG.getContext(); 3988 SDValue OffsVal; 3989 if (IsVectorGEP) 3990 OffsVal = DAG.getConstant( 3991 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3992 else 3993 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3994 3995 // In an inbounds GEP with an offset that is nonnegative even when 3996 // interpreted as signed, assume there is no unsigned overflow. 3997 SDNodeFlags Flags; 3998 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3999 Flags.setNoUnsignedWrap(true); 4000 4001 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4002 4003 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4004 continue; 4005 } 4006 4007 // N = N + Idx * ElementMul; 4008 SDValue IdxN = getValue(Idx); 4009 4010 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4011 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4012 VectorElementCount); 4013 IdxN = DAG.getSplat(VT, dl, IdxN); 4014 } 4015 4016 // If the index is smaller or larger than intptr_t, truncate or extend 4017 // it. 4018 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4019 4020 if (ElementScalable) { 4021 EVT VScaleTy = N.getValueType().getScalarType(); 4022 SDValue VScale = DAG.getNode( 4023 ISD::VSCALE, dl, VScaleTy, 4024 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4025 if (IsVectorGEP) 4026 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4027 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4028 } else { 4029 // If this is a multiply by a power of two, turn it into a shl 4030 // immediately. This is a very common case. 4031 if (ElementMul != 1) { 4032 if (ElementMul.isPowerOf2()) { 4033 unsigned Amt = ElementMul.logBase2(); 4034 IdxN = DAG.getNode(ISD::SHL, dl, 4035 N.getValueType(), IdxN, 4036 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4037 } else { 4038 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4039 IdxN.getValueType()); 4040 IdxN = DAG.getNode(ISD::MUL, dl, 4041 N.getValueType(), IdxN, Scale); 4042 } 4043 } 4044 } 4045 4046 N = DAG.getNode(ISD::ADD, dl, 4047 N.getValueType(), N, IdxN); 4048 } 4049 } 4050 4051 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4052 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4053 if (IsVectorGEP) { 4054 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4055 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4056 } 4057 4058 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4059 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4060 4061 setValue(&I, N); 4062 } 4063 4064 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4065 // If this is a fixed sized alloca in the entry block of the function, 4066 // allocate it statically on the stack. 4067 if (FuncInfo.StaticAllocaMap.count(&I)) 4068 return; // getValue will auto-populate this. 4069 4070 SDLoc dl = getCurSDLoc(); 4071 Type *Ty = I.getAllocatedType(); 4072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4073 auto &DL = DAG.getDataLayout(); 4074 TypeSize TySize = DL.getTypeAllocSize(Ty); 4075 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4076 4077 SDValue AllocSize = getValue(I.getArraySize()); 4078 4079 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4080 if (AllocSize.getValueType() != IntPtr) 4081 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4082 4083 if (TySize.isScalable()) 4084 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4085 DAG.getVScale(dl, IntPtr, 4086 APInt(IntPtr.getScalarSizeInBits(), 4087 TySize.getKnownMinValue()))); 4088 else 4089 AllocSize = 4090 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4091 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4092 4093 // Handle alignment. If the requested alignment is less than or equal to 4094 // the stack alignment, ignore it. If the size is greater than or equal to 4095 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4096 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4097 if (*Alignment <= StackAlign) 4098 Alignment = std::nullopt; 4099 4100 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4101 // Round the size of the allocation up to the stack alignment size 4102 // by add SA-1 to the size. This doesn't overflow because we're computing 4103 // an address inside an alloca. 4104 SDNodeFlags Flags; 4105 Flags.setNoUnsignedWrap(true); 4106 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4107 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4108 4109 // Mask out the low bits for alignment purposes. 4110 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4111 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4112 4113 SDValue Ops[] = { 4114 getRoot(), AllocSize, 4115 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4116 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4117 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4118 setValue(&I, DSA); 4119 DAG.setRoot(DSA.getValue(1)); 4120 4121 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4122 } 4123 4124 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4125 if (I.isAtomic()) 4126 return visitAtomicLoad(I); 4127 4128 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4129 const Value *SV = I.getOperand(0); 4130 if (TLI.supportSwiftError()) { 4131 // Swifterror values can come from either a function parameter with 4132 // swifterror attribute or an alloca with swifterror attribute. 4133 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4134 if (Arg->hasSwiftErrorAttr()) 4135 return visitLoadFromSwiftError(I); 4136 } 4137 4138 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4139 if (Alloca->isSwiftError()) 4140 return visitLoadFromSwiftError(I); 4141 } 4142 } 4143 4144 SDValue Ptr = getValue(SV); 4145 4146 Type *Ty = I.getType(); 4147 SmallVector<EVT, 4> ValueVTs, MemVTs; 4148 SmallVector<uint64_t, 4> Offsets; 4149 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4150 unsigned NumValues = ValueVTs.size(); 4151 if (NumValues == 0) 4152 return; 4153 4154 Align Alignment = I.getAlign(); 4155 AAMDNodes AAInfo = I.getAAMetadata(); 4156 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4157 bool isVolatile = I.isVolatile(); 4158 MachineMemOperand::Flags MMOFlags = 4159 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4160 4161 SDValue Root; 4162 bool ConstantMemory = false; 4163 if (isVolatile) 4164 // Serialize volatile loads with other side effects. 4165 Root = getRoot(); 4166 else if (NumValues > MaxParallelChains) 4167 Root = getMemoryRoot(); 4168 else if (AA && 4169 AA->pointsToConstantMemory(MemoryLocation( 4170 SV, 4171 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4172 AAInfo))) { 4173 // Do not serialize (non-volatile) loads of constant memory with anything. 4174 Root = DAG.getEntryNode(); 4175 ConstantMemory = true; 4176 MMOFlags |= MachineMemOperand::MOInvariant; 4177 } else { 4178 // Do not serialize non-volatile loads against each other. 4179 Root = DAG.getRoot(); 4180 } 4181 4182 SDLoc dl = getCurSDLoc(); 4183 4184 if (isVolatile) 4185 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4186 4187 // An aggregate load cannot wrap around the address space, so offsets to its 4188 // parts don't wrap either. 4189 SDNodeFlags Flags; 4190 Flags.setNoUnsignedWrap(true); 4191 4192 SmallVector<SDValue, 4> Values(NumValues); 4193 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4194 EVT PtrVT = Ptr.getValueType(); 4195 4196 unsigned ChainI = 0; 4197 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4198 // Serializing loads here may result in excessive register pressure, and 4199 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4200 // could recover a bit by hoisting nodes upward in the chain by recognizing 4201 // they are side-effect free or do not alias. The optimizer should really 4202 // avoid this case by converting large object/array copies to llvm.memcpy 4203 // (MaxParallelChains should always remain as failsafe). 4204 if (ChainI == MaxParallelChains) { 4205 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4206 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4207 ArrayRef(Chains.data(), ChainI)); 4208 Root = Chain; 4209 ChainI = 0; 4210 } 4211 SDValue A = DAG.getNode(ISD::ADD, dl, 4212 PtrVT, Ptr, 4213 DAG.getConstant(Offsets[i], dl, PtrVT), 4214 Flags); 4215 4216 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4217 MachinePointerInfo(SV, Offsets[i]), Alignment, 4218 MMOFlags, AAInfo, Ranges); 4219 Chains[ChainI] = L.getValue(1); 4220 4221 if (MemVTs[i] != ValueVTs[i]) 4222 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4223 4224 Values[i] = L; 4225 } 4226 4227 if (!ConstantMemory) { 4228 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4229 ArrayRef(Chains.data(), ChainI)); 4230 if (isVolatile) 4231 DAG.setRoot(Chain); 4232 else 4233 PendingLoads.push_back(Chain); 4234 } 4235 4236 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4237 DAG.getVTList(ValueVTs), Values)); 4238 } 4239 4240 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4241 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4242 "call visitStoreToSwiftError when backend supports swifterror"); 4243 4244 SmallVector<EVT, 4> ValueVTs; 4245 SmallVector<uint64_t, 4> Offsets; 4246 const Value *SrcV = I.getOperand(0); 4247 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4248 SrcV->getType(), ValueVTs, &Offsets); 4249 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4250 "expect a single EVT for swifterror"); 4251 4252 SDValue Src = getValue(SrcV); 4253 // Create a virtual register, then update the virtual register. 4254 Register VReg = 4255 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4256 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4257 // Chain can be getRoot or getControlRoot. 4258 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4259 SDValue(Src.getNode(), Src.getResNo())); 4260 DAG.setRoot(CopyNode); 4261 } 4262 4263 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4264 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4265 "call visitLoadFromSwiftError when backend supports swifterror"); 4266 4267 assert(!I.isVolatile() && 4268 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4269 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4270 "Support volatile, non temporal, invariant for load_from_swift_error"); 4271 4272 const Value *SV = I.getOperand(0); 4273 Type *Ty = I.getType(); 4274 assert( 4275 (!AA || 4276 !AA->pointsToConstantMemory(MemoryLocation( 4277 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4278 I.getAAMetadata()))) && 4279 "load_from_swift_error should not be constant memory"); 4280 4281 SmallVector<EVT, 4> ValueVTs; 4282 SmallVector<uint64_t, 4> Offsets; 4283 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4284 ValueVTs, &Offsets); 4285 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4286 "expect a single EVT for swifterror"); 4287 4288 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4289 SDValue L = DAG.getCopyFromReg( 4290 getRoot(), getCurSDLoc(), 4291 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4292 4293 setValue(&I, L); 4294 } 4295 4296 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4297 if (I.isAtomic()) 4298 return visitAtomicStore(I); 4299 4300 const Value *SrcV = I.getOperand(0); 4301 const Value *PtrV = I.getOperand(1); 4302 4303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4304 if (TLI.supportSwiftError()) { 4305 // Swifterror values can come from either a function parameter with 4306 // swifterror attribute or an alloca with swifterror attribute. 4307 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4308 if (Arg->hasSwiftErrorAttr()) 4309 return visitStoreToSwiftError(I); 4310 } 4311 4312 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4313 if (Alloca->isSwiftError()) 4314 return visitStoreToSwiftError(I); 4315 } 4316 } 4317 4318 SmallVector<EVT, 4> ValueVTs, MemVTs; 4319 SmallVector<uint64_t, 4> Offsets; 4320 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4321 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4322 unsigned NumValues = ValueVTs.size(); 4323 if (NumValues == 0) 4324 return; 4325 4326 // Get the lowered operands. Note that we do this after 4327 // checking if NumResults is zero, because with zero results 4328 // the operands won't have values in the map. 4329 SDValue Src = getValue(SrcV); 4330 SDValue Ptr = getValue(PtrV); 4331 4332 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4333 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4334 SDLoc dl = getCurSDLoc(); 4335 Align Alignment = I.getAlign(); 4336 AAMDNodes AAInfo = I.getAAMetadata(); 4337 4338 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4339 4340 // An aggregate load cannot wrap around the address space, so offsets to its 4341 // parts don't wrap either. 4342 SDNodeFlags Flags; 4343 Flags.setNoUnsignedWrap(true); 4344 4345 unsigned ChainI = 0; 4346 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4347 // See visitLoad comments. 4348 if (ChainI == MaxParallelChains) { 4349 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4350 ArrayRef(Chains.data(), ChainI)); 4351 Root = Chain; 4352 ChainI = 0; 4353 } 4354 SDValue Add = 4355 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4356 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4357 if (MemVTs[i] != ValueVTs[i]) 4358 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4359 SDValue St = 4360 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4361 Alignment, MMOFlags, AAInfo); 4362 Chains[ChainI] = St; 4363 } 4364 4365 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4366 ArrayRef(Chains.data(), ChainI)); 4367 setValue(&I, StoreNode); 4368 DAG.setRoot(StoreNode); 4369 } 4370 4371 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4372 bool IsCompressing) { 4373 SDLoc sdl = getCurSDLoc(); 4374 4375 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4376 MaybeAlign &Alignment) { 4377 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4378 Src0 = I.getArgOperand(0); 4379 Ptr = I.getArgOperand(1); 4380 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4381 Mask = I.getArgOperand(3); 4382 }; 4383 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4384 MaybeAlign &Alignment) { 4385 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4386 Src0 = I.getArgOperand(0); 4387 Ptr = I.getArgOperand(1); 4388 Mask = I.getArgOperand(2); 4389 Alignment = std::nullopt; 4390 }; 4391 4392 Value *PtrOperand, *MaskOperand, *Src0Operand; 4393 MaybeAlign Alignment; 4394 if (IsCompressing) 4395 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4396 else 4397 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4398 4399 SDValue Ptr = getValue(PtrOperand); 4400 SDValue Src0 = getValue(Src0Operand); 4401 SDValue Mask = getValue(MaskOperand); 4402 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4403 4404 EVT VT = Src0.getValueType(); 4405 if (!Alignment) 4406 Alignment = DAG.getEVTAlign(VT); 4407 4408 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4409 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4410 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4411 SDValue StoreNode = 4412 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4413 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4414 DAG.setRoot(StoreNode); 4415 setValue(&I, StoreNode); 4416 } 4417 4418 // Get a uniform base for the Gather/Scatter intrinsic. 4419 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4420 // We try to represent it as a base pointer + vector of indices. 4421 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4422 // The first operand of the GEP may be a single pointer or a vector of pointers 4423 // Example: 4424 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4425 // or 4426 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4427 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4428 // 4429 // When the first GEP operand is a single pointer - it is the uniform base we 4430 // are looking for. If first operand of the GEP is a splat vector - we 4431 // extract the splat value and use it as a uniform base. 4432 // In all other cases the function returns 'false'. 4433 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4434 ISD::MemIndexType &IndexType, SDValue &Scale, 4435 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4436 uint64_t ElemSize) { 4437 SelectionDAG& DAG = SDB->DAG; 4438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4439 const DataLayout &DL = DAG.getDataLayout(); 4440 4441 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4442 4443 // Handle splat constant pointer. 4444 if (auto *C = dyn_cast<Constant>(Ptr)) { 4445 C = C->getSplatValue(); 4446 if (!C) 4447 return false; 4448 4449 Base = SDB->getValue(C); 4450 4451 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4452 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4453 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4454 IndexType = ISD::SIGNED_SCALED; 4455 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4456 return true; 4457 } 4458 4459 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4460 if (!GEP || GEP->getParent() != CurBB) 4461 return false; 4462 4463 if (GEP->getNumOperands() != 2) 4464 return false; 4465 4466 const Value *BasePtr = GEP->getPointerOperand(); 4467 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4468 4469 // Make sure the base is scalar and the index is a vector. 4470 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4471 return false; 4472 4473 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4474 4475 // Target may not support the required addressing mode. 4476 if (ScaleVal != 1 && 4477 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4478 return false; 4479 4480 Base = SDB->getValue(BasePtr); 4481 Index = SDB->getValue(IndexVal); 4482 IndexType = ISD::SIGNED_SCALED; 4483 4484 Scale = 4485 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4486 return true; 4487 } 4488 4489 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4490 SDLoc sdl = getCurSDLoc(); 4491 4492 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4493 const Value *Ptr = I.getArgOperand(1); 4494 SDValue Src0 = getValue(I.getArgOperand(0)); 4495 SDValue Mask = getValue(I.getArgOperand(3)); 4496 EVT VT = Src0.getValueType(); 4497 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4498 ->getMaybeAlignValue() 4499 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4500 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4501 4502 SDValue Base; 4503 SDValue Index; 4504 ISD::MemIndexType IndexType; 4505 SDValue Scale; 4506 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4507 I.getParent(), VT.getScalarStoreSize()); 4508 4509 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4510 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4511 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4512 // TODO: Make MachineMemOperands aware of scalable 4513 // vectors. 4514 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4515 if (!UniformBase) { 4516 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4517 Index = getValue(Ptr); 4518 IndexType = ISD::SIGNED_SCALED; 4519 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4520 } 4521 4522 EVT IdxVT = Index.getValueType(); 4523 EVT EltTy = IdxVT.getVectorElementType(); 4524 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4525 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4526 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4527 } 4528 4529 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4530 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4531 Ops, MMO, IndexType, false); 4532 DAG.setRoot(Scatter); 4533 setValue(&I, Scatter); 4534 } 4535 4536 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4537 SDLoc sdl = getCurSDLoc(); 4538 4539 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4540 MaybeAlign &Alignment) { 4541 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4542 Ptr = I.getArgOperand(0); 4543 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4544 Mask = I.getArgOperand(2); 4545 Src0 = I.getArgOperand(3); 4546 }; 4547 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4548 MaybeAlign &Alignment) { 4549 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4550 Ptr = I.getArgOperand(0); 4551 Alignment = std::nullopt; 4552 Mask = I.getArgOperand(1); 4553 Src0 = I.getArgOperand(2); 4554 }; 4555 4556 Value *PtrOperand, *MaskOperand, *Src0Operand; 4557 MaybeAlign Alignment; 4558 if (IsExpanding) 4559 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4560 else 4561 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4562 4563 SDValue Ptr = getValue(PtrOperand); 4564 SDValue Src0 = getValue(Src0Operand); 4565 SDValue Mask = getValue(MaskOperand); 4566 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4567 4568 EVT VT = Src0.getValueType(); 4569 if (!Alignment) 4570 Alignment = DAG.getEVTAlign(VT); 4571 4572 AAMDNodes AAInfo = I.getAAMetadata(); 4573 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4574 4575 // Do not serialize masked loads of constant memory with anything. 4576 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4577 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4578 4579 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4580 4581 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4582 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4583 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4584 4585 SDValue Load = 4586 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4587 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4588 if (AddToChain) 4589 PendingLoads.push_back(Load.getValue(1)); 4590 setValue(&I, Load); 4591 } 4592 4593 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4594 SDLoc sdl = getCurSDLoc(); 4595 4596 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4597 const Value *Ptr = I.getArgOperand(0); 4598 SDValue Src0 = getValue(I.getArgOperand(3)); 4599 SDValue Mask = getValue(I.getArgOperand(2)); 4600 4601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4602 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4603 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4604 ->getMaybeAlignValue() 4605 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4606 4607 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4608 4609 SDValue Root = DAG.getRoot(); 4610 SDValue Base; 4611 SDValue Index; 4612 ISD::MemIndexType IndexType; 4613 SDValue Scale; 4614 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4615 I.getParent(), VT.getScalarStoreSize()); 4616 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4617 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4618 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4619 // TODO: Make MachineMemOperands aware of scalable 4620 // vectors. 4621 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4622 4623 if (!UniformBase) { 4624 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4625 Index = getValue(Ptr); 4626 IndexType = ISD::SIGNED_SCALED; 4627 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4628 } 4629 4630 EVT IdxVT = Index.getValueType(); 4631 EVT EltTy = IdxVT.getVectorElementType(); 4632 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4633 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4634 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4635 } 4636 4637 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4638 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4639 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4640 4641 PendingLoads.push_back(Gather.getValue(1)); 4642 setValue(&I, Gather); 4643 } 4644 4645 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4646 SDLoc dl = getCurSDLoc(); 4647 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4648 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4649 SyncScope::ID SSID = I.getSyncScopeID(); 4650 4651 SDValue InChain = getRoot(); 4652 4653 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4654 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4655 4656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4657 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4658 4659 MachineFunction &MF = DAG.getMachineFunction(); 4660 MachineMemOperand *MMO = MF.getMachineMemOperand( 4661 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4662 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4663 FailureOrdering); 4664 4665 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4666 dl, MemVT, VTs, InChain, 4667 getValue(I.getPointerOperand()), 4668 getValue(I.getCompareOperand()), 4669 getValue(I.getNewValOperand()), MMO); 4670 4671 SDValue OutChain = L.getValue(2); 4672 4673 setValue(&I, L); 4674 DAG.setRoot(OutChain); 4675 } 4676 4677 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4678 SDLoc dl = getCurSDLoc(); 4679 ISD::NodeType NT; 4680 switch (I.getOperation()) { 4681 default: llvm_unreachable("Unknown atomicrmw operation"); 4682 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4683 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4684 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4685 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4686 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4687 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4688 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4689 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4690 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4691 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4692 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4693 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4694 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4695 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4696 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4697 case AtomicRMWInst::UIncWrap: 4698 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4699 break; 4700 case AtomicRMWInst::UDecWrap: 4701 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4702 break; 4703 } 4704 AtomicOrdering Ordering = I.getOrdering(); 4705 SyncScope::ID SSID = I.getSyncScopeID(); 4706 4707 SDValue InChain = getRoot(); 4708 4709 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4711 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4712 4713 MachineFunction &MF = DAG.getMachineFunction(); 4714 MachineMemOperand *MMO = MF.getMachineMemOperand( 4715 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4716 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4717 4718 SDValue L = 4719 DAG.getAtomic(NT, dl, MemVT, InChain, 4720 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4721 MMO); 4722 4723 SDValue OutChain = L.getValue(1); 4724 4725 setValue(&I, L); 4726 DAG.setRoot(OutChain); 4727 } 4728 4729 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4730 SDLoc dl = getCurSDLoc(); 4731 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4732 SDValue Ops[3]; 4733 Ops[0] = getRoot(); 4734 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4735 TLI.getFenceOperandTy(DAG.getDataLayout())); 4736 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4737 TLI.getFenceOperandTy(DAG.getDataLayout())); 4738 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4739 setValue(&I, N); 4740 DAG.setRoot(N); 4741 } 4742 4743 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4744 SDLoc dl = getCurSDLoc(); 4745 AtomicOrdering Order = I.getOrdering(); 4746 SyncScope::ID SSID = I.getSyncScopeID(); 4747 4748 SDValue InChain = getRoot(); 4749 4750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4751 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4752 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4753 4754 if (!TLI.supportsUnalignedAtomics() && 4755 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4756 report_fatal_error("Cannot generate unaligned atomic load"); 4757 4758 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4759 4760 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4761 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4762 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4763 4764 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4765 4766 SDValue Ptr = getValue(I.getPointerOperand()); 4767 4768 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4769 // TODO: Once this is better exercised by tests, it should be merged with 4770 // the normal path for loads to prevent future divergence. 4771 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4772 if (MemVT != VT) 4773 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4774 4775 setValue(&I, L); 4776 SDValue OutChain = L.getValue(1); 4777 if (!I.isUnordered()) 4778 DAG.setRoot(OutChain); 4779 else 4780 PendingLoads.push_back(OutChain); 4781 return; 4782 } 4783 4784 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4785 Ptr, MMO); 4786 4787 SDValue OutChain = L.getValue(1); 4788 if (MemVT != VT) 4789 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4790 4791 setValue(&I, L); 4792 DAG.setRoot(OutChain); 4793 } 4794 4795 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4796 SDLoc dl = getCurSDLoc(); 4797 4798 AtomicOrdering Ordering = I.getOrdering(); 4799 SyncScope::ID SSID = I.getSyncScopeID(); 4800 4801 SDValue InChain = getRoot(); 4802 4803 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4804 EVT MemVT = 4805 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4806 4807 if (!TLI.supportsUnalignedAtomics() && 4808 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4809 report_fatal_error("Cannot generate unaligned atomic store"); 4810 4811 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4812 4813 MachineFunction &MF = DAG.getMachineFunction(); 4814 MachineMemOperand *MMO = MF.getMachineMemOperand( 4815 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4816 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4817 4818 SDValue Val = getValue(I.getValueOperand()); 4819 if (Val.getValueType() != MemVT) 4820 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4821 SDValue Ptr = getValue(I.getPointerOperand()); 4822 4823 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4824 // TODO: Once this is better exercised by tests, it should be merged with 4825 // the normal path for stores to prevent future divergence. 4826 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4827 setValue(&I, S); 4828 DAG.setRoot(S); 4829 return; 4830 } 4831 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4832 Ptr, Val, MMO); 4833 4834 setValue(&I, OutChain); 4835 DAG.setRoot(OutChain); 4836 } 4837 4838 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4839 /// node. 4840 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4841 unsigned Intrinsic) { 4842 // Ignore the callsite's attributes. A specific call site may be marked with 4843 // readnone, but the lowering code will expect the chain based on the 4844 // definition. 4845 const Function *F = I.getCalledFunction(); 4846 bool HasChain = !F->doesNotAccessMemory(); 4847 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4848 4849 // Build the operand list. 4850 SmallVector<SDValue, 8> Ops; 4851 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4852 if (OnlyLoad) { 4853 // We don't need to serialize loads against other loads. 4854 Ops.push_back(DAG.getRoot()); 4855 } else { 4856 Ops.push_back(getRoot()); 4857 } 4858 } 4859 4860 // Info is set by getTgtMemIntrinsic 4861 TargetLowering::IntrinsicInfo Info; 4862 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4863 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4864 DAG.getMachineFunction(), 4865 Intrinsic); 4866 4867 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4868 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4869 Info.opc == ISD::INTRINSIC_W_CHAIN) 4870 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4871 TLI.getPointerTy(DAG.getDataLayout()))); 4872 4873 // Add all operands of the call to the operand list. 4874 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4875 const Value *Arg = I.getArgOperand(i); 4876 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4877 Ops.push_back(getValue(Arg)); 4878 continue; 4879 } 4880 4881 // Use TargetConstant instead of a regular constant for immarg. 4882 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4883 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4884 assert(CI->getBitWidth() <= 64 && 4885 "large intrinsic immediates not handled"); 4886 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4887 } else { 4888 Ops.push_back( 4889 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4890 } 4891 } 4892 4893 SmallVector<EVT, 4> ValueVTs; 4894 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4895 4896 if (HasChain) 4897 ValueVTs.push_back(MVT::Other); 4898 4899 SDVTList VTs = DAG.getVTList(ValueVTs); 4900 4901 // Propagate fast-math-flags from IR to node(s). 4902 SDNodeFlags Flags; 4903 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4904 Flags.copyFMF(*FPMO); 4905 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4906 4907 // Create the node. 4908 SDValue Result; 4909 // In some cases, custom collection of operands from CallInst I may be needed. 4910 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4911 if (IsTgtIntrinsic) { 4912 // This is target intrinsic that touches memory 4913 // 4914 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4915 // didn't yield anything useful. 4916 MachinePointerInfo MPI; 4917 if (Info.ptrVal) 4918 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4919 else if (Info.fallbackAddressSpace) 4920 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4921 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4922 Info.memVT, MPI, Info.align, Info.flags, 4923 Info.size, I.getAAMetadata()); 4924 } else if (!HasChain) { 4925 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4926 } else if (!I.getType()->isVoidTy()) { 4927 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4928 } else { 4929 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4930 } 4931 4932 if (HasChain) { 4933 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4934 if (OnlyLoad) 4935 PendingLoads.push_back(Chain); 4936 else 4937 DAG.setRoot(Chain); 4938 } 4939 4940 if (!I.getType()->isVoidTy()) { 4941 if (!isa<VectorType>(I.getType())) 4942 Result = lowerRangeToAssertZExt(DAG, I, Result); 4943 4944 MaybeAlign Alignment = I.getRetAlign(); 4945 4946 // Insert `assertalign` node if there's an alignment. 4947 if (InsertAssertAlign && Alignment) { 4948 Result = 4949 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4950 } 4951 4952 setValue(&I, Result); 4953 } 4954 } 4955 4956 /// GetSignificand - Get the significand and build it into a floating-point 4957 /// number with exponent of 1: 4958 /// 4959 /// Op = (Op & 0x007fffff) | 0x3f800000; 4960 /// 4961 /// where Op is the hexadecimal representation of floating point value. 4962 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4963 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4964 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4965 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4966 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4967 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4968 } 4969 4970 /// GetExponent - Get the exponent: 4971 /// 4972 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4973 /// 4974 /// where Op is the hexadecimal representation of floating point value. 4975 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4976 const TargetLowering &TLI, const SDLoc &dl) { 4977 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4978 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4979 SDValue t1 = DAG.getNode( 4980 ISD::SRL, dl, MVT::i32, t0, 4981 DAG.getConstant(23, dl, 4982 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4983 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4984 DAG.getConstant(127, dl, MVT::i32)); 4985 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4986 } 4987 4988 /// getF32Constant - Get 32-bit floating point constant. 4989 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4990 const SDLoc &dl) { 4991 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4992 MVT::f32); 4993 } 4994 4995 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4996 SelectionDAG &DAG) { 4997 // TODO: What fast-math-flags should be set on the floating-point nodes? 4998 4999 // IntegerPartOfX = ((int32_t)(t0); 5000 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5001 5002 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5003 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5004 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5005 5006 // IntegerPartOfX <<= 23; 5007 IntegerPartOfX = 5008 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5009 DAG.getConstant(23, dl, 5010 DAG.getTargetLoweringInfo().getShiftAmountTy( 5011 MVT::i32, DAG.getDataLayout()))); 5012 5013 SDValue TwoToFractionalPartOfX; 5014 if (LimitFloatPrecision <= 6) { 5015 // For floating-point precision of 6: 5016 // 5017 // TwoToFractionalPartOfX = 5018 // 0.997535578f + 5019 // (0.735607626f + 0.252464424f * x) * x; 5020 // 5021 // error 0.0144103317, which is 6 bits 5022 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5023 getF32Constant(DAG, 0x3e814304, dl)); 5024 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5025 getF32Constant(DAG, 0x3f3c50c8, dl)); 5026 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5027 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5028 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5029 } else if (LimitFloatPrecision <= 12) { 5030 // For floating-point precision of 12: 5031 // 5032 // TwoToFractionalPartOfX = 5033 // 0.999892986f + 5034 // (0.696457318f + 5035 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5036 // 5037 // error 0.000107046256, which is 13 to 14 bits 5038 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5039 getF32Constant(DAG, 0x3da235e3, dl)); 5040 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5041 getF32Constant(DAG, 0x3e65b8f3, dl)); 5042 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5043 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5044 getF32Constant(DAG, 0x3f324b07, dl)); 5045 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5046 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5047 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5048 } else { // LimitFloatPrecision <= 18 5049 // For floating-point precision of 18: 5050 // 5051 // TwoToFractionalPartOfX = 5052 // 0.999999982f + 5053 // (0.693148872f + 5054 // (0.240227044f + 5055 // (0.554906021e-1f + 5056 // (0.961591928e-2f + 5057 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5058 // error 2.47208000*10^(-7), which is better than 18 bits 5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5060 getF32Constant(DAG, 0x3924b03e, dl)); 5061 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5062 getF32Constant(DAG, 0x3ab24b87, dl)); 5063 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5064 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5065 getF32Constant(DAG, 0x3c1d8c17, dl)); 5066 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5067 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5068 getF32Constant(DAG, 0x3d634a1d, dl)); 5069 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5070 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5071 getF32Constant(DAG, 0x3e75fe14, dl)); 5072 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5073 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5074 getF32Constant(DAG, 0x3f317234, dl)); 5075 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5076 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5077 getF32Constant(DAG, 0x3f800000, dl)); 5078 } 5079 5080 // Add the exponent into the result in integer domain. 5081 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5082 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5083 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5084 } 5085 5086 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5087 /// limited-precision mode. 5088 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5089 const TargetLowering &TLI, SDNodeFlags Flags) { 5090 if (Op.getValueType() == MVT::f32 && 5091 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5092 5093 // Put the exponent in the right bit position for later addition to the 5094 // final result: 5095 // 5096 // t0 = Op * log2(e) 5097 5098 // TODO: What fast-math-flags should be set here? 5099 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5100 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5101 return getLimitedPrecisionExp2(t0, dl, DAG); 5102 } 5103 5104 // No special expansion. 5105 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5106 } 5107 5108 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5109 /// limited-precision mode. 5110 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5111 const TargetLowering &TLI, SDNodeFlags Flags) { 5112 // TODO: What fast-math-flags should be set on the floating-point nodes? 5113 5114 if (Op.getValueType() == MVT::f32 && 5115 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5116 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5117 5118 // Scale the exponent by log(2). 5119 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5120 SDValue LogOfExponent = 5121 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5122 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5123 5124 // Get the significand and build it into a floating-point number with 5125 // exponent of 1. 5126 SDValue X = GetSignificand(DAG, Op1, dl); 5127 5128 SDValue LogOfMantissa; 5129 if (LimitFloatPrecision <= 6) { 5130 // For floating-point precision of 6: 5131 // 5132 // LogofMantissa = 5133 // -1.1609546f + 5134 // (1.4034025f - 0.23903021f * x) * x; 5135 // 5136 // error 0.0034276066, which is better than 8 bits 5137 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5138 getF32Constant(DAG, 0xbe74c456, dl)); 5139 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5140 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5141 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5142 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5143 getF32Constant(DAG, 0x3f949a29, dl)); 5144 } else if (LimitFloatPrecision <= 12) { 5145 // For floating-point precision of 12: 5146 // 5147 // LogOfMantissa = 5148 // -1.7417939f + 5149 // (2.8212026f + 5150 // (-1.4699568f + 5151 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5152 // 5153 // error 0.000061011436, which is 14 bits 5154 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5155 getF32Constant(DAG, 0xbd67b6d6, dl)); 5156 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5157 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5158 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5159 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5160 getF32Constant(DAG, 0x3fbc278b, dl)); 5161 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5162 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5163 getF32Constant(DAG, 0x40348e95, dl)); 5164 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5165 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5166 getF32Constant(DAG, 0x3fdef31a, dl)); 5167 } else { // LimitFloatPrecision <= 18 5168 // For floating-point precision of 18: 5169 // 5170 // LogOfMantissa = 5171 // -2.1072184f + 5172 // (4.2372794f + 5173 // (-3.7029485f + 5174 // (2.2781945f + 5175 // (-0.87823314f + 5176 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5177 // 5178 // error 0.0000023660568, which is better than 18 bits 5179 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5180 getF32Constant(DAG, 0xbc91e5ac, dl)); 5181 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5182 getF32Constant(DAG, 0x3e4350aa, dl)); 5183 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5184 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5185 getF32Constant(DAG, 0x3f60d3e3, dl)); 5186 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5187 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5188 getF32Constant(DAG, 0x4011cdf0, dl)); 5189 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5190 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5191 getF32Constant(DAG, 0x406cfd1c, dl)); 5192 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5193 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5194 getF32Constant(DAG, 0x408797cb, dl)); 5195 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5196 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5197 getF32Constant(DAG, 0x4006dcab, dl)); 5198 } 5199 5200 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5201 } 5202 5203 // No special expansion. 5204 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5205 } 5206 5207 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5208 /// limited-precision mode. 5209 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5210 const TargetLowering &TLI, SDNodeFlags Flags) { 5211 // TODO: What fast-math-flags should be set on the floating-point nodes? 5212 5213 if (Op.getValueType() == MVT::f32 && 5214 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5215 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5216 5217 // Get the exponent. 5218 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5219 5220 // Get the significand and build it into a floating-point number with 5221 // exponent of 1. 5222 SDValue X = GetSignificand(DAG, Op1, dl); 5223 5224 // Different possible minimax approximations of significand in 5225 // floating-point for various degrees of accuracy over [1,2]. 5226 SDValue Log2ofMantissa; 5227 if (LimitFloatPrecision <= 6) { 5228 // For floating-point precision of 6: 5229 // 5230 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5231 // 5232 // error 0.0049451742, which is more than 7 bits 5233 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5234 getF32Constant(DAG, 0xbeb08fe0, dl)); 5235 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5236 getF32Constant(DAG, 0x40019463, dl)); 5237 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5238 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5239 getF32Constant(DAG, 0x3fd6633d, dl)); 5240 } else if (LimitFloatPrecision <= 12) { 5241 // For floating-point precision of 12: 5242 // 5243 // Log2ofMantissa = 5244 // -2.51285454f + 5245 // (4.07009056f + 5246 // (-2.12067489f + 5247 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5248 // 5249 // error 0.0000876136000, which is better than 13 bits 5250 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5251 getF32Constant(DAG, 0xbda7262e, dl)); 5252 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5253 getF32Constant(DAG, 0x3f25280b, dl)); 5254 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5255 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5256 getF32Constant(DAG, 0x4007b923, dl)); 5257 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5258 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5259 getF32Constant(DAG, 0x40823e2f, dl)); 5260 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5261 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5262 getF32Constant(DAG, 0x4020d29c, dl)); 5263 } else { // LimitFloatPrecision <= 18 5264 // For floating-point precision of 18: 5265 // 5266 // Log2ofMantissa = 5267 // -3.0400495f + 5268 // (6.1129976f + 5269 // (-5.3420409f + 5270 // (3.2865683f + 5271 // (-1.2669343f + 5272 // (0.27515199f - 5273 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5274 // 5275 // error 0.0000018516, which is better than 18 bits 5276 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5277 getF32Constant(DAG, 0xbcd2769e, dl)); 5278 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5279 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5280 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5281 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5282 getF32Constant(DAG, 0x3fa22ae7, dl)); 5283 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5284 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5285 getF32Constant(DAG, 0x40525723, dl)); 5286 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5287 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5288 getF32Constant(DAG, 0x40aaf200, dl)); 5289 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5290 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5291 getF32Constant(DAG, 0x40c39dad, dl)); 5292 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5293 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5294 getF32Constant(DAG, 0x4042902c, dl)); 5295 } 5296 5297 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5298 } 5299 5300 // No special expansion. 5301 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5302 } 5303 5304 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5305 /// limited-precision mode. 5306 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5307 const TargetLowering &TLI, SDNodeFlags Flags) { 5308 // TODO: What fast-math-flags should be set on the floating-point nodes? 5309 5310 if (Op.getValueType() == MVT::f32 && 5311 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5312 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5313 5314 // Scale the exponent by log10(2) [0.30102999f]. 5315 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5316 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5317 getF32Constant(DAG, 0x3e9a209a, dl)); 5318 5319 // Get the significand and build it into a floating-point number with 5320 // exponent of 1. 5321 SDValue X = GetSignificand(DAG, Op1, dl); 5322 5323 SDValue Log10ofMantissa; 5324 if (LimitFloatPrecision <= 6) { 5325 // For floating-point precision of 6: 5326 // 5327 // Log10ofMantissa = 5328 // -0.50419619f + 5329 // (0.60948995f - 0.10380950f * x) * x; 5330 // 5331 // error 0.0014886165, which is 6 bits 5332 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5333 getF32Constant(DAG, 0xbdd49a13, dl)); 5334 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5335 getF32Constant(DAG, 0x3f1c0789, dl)); 5336 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5337 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5338 getF32Constant(DAG, 0x3f011300, dl)); 5339 } else if (LimitFloatPrecision <= 12) { 5340 // For floating-point precision of 12: 5341 // 5342 // Log10ofMantissa = 5343 // -0.64831180f + 5344 // (0.91751397f + 5345 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5346 // 5347 // error 0.00019228036, which is better than 12 bits 5348 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5349 getF32Constant(DAG, 0x3d431f31, dl)); 5350 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5351 getF32Constant(DAG, 0x3ea21fb2, dl)); 5352 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5353 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5354 getF32Constant(DAG, 0x3f6ae232, dl)); 5355 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5356 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5357 getF32Constant(DAG, 0x3f25f7c3, dl)); 5358 } else { // LimitFloatPrecision <= 18 5359 // For floating-point precision of 18: 5360 // 5361 // Log10ofMantissa = 5362 // -0.84299375f + 5363 // (1.5327582f + 5364 // (-1.0688956f + 5365 // (0.49102474f + 5366 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5367 // 5368 // error 0.0000037995730, which is better than 18 bits 5369 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5370 getF32Constant(DAG, 0x3c5d51ce, dl)); 5371 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5372 getF32Constant(DAG, 0x3e00685a, dl)); 5373 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5374 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5375 getF32Constant(DAG, 0x3efb6798, dl)); 5376 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5377 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5378 getF32Constant(DAG, 0x3f88d192, dl)); 5379 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5380 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5381 getF32Constant(DAG, 0x3fc4316c, dl)); 5382 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5383 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5384 getF32Constant(DAG, 0x3f57ce70, dl)); 5385 } 5386 5387 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5388 } 5389 5390 // No special expansion. 5391 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5392 } 5393 5394 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5395 /// limited-precision mode. 5396 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5397 const TargetLowering &TLI, SDNodeFlags Flags) { 5398 if (Op.getValueType() == MVT::f32 && 5399 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5400 return getLimitedPrecisionExp2(Op, dl, DAG); 5401 5402 // No special expansion. 5403 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5404 } 5405 5406 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5407 /// limited-precision mode with x == 10.0f. 5408 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5409 SelectionDAG &DAG, const TargetLowering &TLI, 5410 SDNodeFlags Flags) { 5411 bool IsExp10 = false; 5412 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5413 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5414 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5415 APFloat Ten(10.0f); 5416 IsExp10 = LHSC->isExactlyValue(Ten); 5417 } 5418 } 5419 5420 // TODO: What fast-math-flags should be set on the FMUL node? 5421 if (IsExp10) { 5422 // Put the exponent in the right bit position for later addition to the 5423 // final result: 5424 // 5425 // #define LOG2OF10 3.3219281f 5426 // t0 = Op * LOG2OF10; 5427 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5428 getF32Constant(DAG, 0x40549a78, dl)); 5429 return getLimitedPrecisionExp2(t0, dl, DAG); 5430 } 5431 5432 // No special expansion. 5433 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5434 } 5435 5436 /// ExpandPowI - Expand a llvm.powi intrinsic. 5437 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5438 SelectionDAG &DAG) { 5439 // If RHS is a constant, we can expand this out to a multiplication tree if 5440 // it's beneficial on the target, otherwise we end up lowering to a call to 5441 // __powidf2 (for example). 5442 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5443 unsigned Val = RHSC->getSExtValue(); 5444 5445 // powi(x, 0) -> 1.0 5446 if (Val == 0) 5447 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5448 5449 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5450 Val, DAG.shouldOptForSize())) { 5451 // Get the exponent as a positive value. 5452 if ((int)Val < 0) 5453 Val = -Val; 5454 // We use the simple binary decomposition method to generate the multiply 5455 // sequence. There are more optimal ways to do this (for example, 5456 // powi(x,15) generates one more multiply than it should), but this has 5457 // the benefit of being both really simple and much better than a libcall. 5458 SDValue Res; // Logically starts equal to 1.0 5459 SDValue CurSquare = LHS; 5460 // TODO: Intrinsics should have fast-math-flags that propagate to these 5461 // nodes. 5462 while (Val) { 5463 if (Val & 1) { 5464 if (Res.getNode()) 5465 Res = 5466 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5467 else 5468 Res = CurSquare; // 1.0*CurSquare. 5469 } 5470 5471 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5472 CurSquare, CurSquare); 5473 Val >>= 1; 5474 } 5475 5476 // If the original was negative, invert the result, producing 1/(x*x*x). 5477 if (RHSC->getSExtValue() < 0) 5478 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5479 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5480 return Res; 5481 } 5482 } 5483 5484 // Otherwise, expand to a libcall. 5485 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5486 } 5487 5488 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5489 SDValue LHS, SDValue RHS, SDValue Scale, 5490 SelectionDAG &DAG, const TargetLowering &TLI) { 5491 EVT VT = LHS.getValueType(); 5492 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5493 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5494 LLVMContext &Ctx = *DAG.getContext(); 5495 5496 // If the type is legal but the operation isn't, this node might survive all 5497 // the way to operation legalization. If we end up there and we do not have 5498 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5499 // node. 5500 5501 // Coax the legalizer into expanding the node during type legalization instead 5502 // by bumping the size by one bit. This will force it to Promote, enabling the 5503 // early expansion and avoiding the need to expand later. 5504 5505 // We don't have to do this if Scale is 0; that can always be expanded, unless 5506 // it's a saturating signed operation. Those can experience true integer 5507 // division overflow, a case which we must avoid. 5508 5509 // FIXME: We wouldn't have to do this (or any of the early 5510 // expansion/promotion) if it was possible to expand a libcall of an 5511 // illegal type during operation legalization. But it's not, so things 5512 // get a bit hacky. 5513 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5514 if ((ScaleInt > 0 || (Saturating && Signed)) && 5515 (TLI.isTypeLegal(VT) || 5516 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5517 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5518 Opcode, VT, ScaleInt); 5519 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5520 EVT PromVT; 5521 if (VT.isScalarInteger()) 5522 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5523 else if (VT.isVector()) { 5524 PromVT = VT.getVectorElementType(); 5525 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5526 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5527 } else 5528 llvm_unreachable("Wrong VT for DIVFIX?"); 5529 if (Signed) { 5530 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5531 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5532 } else { 5533 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5534 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5535 } 5536 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5537 // For saturating operations, we need to shift up the LHS to get the 5538 // proper saturation width, and then shift down again afterwards. 5539 if (Saturating) 5540 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5541 DAG.getConstant(1, DL, ShiftTy)); 5542 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5543 if (Saturating) 5544 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5545 DAG.getConstant(1, DL, ShiftTy)); 5546 return DAG.getZExtOrTrunc(Res, DL, VT); 5547 } 5548 } 5549 5550 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5551 } 5552 5553 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5554 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5555 static void 5556 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5557 const SDValue &N) { 5558 switch (N.getOpcode()) { 5559 case ISD::CopyFromReg: { 5560 SDValue Op = N.getOperand(1); 5561 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5562 Op.getValueType().getSizeInBits()); 5563 return; 5564 } 5565 case ISD::BITCAST: 5566 case ISD::AssertZext: 5567 case ISD::AssertSext: 5568 case ISD::TRUNCATE: 5569 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5570 return; 5571 case ISD::BUILD_PAIR: 5572 case ISD::BUILD_VECTOR: 5573 case ISD::CONCAT_VECTORS: 5574 for (SDValue Op : N->op_values()) 5575 getUnderlyingArgRegs(Regs, Op); 5576 return; 5577 default: 5578 return; 5579 } 5580 } 5581 5582 /// If the DbgValueInst is a dbg_value of a function argument, create the 5583 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5584 /// instruction selection, they will be inserted to the entry BB. 5585 /// We don't currently support this for variadic dbg_values, as they shouldn't 5586 /// appear for function arguments or in the prologue. 5587 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5588 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5589 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5590 const Argument *Arg = dyn_cast<Argument>(V); 5591 if (!Arg) 5592 return false; 5593 5594 MachineFunction &MF = DAG.getMachineFunction(); 5595 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5596 5597 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5598 // we've been asked to pursue. 5599 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5600 bool Indirect) { 5601 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5602 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5603 // pointing at the VReg, which will be patched up later. 5604 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5605 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5606 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5607 /* isKill */ false, /* isDead */ false, 5608 /* isUndef */ false, /* isEarlyClobber */ false, 5609 /* SubReg */ 0, /* isDebug */ true)}); 5610 5611 auto *NewDIExpr = FragExpr; 5612 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5613 // the DIExpression. 5614 if (Indirect) 5615 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5616 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5617 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5618 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5619 } else { 5620 // Create a completely standard DBG_VALUE. 5621 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5622 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5623 } 5624 }; 5625 5626 if (Kind == FuncArgumentDbgValueKind::Value) { 5627 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5628 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5629 // the entry block. 5630 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5631 if (!IsInEntryBlock) 5632 return false; 5633 5634 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5635 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5636 // variable that also is a param. 5637 // 5638 // Although, if we are at the top of the entry block already, we can still 5639 // emit using ArgDbgValue. This might catch some situations when the 5640 // dbg.value refers to an argument that isn't used in the entry block, so 5641 // any CopyToReg node would be optimized out and the only way to express 5642 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5643 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5644 // we should only emit as ArgDbgValue if the Variable is an argument to the 5645 // current function, and the dbg.value intrinsic is found in the entry 5646 // block. 5647 bool VariableIsFunctionInputArg = Variable->isParameter() && 5648 !DL->getInlinedAt(); 5649 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5650 if (!IsInPrologue && !VariableIsFunctionInputArg) 5651 return false; 5652 5653 // Here we assume that a function argument on IR level only can be used to 5654 // describe one input parameter on source level. If we for example have 5655 // source code like this 5656 // 5657 // struct A { long x, y; }; 5658 // void foo(struct A a, long b) { 5659 // ... 5660 // b = a.x; 5661 // ... 5662 // } 5663 // 5664 // and IR like this 5665 // 5666 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5667 // entry: 5668 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5669 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5670 // call void @llvm.dbg.value(metadata i32 %b, "b", 5671 // ... 5672 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5673 // ... 5674 // 5675 // then the last dbg.value is describing a parameter "b" using a value that 5676 // is an argument. But since we already has used %a1 to describe a parameter 5677 // we should not handle that last dbg.value here (that would result in an 5678 // incorrect hoisting of the DBG_VALUE to the function entry). 5679 // Notice that we allow one dbg.value per IR level argument, to accommodate 5680 // for the situation with fragments above. 5681 if (VariableIsFunctionInputArg) { 5682 unsigned ArgNo = Arg->getArgNo(); 5683 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5684 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5685 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5686 return false; 5687 FuncInfo.DescribedArgs.set(ArgNo); 5688 } 5689 } 5690 5691 bool IsIndirect = false; 5692 std::optional<MachineOperand> Op; 5693 // Some arguments' frame index is recorded during argument lowering. 5694 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5695 if (FI != std::numeric_limits<int>::max()) 5696 Op = MachineOperand::CreateFI(FI); 5697 5698 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5699 if (!Op && N.getNode()) { 5700 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5701 Register Reg; 5702 if (ArgRegsAndSizes.size() == 1) 5703 Reg = ArgRegsAndSizes.front().first; 5704 5705 if (Reg && Reg.isVirtual()) { 5706 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5707 Register PR = RegInfo.getLiveInPhysReg(Reg); 5708 if (PR) 5709 Reg = PR; 5710 } 5711 if (Reg) { 5712 Op = MachineOperand::CreateReg(Reg, false); 5713 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5714 } 5715 } 5716 5717 if (!Op && N.getNode()) { 5718 // Check if frame index is available. 5719 SDValue LCandidate = peekThroughBitcasts(N); 5720 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5721 if (FrameIndexSDNode *FINode = 5722 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5723 Op = MachineOperand::CreateFI(FINode->getIndex()); 5724 } 5725 5726 if (!Op) { 5727 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5728 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5729 SplitRegs) { 5730 unsigned Offset = 0; 5731 for (const auto &RegAndSize : SplitRegs) { 5732 // If the expression is already a fragment, the current register 5733 // offset+size might extend beyond the fragment. In this case, only 5734 // the register bits that are inside the fragment are relevant. 5735 int RegFragmentSizeInBits = RegAndSize.second; 5736 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5737 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5738 // The register is entirely outside the expression fragment, 5739 // so is irrelevant for debug info. 5740 if (Offset >= ExprFragmentSizeInBits) 5741 break; 5742 // The register is partially outside the expression fragment, only 5743 // the low bits within the fragment are relevant for debug info. 5744 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5745 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5746 } 5747 } 5748 5749 auto FragmentExpr = DIExpression::createFragmentExpression( 5750 Expr, Offset, RegFragmentSizeInBits); 5751 Offset += RegAndSize.second; 5752 // If a valid fragment expression cannot be created, the variable's 5753 // correct value cannot be determined and so it is set as Undef. 5754 if (!FragmentExpr) { 5755 SDDbgValue *SDV = DAG.getConstantDbgValue( 5756 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5757 DAG.AddDbgValue(SDV, false); 5758 continue; 5759 } 5760 MachineInstr *NewMI = 5761 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5762 Kind != FuncArgumentDbgValueKind::Value); 5763 FuncInfo.ArgDbgValues.push_back(NewMI); 5764 } 5765 }; 5766 5767 // Check if ValueMap has reg number. 5768 DenseMap<const Value *, Register>::const_iterator 5769 VMI = FuncInfo.ValueMap.find(V); 5770 if (VMI != FuncInfo.ValueMap.end()) { 5771 const auto &TLI = DAG.getTargetLoweringInfo(); 5772 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5773 V->getType(), std::nullopt); 5774 if (RFV.occupiesMultipleRegs()) { 5775 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5776 return true; 5777 } 5778 5779 Op = MachineOperand::CreateReg(VMI->second, false); 5780 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5781 } else if (ArgRegsAndSizes.size() > 1) { 5782 // This was split due to the calling convention, and no virtual register 5783 // mapping exists for the value. 5784 splitMultiRegDbgValue(ArgRegsAndSizes); 5785 return true; 5786 } 5787 } 5788 5789 if (!Op) 5790 return false; 5791 5792 assert(Variable->isValidLocationForIntrinsic(DL) && 5793 "Expected inlined-at fields to agree"); 5794 MachineInstr *NewMI = nullptr; 5795 5796 if (Op->isReg()) 5797 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5798 else 5799 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5800 Variable, Expr); 5801 5802 // Otherwise, use ArgDbgValues. 5803 FuncInfo.ArgDbgValues.push_back(NewMI); 5804 return true; 5805 } 5806 5807 /// Return the appropriate SDDbgValue based on N. 5808 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5809 DILocalVariable *Variable, 5810 DIExpression *Expr, 5811 const DebugLoc &dl, 5812 unsigned DbgSDNodeOrder) { 5813 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5814 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5815 // stack slot locations. 5816 // 5817 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5818 // debug values here after optimization: 5819 // 5820 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5821 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5822 // 5823 // Both describe the direct values of their associated variables. 5824 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5825 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5826 } 5827 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5828 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5829 } 5830 5831 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5832 switch (Intrinsic) { 5833 case Intrinsic::smul_fix: 5834 return ISD::SMULFIX; 5835 case Intrinsic::umul_fix: 5836 return ISD::UMULFIX; 5837 case Intrinsic::smul_fix_sat: 5838 return ISD::SMULFIXSAT; 5839 case Intrinsic::umul_fix_sat: 5840 return ISD::UMULFIXSAT; 5841 case Intrinsic::sdiv_fix: 5842 return ISD::SDIVFIX; 5843 case Intrinsic::udiv_fix: 5844 return ISD::UDIVFIX; 5845 case Intrinsic::sdiv_fix_sat: 5846 return ISD::SDIVFIXSAT; 5847 case Intrinsic::udiv_fix_sat: 5848 return ISD::UDIVFIXSAT; 5849 default: 5850 llvm_unreachable("Unhandled fixed point intrinsic"); 5851 } 5852 } 5853 5854 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5855 const char *FunctionName) { 5856 assert(FunctionName && "FunctionName must not be nullptr"); 5857 SDValue Callee = DAG.getExternalSymbol( 5858 FunctionName, 5859 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5860 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5861 } 5862 5863 /// Given a @llvm.call.preallocated.setup, return the corresponding 5864 /// preallocated call. 5865 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5866 assert(cast<CallBase>(PreallocatedSetup) 5867 ->getCalledFunction() 5868 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5869 "expected call_preallocated_setup Value"); 5870 for (const auto *U : PreallocatedSetup->users()) { 5871 auto *UseCall = cast<CallBase>(U); 5872 const Function *Fn = UseCall->getCalledFunction(); 5873 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5874 return UseCall; 5875 } 5876 } 5877 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5878 } 5879 5880 /// Lower the call to the specified intrinsic function. 5881 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5882 unsigned Intrinsic) { 5883 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5884 SDLoc sdl = getCurSDLoc(); 5885 DebugLoc dl = getCurDebugLoc(); 5886 SDValue Res; 5887 5888 SDNodeFlags Flags; 5889 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5890 Flags.copyFMF(*FPOp); 5891 5892 switch (Intrinsic) { 5893 default: 5894 // By default, turn this into a target intrinsic node. 5895 visitTargetIntrinsic(I, Intrinsic); 5896 return; 5897 case Intrinsic::vscale: { 5898 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5899 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5900 return; 5901 } 5902 case Intrinsic::vastart: visitVAStart(I); return; 5903 case Intrinsic::vaend: visitVAEnd(I); return; 5904 case Intrinsic::vacopy: visitVACopy(I); return; 5905 case Intrinsic::returnaddress: 5906 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5907 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5908 getValue(I.getArgOperand(0)))); 5909 return; 5910 case Intrinsic::addressofreturnaddress: 5911 setValue(&I, 5912 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5913 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5914 return; 5915 case Intrinsic::sponentry: 5916 setValue(&I, 5917 DAG.getNode(ISD::SPONENTRY, sdl, 5918 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5919 return; 5920 case Intrinsic::frameaddress: 5921 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5922 TLI.getFrameIndexTy(DAG.getDataLayout()), 5923 getValue(I.getArgOperand(0)))); 5924 return; 5925 case Intrinsic::read_volatile_register: 5926 case Intrinsic::read_register: { 5927 Value *Reg = I.getArgOperand(0); 5928 SDValue Chain = getRoot(); 5929 SDValue RegName = 5930 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5931 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5932 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5933 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5934 setValue(&I, Res); 5935 DAG.setRoot(Res.getValue(1)); 5936 return; 5937 } 5938 case Intrinsic::write_register: { 5939 Value *Reg = I.getArgOperand(0); 5940 Value *RegValue = I.getArgOperand(1); 5941 SDValue Chain = getRoot(); 5942 SDValue RegName = 5943 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5944 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5945 RegName, getValue(RegValue))); 5946 return; 5947 } 5948 case Intrinsic::memcpy: { 5949 const auto &MCI = cast<MemCpyInst>(I); 5950 SDValue Op1 = getValue(I.getArgOperand(0)); 5951 SDValue Op2 = getValue(I.getArgOperand(1)); 5952 SDValue Op3 = getValue(I.getArgOperand(2)); 5953 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5954 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5955 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5956 Align Alignment = std::min(DstAlign, SrcAlign); 5957 bool isVol = MCI.isVolatile(); 5958 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5959 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5960 // node. 5961 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5962 SDValue MC = DAG.getMemcpy( 5963 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5964 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5965 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5966 updateDAGForMaybeTailCall(MC); 5967 return; 5968 } 5969 case Intrinsic::memcpy_inline: { 5970 const auto &MCI = cast<MemCpyInlineInst>(I); 5971 SDValue Dst = getValue(I.getArgOperand(0)); 5972 SDValue Src = getValue(I.getArgOperand(1)); 5973 SDValue Size = getValue(I.getArgOperand(2)); 5974 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5975 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5976 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5977 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5978 Align Alignment = std::min(DstAlign, SrcAlign); 5979 bool isVol = MCI.isVolatile(); 5980 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5981 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5982 // node. 5983 SDValue MC = DAG.getMemcpy( 5984 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5985 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5986 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5987 updateDAGForMaybeTailCall(MC); 5988 return; 5989 } 5990 case Intrinsic::memset: { 5991 const auto &MSI = cast<MemSetInst>(I); 5992 SDValue Op1 = getValue(I.getArgOperand(0)); 5993 SDValue Op2 = getValue(I.getArgOperand(1)); 5994 SDValue Op3 = getValue(I.getArgOperand(2)); 5995 // @llvm.memset defines 0 and 1 to both mean no alignment. 5996 Align Alignment = MSI.getDestAlign().valueOrOne(); 5997 bool isVol = MSI.isVolatile(); 5998 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5999 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6000 SDValue MS = DAG.getMemset( 6001 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6002 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6003 updateDAGForMaybeTailCall(MS); 6004 return; 6005 } 6006 case Intrinsic::memset_inline: { 6007 const auto &MSII = cast<MemSetInlineInst>(I); 6008 SDValue Dst = getValue(I.getArgOperand(0)); 6009 SDValue Value = getValue(I.getArgOperand(1)); 6010 SDValue Size = getValue(I.getArgOperand(2)); 6011 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6012 // @llvm.memset defines 0 and 1 to both mean no alignment. 6013 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6014 bool isVol = MSII.isVolatile(); 6015 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6016 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6017 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6018 /* AlwaysInline */ true, isTC, 6019 MachinePointerInfo(I.getArgOperand(0)), 6020 I.getAAMetadata()); 6021 updateDAGForMaybeTailCall(MC); 6022 return; 6023 } 6024 case Intrinsic::memmove: { 6025 const auto &MMI = cast<MemMoveInst>(I); 6026 SDValue Op1 = getValue(I.getArgOperand(0)); 6027 SDValue Op2 = getValue(I.getArgOperand(1)); 6028 SDValue Op3 = getValue(I.getArgOperand(2)); 6029 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6030 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6031 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6032 Align Alignment = std::min(DstAlign, SrcAlign); 6033 bool isVol = MMI.isVolatile(); 6034 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6035 // FIXME: Support passing different dest/src alignments to the memmove DAG 6036 // node. 6037 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6038 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6039 isTC, MachinePointerInfo(I.getArgOperand(0)), 6040 MachinePointerInfo(I.getArgOperand(1)), 6041 I.getAAMetadata(), AA); 6042 updateDAGForMaybeTailCall(MM); 6043 return; 6044 } 6045 case Intrinsic::memcpy_element_unordered_atomic: { 6046 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6047 SDValue Dst = getValue(MI.getRawDest()); 6048 SDValue Src = getValue(MI.getRawSource()); 6049 SDValue Length = getValue(MI.getLength()); 6050 6051 Type *LengthTy = MI.getLength()->getType(); 6052 unsigned ElemSz = MI.getElementSizeInBytes(); 6053 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6054 SDValue MC = 6055 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6056 isTC, MachinePointerInfo(MI.getRawDest()), 6057 MachinePointerInfo(MI.getRawSource())); 6058 updateDAGForMaybeTailCall(MC); 6059 return; 6060 } 6061 case Intrinsic::memmove_element_unordered_atomic: { 6062 auto &MI = cast<AtomicMemMoveInst>(I); 6063 SDValue Dst = getValue(MI.getRawDest()); 6064 SDValue Src = getValue(MI.getRawSource()); 6065 SDValue Length = getValue(MI.getLength()); 6066 6067 Type *LengthTy = MI.getLength()->getType(); 6068 unsigned ElemSz = MI.getElementSizeInBytes(); 6069 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6070 SDValue MC = 6071 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6072 isTC, MachinePointerInfo(MI.getRawDest()), 6073 MachinePointerInfo(MI.getRawSource())); 6074 updateDAGForMaybeTailCall(MC); 6075 return; 6076 } 6077 case Intrinsic::memset_element_unordered_atomic: { 6078 auto &MI = cast<AtomicMemSetInst>(I); 6079 SDValue Dst = getValue(MI.getRawDest()); 6080 SDValue Val = getValue(MI.getValue()); 6081 SDValue Length = getValue(MI.getLength()); 6082 6083 Type *LengthTy = MI.getLength()->getType(); 6084 unsigned ElemSz = MI.getElementSizeInBytes(); 6085 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6086 SDValue MC = 6087 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6088 isTC, MachinePointerInfo(MI.getRawDest())); 6089 updateDAGForMaybeTailCall(MC); 6090 return; 6091 } 6092 case Intrinsic::call_preallocated_setup: { 6093 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6094 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6095 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6096 getRoot(), SrcValue); 6097 setValue(&I, Res); 6098 DAG.setRoot(Res); 6099 return; 6100 } 6101 case Intrinsic::call_preallocated_arg: { 6102 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6103 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6104 SDValue Ops[3]; 6105 Ops[0] = getRoot(); 6106 Ops[1] = SrcValue; 6107 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6108 MVT::i32); // arg index 6109 SDValue Res = DAG.getNode( 6110 ISD::PREALLOCATED_ARG, sdl, 6111 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6112 setValue(&I, Res); 6113 DAG.setRoot(Res.getValue(1)); 6114 return; 6115 } 6116 case Intrinsic::dbg_declare: { 6117 // Debug intrinsics are handled separately in assignment tracking mode. 6118 if (AssignmentTrackingEnabled) 6119 return; 6120 // Assume dbg.declare can not currently use DIArgList, i.e. 6121 // it is non-variadic. 6122 const auto &DI = cast<DbgVariableIntrinsic>(I); 6123 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6124 DILocalVariable *Variable = DI.getVariable(); 6125 DIExpression *Expression = DI.getExpression(); 6126 dropDanglingDebugInfo(Variable, Expression); 6127 assert(Variable && "Missing variable"); 6128 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6129 << "\n"); 6130 // Check if address has undef value. 6131 const Value *Address = DI.getVariableLocationOp(0); 6132 if (!Address || isa<UndefValue>(Address) || 6133 (Address->use_empty() && !isa<Argument>(Address))) { 6134 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6135 << " (bad/undef/unused-arg address)\n"); 6136 return; 6137 } 6138 6139 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6140 6141 // Check if this variable can be described by a frame index, typically 6142 // either as a static alloca or a byval parameter. 6143 int FI = std::numeric_limits<int>::max(); 6144 if (const auto *AI = 6145 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6146 if (AI->isStaticAlloca()) { 6147 auto I = FuncInfo.StaticAllocaMap.find(AI); 6148 if (I != FuncInfo.StaticAllocaMap.end()) 6149 FI = I->second; 6150 } 6151 } else if (const auto *Arg = dyn_cast<Argument>( 6152 Address->stripInBoundsConstantOffsets())) { 6153 FI = FuncInfo.getArgumentFrameIndex(Arg); 6154 } 6155 6156 // llvm.dbg.declare is handled as a frame index in the MachineFunction 6157 // variable table. 6158 if (FI != std::numeric_limits<int>::max()) { 6159 LLVM_DEBUG(dbgs() << "Skipping " << DI 6160 << " (variable info stashed in MF side table)\n"); 6161 return; 6162 } 6163 6164 SDValue &N = NodeMap[Address]; 6165 if (!N.getNode() && isa<Argument>(Address)) 6166 // Check unused arguments map. 6167 N = UnusedArgNodeMap[Address]; 6168 SDDbgValue *SDV; 6169 if (N.getNode()) { 6170 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6171 Address = BCI->getOperand(0); 6172 // Parameters are handled specially. 6173 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6174 if (isParameter && FINode) { 6175 // Byval parameter. We have a frame index at this point. 6176 SDV = 6177 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6178 /*IsIndirect*/ true, dl, SDNodeOrder); 6179 } else if (isa<Argument>(Address)) { 6180 // Address is an argument, so try to emit its dbg value using 6181 // virtual register info from the FuncInfo.ValueMap. 6182 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6183 FuncArgumentDbgValueKind::Declare, N); 6184 return; 6185 } else { 6186 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6187 true, dl, SDNodeOrder); 6188 } 6189 DAG.AddDbgValue(SDV, isParameter); 6190 } else { 6191 // If Address is an argument then try to emit its dbg value using 6192 // virtual register info from the FuncInfo.ValueMap. 6193 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6194 FuncArgumentDbgValueKind::Declare, N)) { 6195 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6196 << " (could not emit func-arg dbg_value)\n"); 6197 } 6198 } 6199 return; 6200 } 6201 case Intrinsic::dbg_label: { 6202 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6203 DILabel *Label = DI.getLabel(); 6204 assert(Label && "Missing label"); 6205 6206 SDDbgLabel *SDV; 6207 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6208 DAG.AddDbgLabel(SDV); 6209 return; 6210 } 6211 case Intrinsic::dbg_assign: { 6212 // Debug intrinsics are handled seperately in assignment tracking mode. 6213 assert(AssignmentTrackingEnabled && 6214 "expected assignment tracking to be enabled"); 6215 return; 6216 } 6217 case Intrinsic::dbg_value: { 6218 // Debug intrinsics are handled seperately in assignment tracking mode. 6219 if (AssignmentTrackingEnabled) 6220 return; 6221 const DbgValueInst &DI = cast<DbgValueInst>(I); 6222 assert(DI.getVariable() && "Missing variable"); 6223 6224 DILocalVariable *Variable = DI.getVariable(); 6225 DIExpression *Expression = DI.getExpression(); 6226 dropDanglingDebugInfo(Variable, Expression); 6227 SmallVector<Value *, 4> Values(DI.getValues()); 6228 if (Values.empty()) 6229 return; 6230 6231 if (llvm::is_contained(Values, nullptr)) 6232 return; 6233 6234 bool IsVariadic = DI.hasArgList(); 6235 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6236 SDNodeOrder, IsVariadic)) 6237 addDanglingDebugInfo(&DI, SDNodeOrder); 6238 return; 6239 } 6240 6241 case Intrinsic::eh_typeid_for: { 6242 // Find the type id for the given typeinfo. 6243 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6244 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6245 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6246 setValue(&I, Res); 6247 return; 6248 } 6249 6250 case Intrinsic::eh_return_i32: 6251 case Intrinsic::eh_return_i64: 6252 DAG.getMachineFunction().setCallsEHReturn(true); 6253 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6254 MVT::Other, 6255 getControlRoot(), 6256 getValue(I.getArgOperand(0)), 6257 getValue(I.getArgOperand(1)))); 6258 return; 6259 case Intrinsic::eh_unwind_init: 6260 DAG.getMachineFunction().setCallsUnwindInit(true); 6261 return; 6262 case Intrinsic::eh_dwarf_cfa: 6263 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6264 TLI.getPointerTy(DAG.getDataLayout()), 6265 getValue(I.getArgOperand(0)))); 6266 return; 6267 case Intrinsic::eh_sjlj_callsite: { 6268 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6269 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6270 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6271 6272 MMI.setCurrentCallSite(CI->getZExtValue()); 6273 return; 6274 } 6275 case Intrinsic::eh_sjlj_functioncontext: { 6276 // Get and store the index of the function context. 6277 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6278 AllocaInst *FnCtx = 6279 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6280 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6281 MFI.setFunctionContextIndex(FI); 6282 return; 6283 } 6284 case Intrinsic::eh_sjlj_setjmp: { 6285 SDValue Ops[2]; 6286 Ops[0] = getRoot(); 6287 Ops[1] = getValue(I.getArgOperand(0)); 6288 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6289 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6290 setValue(&I, Op.getValue(0)); 6291 DAG.setRoot(Op.getValue(1)); 6292 return; 6293 } 6294 case Intrinsic::eh_sjlj_longjmp: 6295 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6296 getRoot(), getValue(I.getArgOperand(0)))); 6297 return; 6298 case Intrinsic::eh_sjlj_setup_dispatch: 6299 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6300 getRoot())); 6301 return; 6302 case Intrinsic::masked_gather: 6303 visitMaskedGather(I); 6304 return; 6305 case Intrinsic::masked_load: 6306 visitMaskedLoad(I); 6307 return; 6308 case Intrinsic::masked_scatter: 6309 visitMaskedScatter(I); 6310 return; 6311 case Intrinsic::masked_store: 6312 visitMaskedStore(I); 6313 return; 6314 case Intrinsic::masked_expandload: 6315 visitMaskedLoad(I, true /* IsExpanding */); 6316 return; 6317 case Intrinsic::masked_compressstore: 6318 visitMaskedStore(I, true /* IsCompressing */); 6319 return; 6320 case Intrinsic::powi: 6321 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6322 getValue(I.getArgOperand(1)), DAG)); 6323 return; 6324 case Intrinsic::log: 6325 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6326 return; 6327 case Intrinsic::log2: 6328 setValue(&I, 6329 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6330 return; 6331 case Intrinsic::log10: 6332 setValue(&I, 6333 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6334 return; 6335 case Intrinsic::exp: 6336 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6337 return; 6338 case Intrinsic::exp2: 6339 setValue(&I, 6340 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6341 return; 6342 case Intrinsic::pow: 6343 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6344 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6345 return; 6346 case Intrinsic::sqrt: 6347 case Intrinsic::fabs: 6348 case Intrinsic::sin: 6349 case Intrinsic::cos: 6350 case Intrinsic::floor: 6351 case Intrinsic::ceil: 6352 case Intrinsic::trunc: 6353 case Intrinsic::rint: 6354 case Intrinsic::nearbyint: 6355 case Intrinsic::round: 6356 case Intrinsic::roundeven: 6357 case Intrinsic::canonicalize: { 6358 unsigned Opcode; 6359 switch (Intrinsic) { 6360 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6361 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6362 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6363 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6364 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6365 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6366 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6367 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6368 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6369 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6370 case Intrinsic::round: Opcode = ISD::FROUND; break; 6371 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6372 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6373 } 6374 6375 setValue(&I, DAG.getNode(Opcode, sdl, 6376 getValue(I.getArgOperand(0)).getValueType(), 6377 getValue(I.getArgOperand(0)), Flags)); 6378 return; 6379 } 6380 case Intrinsic::lround: 6381 case Intrinsic::llround: 6382 case Intrinsic::lrint: 6383 case Intrinsic::llrint: { 6384 unsigned Opcode; 6385 switch (Intrinsic) { 6386 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6387 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6388 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6389 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6390 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6391 } 6392 6393 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6394 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6395 getValue(I.getArgOperand(0)))); 6396 return; 6397 } 6398 case Intrinsic::minnum: 6399 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6400 getValue(I.getArgOperand(0)).getValueType(), 6401 getValue(I.getArgOperand(0)), 6402 getValue(I.getArgOperand(1)), Flags)); 6403 return; 6404 case Intrinsic::maxnum: 6405 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6406 getValue(I.getArgOperand(0)).getValueType(), 6407 getValue(I.getArgOperand(0)), 6408 getValue(I.getArgOperand(1)), Flags)); 6409 return; 6410 case Intrinsic::minimum: 6411 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6412 getValue(I.getArgOperand(0)).getValueType(), 6413 getValue(I.getArgOperand(0)), 6414 getValue(I.getArgOperand(1)), Flags)); 6415 return; 6416 case Intrinsic::maximum: 6417 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6418 getValue(I.getArgOperand(0)).getValueType(), 6419 getValue(I.getArgOperand(0)), 6420 getValue(I.getArgOperand(1)), Flags)); 6421 return; 6422 case Intrinsic::copysign: 6423 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6424 getValue(I.getArgOperand(0)).getValueType(), 6425 getValue(I.getArgOperand(0)), 6426 getValue(I.getArgOperand(1)), Flags)); 6427 return; 6428 case Intrinsic::arithmetic_fence: { 6429 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6430 getValue(I.getArgOperand(0)).getValueType(), 6431 getValue(I.getArgOperand(0)), Flags)); 6432 return; 6433 } 6434 case Intrinsic::fma: 6435 setValue(&I, DAG.getNode( 6436 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6437 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6438 getValue(I.getArgOperand(2)), Flags)); 6439 return; 6440 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6441 case Intrinsic::INTRINSIC: 6442 #include "llvm/IR/ConstrainedOps.def" 6443 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6444 return; 6445 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6446 #include "llvm/IR/VPIntrinsics.def" 6447 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6448 return; 6449 case Intrinsic::fptrunc_round: { 6450 // Get the last argument, the metadata and convert it to an integer in the 6451 // call 6452 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6453 std::optional<RoundingMode> RoundMode = 6454 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6455 6456 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6457 6458 // Propagate fast-math-flags from IR to node(s). 6459 SDNodeFlags Flags; 6460 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6461 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6462 6463 SDValue Result; 6464 Result = DAG.getNode( 6465 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6466 DAG.getTargetConstant((int)*RoundMode, sdl, 6467 TLI.getPointerTy(DAG.getDataLayout()))); 6468 setValue(&I, Result); 6469 6470 return; 6471 } 6472 case Intrinsic::fmuladd: { 6473 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6474 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6475 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6476 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6477 getValue(I.getArgOperand(0)).getValueType(), 6478 getValue(I.getArgOperand(0)), 6479 getValue(I.getArgOperand(1)), 6480 getValue(I.getArgOperand(2)), Flags)); 6481 } else { 6482 // TODO: Intrinsic calls should have fast-math-flags. 6483 SDValue Mul = DAG.getNode( 6484 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6485 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6486 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6487 getValue(I.getArgOperand(0)).getValueType(), 6488 Mul, getValue(I.getArgOperand(2)), Flags); 6489 setValue(&I, Add); 6490 } 6491 return; 6492 } 6493 case Intrinsic::convert_to_fp16: 6494 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6495 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6496 getValue(I.getArgOperand(0)), 6497 DAG.getTargetConstant(0, sdl, 6498 MVT::i32)))); 6499 return; 6500 case Intrinsic::convert_from_fp16: 6501 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6502 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6503 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6504 getValue(I.getArgOperand(0))))); 6505 return; 6506 case Intrinsic::fptosi_sat: { 6507 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6508 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6509 getValue(I.getArgOperand(0)), 6510 DAG.getValueType(VT.getScalarType()))); 6511 return; 6512 } 6513 case Intrinsic::fptoui_sat: { 6514 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6515 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6516 getValue(I.getArgOperand(0)), 6517 DAG.getValueType(VT.getScalarType()))); 6518 return; 6519 } 6520 case Intrinsic::set_rounding: 6521 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6522 {getRoot(), getValue(I.getArgOperand(0))}); 6523 setValue(&I, Res); 6524 DAG.setRoot(Res.getValue(0)); 6525 return; 6526 case Intrinsic::is_fpclass: { 6527 const DataLayout DLayout = DAG.getDataLayout(); 6528 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6529 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6530 FPClassTest Test = static_cast<FPClassTest>( 6531 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6532 MachineFunction &MF = DAG.getMachineFunction(); 6533 const Function &F = MF.getFunction(); 6534 SDValue Op = getValue(I.getArgOperand(0)); 6535 SDNodeFlags Flags; 6536 Flags.setNoFPExcept( 6537 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6538 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6539 // expansion can use illegal types. Making expansion early allows 6540 // legalizing these types prior to selection. 6541 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6542 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6543 setValue(&I, Result); 6544 return; 6545 } 6546 6547 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6548 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6549 setValue(&I, V); 6550 return; 6551 } 6552 case Intrinsic::pcmarker: { 6553 SDValue Tmp = getValue(I.getArgOperand(0)); 6554 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6555 return; 6556 } 6557 case Intrinsic::readcyclecounter: { 6558 SDValue Op = getRoot(); 6559 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6560 DAG.getVTList(MVT::i64, MVT::Other), Op); 6561 setValue(&I, Res); 6562 DAG.setRoot(Res.getValue(1)); 6563 return; 6564 } 6565 case Intrinsic::bitreverse: 6566 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6567 getValue(I.getArgOperand(0)).getValueType(), 6568 getValue(I.getArgOperand(0)))); 6569 return; 6570 case Intrinsic::bswap: 6571 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6572 getValue(I.getArgOperand(0)).getValueType(), 6573 getValue(I.getArgOperand(0)))); 6574 return; 6575 case Intrinsic::cttz: { 6576 SDValue Arg = getValue(I.getArgOperand(0)); 6577 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6578 EVT Ty = Arg.getValueType(); 6579 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6580 sdl, Ty, Arg)); 6581 return; 6582 } 6583 case Intrinsic::ctlz: { 6584 SDValue Arg = getValue(I.getArgOperand(0)); 6585 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6586 EVT Ty = Arg.getValueType(); 6587 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6588 sdl, Ty, Arg)); 6589 return; 6590 } 6591 case Intrinsic::ctpop: { 6592 SDValue Arg = getValue(I.getArgOperand(0)); 6593 EVT Ty = Arg.getValueType(); 6594 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6595 return; 6596 } 6597 case Intrinsic::fshl: 6598 case Intrinsic::fshr: { 6599 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6600 SDValue X = getValue(I.getArgOperand(0)); 6601 SDValue Y = getValue(I.getArgOperand(1)); 6602 SDValue Z = getValue(I.getArgOperand(2)); 6603 EVT VT = X.getValueType(); 6604 6605 if (X == Y) { 6606 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6607 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6608 } else { 6609 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6610 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6611 } 6612 return; 6613 } 6614 case Intrinsic::sadd_sat: { 6615 SDValue Op1 = getValue(I.getArgOperand(0)); 6616 SDValue Op2 = getValue(I.getArgOperand(1)); 6617 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6618 return; 6619 } 6620 case Intrinsic::uadd_sat: { 6621 SDValue Op1 = getValue(I.getArgOperand(0)); 6622 SDValue Op2 = getValue(I.getArgOperand(1)); 6623 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6624 return; 6625 } 6626 case Intrinsic::ssub_sat: { 6627 SDValue Op1 = getValue(I.getArgOperand(0)); 6628 SDValue Op2 = getValue(I.getArgOperand(1)); 6629 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6630 return; 6631 } 6632 case Intrinsic::usub_sat: { 6633 SDValue Op1 = getValue(I.getArgOperand(0)); 6634 SDValue Op2 = getValue(I.getArgOperand(1)); 6635 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6636 return; 6637 } 6638 case Intrinsic::sshl_sat: { 6639 SDValue Op1 = getValue(I.getArgOperand(0)); 6640 SDValue Op2 = getValue(I.getArgOperand(1)); 6641 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6642 return; 6643 } 6644 case Intrinsic::ushl_sat: { 6645 SDValue Op1 = getValue(I.getArgOperand(0)); 6646 SDValue Op2 = getValue(I.getArgOperand(1)); 6647 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6648 return; 6649 } 6650 case Intrinsic::smul_fix: 6651 case Intrinsic::umul_fix: 6652 case Intrinsic::smul_fix_sat: 6653 case Intrinsic::umul_fix_sat: { 6654 SDValue Op1 = getValue(I.getArgOperand(0)); 6655 SDValue Op2 = getValue(I.getArgOperand(1)); 6656 SDValue Op3 = getValue(I.getArgOperand(2)); 6657 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6658 Op1.getValueType(), Op1, Op2, Op3)); 6659 return; 6660 } 6661 case Intrinsic::sdiv_fix: 6662 case Intrinsic::udiv_fix: 6663 case Intrinsic::sdiv_fix_sat: 6664 case Intrinsic::udiv_fix_sat: { 6665 SDValue Op1 = getValue(I.getArgOperand(0)); 6666 SDValue Op2 = getValue(I.getArgOperand(1)); 6667 SDValue Op3 = getValue(I.getArgOperand(2)); 6668 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6669 Op1, Op2, Op3, DAG, TLI)); 6670 return; 6671 } 6672 case Intrinsic::smax: { 6673 SDValue Op1 = getValue(I.getArgOperand(0)); 6674 SDValue Op2 = getValue(I.getArgOperand(1)); 6675 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6676 return; 6677 } 6678 case Intrinsic::smin: { 6679 SDValue Op1 = getValue(I.getArgOperand(0)); 6680 SDValue Op2 = getValue(I.getArgOperand(1)); 6681 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6682 return; 6683 } 6684 case Intrinsic::umax: { 6685 SDValue Op1 = getValue(I.getArgOperand(0)); 6686 SDValue Op2 = getValue(I.getArgOperand(1)); 6687 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6688 return; 6689 } 6690 case Intrinsic::umin: { 6691 SDValue Op1 = getValue(I.getArgOperand(0)); 6692 SDValue Op2 = getValue(I.getArgOperand(1)); 6693 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6694 return; 6695 } 6696 case Intrinsic::abs: { 6697 // TODO: Preserve "int min is poison" arg in SDAG? 6698 SDValue Op1 = getValue(I.getArgOperand(0)); 6699 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6700 return; 6701 } 6702 case Intrinsic::stacksave: { 6703 SDValue Op = getRoot(); 6704 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6705 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6706 setValue(&I, Res); 6707 DAG.setRoot(Res.getValue(1)); 6708 return; 6709 } 6710 case Intrinsic::stackrestore: 6711 Res = getValue(I.getArgOperand(0)); 6712 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6713 return; 6714 case Intrinsic::get_dynamic_area_offset: { 6715 SDValue Op = getRoot(); 6716 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6717 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6718 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6719 // target. 6720 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6721 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6722 " intrinsic!"); 6723 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6724 Op); 6725 DAG.setRoot(Op); 6726 setValue(&I, Res); 6727 return; 6728 } 6729 case Intrinsic::stackguard: { 6730 MachineFunction &MF = DAG.getMachineFunction(); 6731 const Module &M = *MF.getFunction().getParent(); 6732 SDValue Chain = getRoot(); 6733 if (TLI.useLoadStackGuardNode()) { 6734 Res = getLoadStackGuard(DAG, sdl, Chain); 6735 } else { 6736 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6737 const Value *Global = TLI.getSDagStackGuard(M); 6738 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6739 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6740 MachinePointerInfo(Global, 0), Align, 6741 MachineMemOperand::MOVolatile); 6742 } 6743 if (TLI.useStackGuardXorFP()) 6744 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6745 DAG.setRoot(Chain); 6746 setValue(&I, Res); 6747 return; 6748 } 6749 case Intrinsic::stackprotector: { 6750 // Emit code into the DAG to store the stack guard onto the stack. 6751 MachineFunction &MF = DAG.getMachineFunction(); 6752 MachineFrameInfo &MFI = MF.getFrameInfo(); 6753 SDValue Src, Chain = getRoot(); 6754 6755 if (TLI.useLoadStackGuardNode()) 6756 Src = getLoadStackGuard(DAG, sdl, Chain); 6757 else 6758 Src = getValue(I.getArgOperand(0)); // The guard's value. 6759 6760 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6761 6762 int FI = FuncInfo.StaticAllocaMap[Slot]; 6763 MFI.setStackProtectorIndex(FI); 6764 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6765 6766 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6767 6768 // Store the stack protector onto the stack. 6769 Res = DAG.getStore( 6770 Chain, sdl, Src, FIN, 6771 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6772 MaybeAlign(), MachineMemOperand::MOVolatile); 6773 setValue(&I, Res); 6774 DAG.setRoot(Res); 6775 return; 6776 } 6777 case Intrinsic::objectsize: 6778 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6779 6780 case Intrinsic::is_constant: 6781 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6782 6783 case Intrinsic::annotation: 6784 case Intrinsic::ptr_annotation: 6785 case Intrinsic::launder_invariant_group: 6786 case Intrinsic::strip_invariant_group: 6787 // Drop the intrinsic, but forward the value 6788 setValue(&I, getValue(I.getOperand(0))); 6789 return; 6790 6791 case Intrinsic::assume: 6792 case Intrinsic::experimental_noalias_scope_decl: 6793 case Intrinsic::var_annotation: 6794 case Intrinsic::sideeffect: 6795 // Discard annotate attributes, noalias scope declarations, assumptions, and 6796 // artificial side-effects. 6797 return; 6798 6799 case Intrinsic::codeview_annotation: { 6800 // Emit a label associated with this metadata. 6801 MachineFunction &MF = DAG.getMachineFunction(); 6802 MCSymbol *Label = 6803 MF.getMMI().getContext().createTempSymbol("annotation", true); 6804 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6805 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6806 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6807 DAG.setRoot(Res); 6808 return; 6809 } 6810 6811 case Intrinsic::init_trampoline: { 6812 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6813 6814 SDValue Ops[6]; 6815 Ops[0] = getRoot(); 6816 Ops[1] = getValue(I.getArgOperand(0)); 6817 Ops[2] = getValue(I.getArgOperand(1)); 6818 Ops[3] = getValue(I.getArgOperand(2)); 6819 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6820 Ops[5] = DAG.getSrcValue(F); 6821 6822 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6823 6824 DAG.setRoot(Res); 6825 return; 6826 } 6827 case Intrinsic::adjust_trampoline: 6828 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6829 TLI.getPointerTy(DAG.getDataLayout()), 6830 getValue(I.getArgOperand(0)))); 6831 return; 6832 case Intrinsic::gcroot: { 6833 assert(DAG.getMachineFunction().getFunction().hasGC() && 6834 "only valid in functions with gc specified, enforced by Verifier"); 6835 assert(GFI && "implied by previous"); 6836 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6837 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6838 6839 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6840 GFI->addStackRoot(FI->getIndex(), TypeMap); 6841 return; 6842 } 6843 case Intrinsic::gcread: 6844 case Intrinsic::gcwrite: 6845 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6846 case Intrinsic::get_rounding: 6847 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6848 setValue(&I, Res); 6849 DAG.setRoot(Res.getValue(1)); 6850 return; 6851 6852 case Intrinsic::expect: 6853 // Just replace __builtin_expect(exp, c) with EXP. 6854 setValue(&I, getValue(I.getArgOperand(0))); 6855 return; 6856 6857 case Intrinsic::ubsantrap: 6858 case Intrinsic::debugtrap: 6859 case Intrinsic::trap: { 6860 StringRef TrapFuncName = 6861 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6862 if (TrapFuncName.empty()) { 6863 switch (Intrinsic) { 6864 case Intrinsic::trap: 6865 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6866 break; 6867 case Intrinsic::debugtrap: 6868 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6869 break; 6870 case Intrinsic::ubsantrap: 6871 DAG.setRoot(DAG.getNode( 6872 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6873 DAG.getTargetConstant( 6874 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6875 MVT::i32))); 6876 break; 6877 default: llvm_unreachable("unknown trap intrinsic"); 6878 } 6879 return; 6880 } 6881 TargetLowering::ArgListTy Args; 6882 if (Intrinsic == Intrinsic::ubsantrap) { 6883 Args.push_back(TargetLoweringBase::ArgListEntry()); 6884 Args[0].Val = I.getArgOperand(0); 6885 Args[0].Node = getValue(Args[0].Val); 6886 Args[0].Ty = Args[0].Val->getType(); 6887 } 6888 6889 TargetLowering::CallLoweringInfo CLI(DAG); 6890 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6891 CallingConv::C, I.getType(), 6892 DAG.getExternalSymbol(TrapFuncName.data(), 6893 TLI.getPointerTy(DAG.getDataLayout())), 6894 std::move(Args)); 6895 6896 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6897 DAG.setRoot(Result.second); 6898 return; 6899 } 6900 6901 case Intrinsic::uadd_with_overflow: 6902 case Intrinsic::sadd_with_overflow: 6903 case Intrinsic::usub_with_overflow: 6904 case Intrinsic::ssub_with_overflow: 6905 case Intrinsic::umul_with_overflow: 6906 case Intrinsic::smul_with_overflow: { 6907 ISD::NodeType Op; 6908 switch (Intrinsic) { 6909 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6910 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6911 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6912 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6913 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6914 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6915 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6916 } 6917 SDValue Op1 = getValue(I.getArgOperand(0)); 6918 SDValue Op2 = getValue(I.getArgOperand(1)); 6919 6920 EVT ResultVT = Op1.getValueType(); 6921 EVT OverflowVT = MVT::i1; 6922 if (ResultVT.isVector()) 6923 OverflowVT = EVT::getVectorVT( 6924 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6925 6926 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6927 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6928 return; 6929 } 6930 case Intrinsic::prefetch: { 6931 SDValue Ops[5]; 6932 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6933 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6934 Ops[0] = DAG.getRoot(); 6935 Ops[1] = getValue(I.getArgOperand(0)); 6936 Ops[2] = getValue(I.getArgOperand(1)); 6937 Ops[3] = getValue(I.getArgOperand(2)); 6938 Ops[4] = getValue(I.getArgOperand(3)); 6939 SDValue Result = DAG.getMemIntrinsicNode( 6940 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6941 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6942 /* align */ std::nullopt, Flags); 6943 6944 // Chain the prefetch in parallell with any pending loads, to stay out of 6945 // the way of later optimizations. 6946 PendingLoads.push_back(Result); 6947 Result = getRoot(); 6948 DAG.setRoot(Result); 6949 return; 6950 } 6951 case Intrinsic::lifetime_start: 6952 case Intrinsic::lifetime_end: { 6953 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6954 // Stack coloring is not enabled in O0, discard region information. 6955 if (TM.getOptLevel() == CodeGenOpt::None) 6956 return; 6957 6958 const int64_t ObjectSize = 6959 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6960 Value *const ObjectPtr = I.getArgOperand(1); 6961 SmallVector<const Value *, 4> Allocas; 6962 getUnderlyingObjects(ObjectPtr, Allocas); 6963 6964 for (const Value *Alloca : Allocas) { 6965 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6966 6967 // Could not find an Alloca. 6968 if (!LifetimeObject) 6969 continue; 6970 6971 // First check that the Alloca is static, otherwise it won't have a 6972 // valid frame index. 6973 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6974 if (SI == FuncInfo.StaticAllocaMap.end()) 6975 return; 6976 6977 const int FrameIndex = SI->second; 6978 int64_t Offset; 6979 if (GetPointerBaseWithConstantOffset( 6980 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6981 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6982 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6983 Offset); 6984 DAG.setRoot(Res); 6985 } 6986 return; 6987 } 6988 case Intrinsic::pseudoprobe: { 6989 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6990 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6991 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6992 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6993 DAG.setRoot(Res); 6994 return; 6995 } 6996 case Intrinsic::invariant_start: 6997 // Discard region information. 6998 setValue(&I, 6999 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7000 return; 7001 case Intrinsic::invariant_end: 7002 // Discard region information. 7003 return; 7004 case Intrinsic::clear_cache: 7005 /// FunctionName may be null. 7006 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7007 lowerCallToExternalSymbol(I, FunctionName); 7008 return; 7009 case Intrinsic::donothing: 7010 case Intrinsic::seh_try_begin: 7011 case Intrinsic::seh_scope_begin: 7012 case Intrinsic::seh_try_end: 7013 case Intrinsic::seh_scope_end: 7014 // ignore 7015 return; 7016 case Intrinsic::experimental_stackmap: 7017 visitStackmap(I); 7018 return; 7019 case Intrinsic::experimental_patchpoint_void: 7020 case Intrinsic::experimental_patchpoint_i64: 7021 visitPatchpoint(I); 7022 return; 7023 case Intrinsic::experimental_gc_statepoint: 7024 LowerStatepoint(cast<GCStatepointInst>(I)); 7025 return; 7026 case Intrinsic::experimental_gc_result: 7027 visitGCResult(cast<GCResultInst>(I)); 7028 return; 7029 case Intrinsic::experimental_gc_relocate: 7030 visitGCRelocate(cast<GCRelocateInst>(I)); 7031 return; 7032 case Intrinsic::instrprof_cover: 7033 llvm_unreachable("instrprof failed to lower a cover"); 7034 case Intrinsic::instrprof_increment: 7035 llvm_unreachable("instrprof failed to lower an increment"); 7036 case Intrinsic::instrprof_value_profile: 7037 llvm_unreachable("instrprof failed to lower a value profiling call"); 7038 case Intrinsic::localescape: { 7039 MachineFunction &MF = DAG.getMachineFunction(); 7040 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7041 7042 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7043 // is the same on all targets. 7044 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7045 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7046 if (isa<ConstantPointerNull>(Arg)) 7047 continue; // Skip null pointers. They represent a hole in index space. 7048 AllocaInst *Slot = cast<AllocaInst>(Arg); 7049 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7050 "can only escape static allocas"); 7051 int FI = FuncInfo.StaticAllocaMap[Slot]; 7052 MCSymbol *FrameAllocSym = 7053 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7054 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7055 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7056 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7057 .addSym(FrameAllocSym) 7058 .addFrameIndex(FI); 7059 } 7060 7061 return; 7062 } 7063 7064 case Intrinsic::localrecover: { 7065 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7066 MachineFunction &MF = DAG.getMachineFunction(); 7067 7068 // Get the symbol that defines the frame offset. 7069 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7070 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7071 unsigned IdxVal = 7072 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7073 MCSymbol *FrameAllocSym = 7074 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7075 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7076 7077 Value *FP = I.getArgOperand(1); 7078 SDValue FPVal = getValue(FP); 7079 EVT PtrVT = FPVal.getValueType(); 7080 7081 // Create a MCSymbol for the label to avoid any target lowering 7082 // that would make this PC relative. 7083 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7084 SDValue OffsetVal = 7085 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7086 7087 // Add the offset to the FP. 7088 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7089 setValue(&I, Add); 7090 7091 return; 7092 } 7093 7094 case Intrinsic::eh_exceptionpointer: 7095 case Intrinsic::eh_exceptioncode: { 7096 // Get the exception pointer vreg, copy from it, and resize it to fit. 7097 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7098 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7099 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7100 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7101 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7102 if (Intrinsic == Intrinsic::eh_exceptioncode) 7103 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7104 setValue(&I, N); 7105 return; 7106 } 7107 case Intrinsic::xray_customevent: { 7108 // Here we want to make sure that the intrinsic behaves as if it has a 7109 // specific calling convention, and only for x86_64. 7110 // FIXME: Support other platforms later. 7111 const auto &Triple = DAG.getTarget().getTargetTriple(); 7112 if (Triple.getArch() != Triple::x86_64) 7113 return; 7114 7115 SmallVector<SDValue, 8> Ops; 7116 7117 // We want to say that we always want the arguments in registers. 7118 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7119 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7120 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7121 SDValue Chain = getRoot(); 7122 Ops.push_back(LogEntryVal); 7123 Ops.push_back(StrSizeVal); 7124 Ops.push_back(Chain); 7125 7126 // We need to enforce the calling convention for the callsite, so that 7127 // argument ordering is enforced correctly, and that register allocation can 7128 // see that some registers may be assumed clobbered and have to preserve 7129 // them across calls to the intrinsic. 7130 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7131 sdl, NodeTys, Ops); 7132 SDValue patchableNode = SDValue(MN, 0); 7133 DAG.setRoot(patchableNode); 7134 setValue(&I, patchableNode); 7135 return; 7136 } 7137 case Intrinsic::xray_typedevent: { 7138 // Here we want to make sure that the intrinsic behaves as if it has a 7139 // specific calling convention, and only for x86_64. 7140 // FIXME: Support other platforms later. 7141 const auto &Triple = DAG.getTarget().getTargetTriple(); 7142 if (Triple.getArch() != Triple::x86_64) 7143 return; 7144 7145 SmallVector<SDValue, 8> Ops; 7146 7147 // We want to say that we always want the arguments in registers. 7148 // It's unclear to me how manipulating the selection DAG here forces callers 7149 // to provide arguments in registers instead of on the stack. 7150 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7151 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7152 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7153 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7154 SDValue Chain = getRoot(); 7155 Ops.push_back(LogTypeId); 7156 Ops.push_back(LogEntryVal); 7157 Ops.push_back(StrSizeVal); 7158 Ops.push_back(Chain); 7159 7160 // We need to enforce the calling convention for the callsite, so that 7161 // argument ordering is enforced correctly, and that register allocation can 7162 // see that some registers may be assumed clobbered and have to preserve 7163 // them across calls to the intrinsic. 7164 MachineSDNode *MN = DAG.getMachineNode( 7165 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7166 SDValue patchableNode = SDValue(MN, 0); 7167 DAG.setRoot(patchableNode); 7168 setValue(&I, patchableNode); 7169 return; 7170 } 7171 case Intrinsic::experimental_deoptimize: 7172 LowerDeoptimizeCall(&I); 7173 return; 7174 case Intrinsic::experimental_stepvector: 7175 visitStepVector(I); 7176 return; 7177 case Intrinsic::vector_reduce_fadd: 7178 case Intrinsic::vector_reduce_fmul: 7179 case Intrinsic::vector_reduce_add: 7180 case Intrinsic::vector_reduce_mul: 7181 case Intrinsic::vector_reduce_and: 7182 case Intrinsic::vector_reduce_or: 7183 case Intrinsic::vector_reduce_xor: 7184 case Intrinsic::vector_reduce_smax: 7185 case Intrinsic::vector_reduce_smin: 7186 case Intrinsic::vector_reduce_umax: 7187 case Intrinsic::vector_reduce_umin: 7188 case Intrinsic::vector_reduce_fmax: 7189 case Intrinsic::vector_reduce_fmin: 7190 visitVectorReduce(I, Intrinsic); 7191 return; 7192 7193 case Intrinsic::icall_branch_funnel: { 7194 SmallVector<SDValue, 16> Ops; 7195 Ops.push_back(getValue(I.getArgOperand(0))); 7196 7197 int64_t Offset; 7198 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7199 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7200 if (!Base) 7201 report_fatal_error( 7202 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7203 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7204 7205 struct BranchFunnelTarget { 7206 int64_t Offset; 7207 SDValue Target; 7208 }; 7209 SmallVector<BranchFunnelTarget, 8> Targets; 7210 7211 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7212 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7213 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7214 if (ElemBase != Base) 7215 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7216 "to the same GlobalValue"); 7217 7218 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7219 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7220 if (!GA) 7221 report_fatal_error( 7222 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7223 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7224 GA->getGlobal(), sdl, Val.getValueType(), 7225 GA->getOffset())}); 7226 } 7227 llvm::sort(Targets, 7228 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7229 return T1.Offset < T2.Offset; 7230 }); 7231 7232 for (auto &T : Targets) { 7233 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7234 Ops.push_back(T.Target); 7235 } 7236 7237 Ops.push_back(DAG.getRoot()); // Chain 7238 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7239 MVT::Other, Ops), 7240 0); 7241 DAG.setRoot(N); 7242 setValue(&I, N); 7243 HasTailCall = true; 7244 return; 7245 } 7246 7247 case Intrinsic::wasm_landingpad_index: 7248 // Information this intrinsic contained has been transferred to 7249 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7250 // delete it now. 7251 return; 7252 7253 case Intrinsic::aarch64_settag: 7254 case Intrinsic::aarch64_settag_zero: { 7255 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7256 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7257 SDValue Val = TSI.EmitTargetCodeForSetTag( 7258 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7259 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7260 ZeroMemory); 7261 DAG.setRoot(Val); 7262 setValue(&I, Val); 7263 return; 7264 } 7265 case Intrinsic::ptrmask: { 7266 SDValue Ptr = getValue(I.getOperand(0)); 7267 SDValue Const = getValue(I.getOperand(1)); 7268 7269 EVT PtrVT = Ptr.getValueType(); 7270 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7271 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7272 return; 7273 } 7274 case Intrinsic::threadlocal_address: { 7275 setValue(&I, getValue(I.getOperand(0))); 7276 return; 7277 } 7278 case Intrinsic::get_active_lane_mask: { 7279 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7280 SDValue Index = getValue(I.getOperand(0)); 7281 EVT ElementVT = Index.getValueType(); 7282 7283 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7284 visitTargetIntrinsic(I, Intrinsic); 7285 return; 7286 } 7287 7288 SDValue TripCount = getValue(I.getOperand(1)); 7289 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7290 7291 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7292 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7293 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7294 SDValue VectorInduction = DAG.getNode( 7295 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7296 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7297 VectorTripCount, ISD::CondCode::SETULT); 7298 setValue(&I, SetCC); 7299 return; 7300 } 7301 case Intrinsic::vector_insert: { 7302 SDValue Vec = getValue(I.getOperand(0)); 7303 SDValue SubVec = getValue(I.getOperand(1)); 7304 SDValue Index = getValue(I.getOperand(2)); 7305 7306 // The intrinsic's index type is i64, but the SDNode requires an index type 7307 // suitable for the target. Convert the index as required. 7308 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7309 if (Index.getValueType() != VectorIdxTy) 7310 Index = DAG.getVectorIdxConstant( 7311 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7312 7313 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7314 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7315 Index)); 7316 return; 7317 } 7318 case Intrinsic::vector_extract: { 7319 SDValue Vec = getValue(I.getOperand(0)); 7320 SDValue Index = getValue(I.getOperand(1)); 7321 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7322 7323 // The intrinsic's index type is i64, but the SDNode requires an index type 7324 // suitable for the target. Convert the index as required. 7325 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7326 if (Index.getValueType() != VectorIdxTy) 7327 Index = DAG.getVectorIdxConstant( 7328 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7329 7330 setValue(&I, 7331 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7332 return; 7333 } 7334 case Intrinsic::experimental_vector_reverse: 7335 visitVectorReverse(I); 7336 return; 7337 case Intrinsic::experimental_vector_splice: 7338 visitVectorSplice(I); 7339 return; 7340 case Intrinsic::callbr_landingpad: 7341 visitCallBrLandingPad(I); 7342 return; 7343 case Intrinsic::experimental_vector_interleave2: 7344 visitVectorInterleave(I); 7345 return; 7346 case Intrinsic::experimental_vector_deinterleave2: 7347 visitVectorDeinterleave(I); 7348 return; 7349 } 7350 } 7351 7352 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7353 const ConstrainedFPIntrinsic &FPI) { 7354 SDLoc sdl = getCurSDLoc(); 7355 7356 // We do not need to serialize constrained FP intrinsics against 7357 // each other or against (nonvolatile) loads, so they can be 7358 // chained like loads. 7359 SDValue Chain = DAG.getRoot(); 7360 SmallVector<SDValue, 4> Opers; 7361 Opers.push_back(Chain); 7362 if (FPI.isUnaryOp()) { 7363 Opers.push_back(getValue(FPI.getArgOperand(0))); 7364 } else if (FPI.isTernaryOp()) { 7365 Opers.push_back(getValue(FPI.getArgOperand(0))); 7366 Opers.push_back(getValue(FPI.getArgOperand(1))); 7367 Opers.push_back(getValue(FPI.getArgOperand(2))); 7368 } else { 7369 Opers.push_back(getValue(FPI.getArgOperand(0))); 7370 Opers.push_back(getValue(FPI.getArgOperand(1))); 7371 } 7372 7373 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7374 assert(Result.getNode()->getNumValues() == 2); 7375 7376 // Push node to the appropriate list so that future instructions can be 7377 // chained up correctly. 7378 SDValue OutChain = Result.getValue(1); 7379 switch (EB) { 7380 case fp::ExceptionBehavior::ebIgnore: 7381 // The only reason why ebIgnore nodes still need to be chained is that 7382 // they might depend on the current rounding mode, and therefore must 7383 // not be moved across instruction that may change that mode. 7384 [[fallthrough]]; 7385 case fp::ExceptionBehavior::ebMayTrap: 7386 // These must not be moved across calls or instructions that may change 7387 // floating-point exception masks. 7388 PendingConstrainedFP.push_back(OutChain); 7389 break; 7390 case fp::ExceptionBehavior::ebStrict: 7391 // These must not be moved across calls or instructions that may change 7392 // floating-point exception masks or read floating-point exception flags. 7393 // In addition, they cannot be optimized out even if unused. 7394 PendingConstrainedFPStrict.push_back(OutChain); 7395 break; 7396 } 7397 }; 7398 7399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7400 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7401 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7402 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7403 7404 SDNodeFlags Flags; 7405 if (EB == fp::ExceptionBehavior::ebIgnore) 7406 Flags.setNoFPExcept(true); 7407 7408 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7409 Flags.copyFMF(*FPOp); 7410 7411 unsigned Opcode; 7412 switch (FPI.getIntrinsicID()) { 7413 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7414 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7415 case Intrinsic::INTRINSIC: \ 7416 Opcode = ISD::STRICT_##DAGN; \ 7417 break; 7418 #include "llvm/IR/ConstrainedOps.def" 7419 case Intrinsic::experimental_constrained_fmuladd: { 7420 Opcode = ISD::STRICT_FMA; 7421 // Break fmuladd into fmul and fadd. 7422 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7423 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7424 Opers.pop_back(); 7425 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7426 pushOutChain(Mul, EB); 7427 Opcode = ISD::STRICT_FADD; 7428 Opers.clear(); 7429 Opers.push_back(Mul.getValue(1)); 7430 Opers.push_back(Mul.getValue(0)); 7431 Opers.push_back(getValue(FPI.getArgOperand(2))); 7432 } 7433 break; 7434 } 7435 } 7436 7437 // A few strict DAG nodes carry additional operands that are not 7438 // set up by the default code above. 7439 switch (Opcode) { 7440 default: break; 7441 case ISD::STRICT_FP_ROUND: 7442 Opers.push_back( 7443 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7444 break; 7445 case ISD::STRICT_FSETCC: 7446 case ISD::STRICT_FSETCCS: { 7447 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7448 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7449 if (TM.Options.NoNaNsFPMath) 7450 Condition = getFCmpCodeWithoutNaN(Condition); 7451 Opers.push_back(DAG.getCondCode(Condition)); 7452 break; 7453 } 7454 } 7455 7456 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7457 pushOutChain(Result, EB); 7458 7459 SDValue FPResult = Result.getValue(0); 7460 setValue(&FPI, FPResult); 7461 } 7462 7463 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7464 std::optional<unsigned> ResOPC; 7465 switch (VPIntrin.getIntrinsicID()) { 7466 case Intrinsic::vp_ctlz: { 7467 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7468 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7469 break; 7470 } 7471 case Intrinsic::vp_cttz: { 7472 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7473 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7474 break; 7475 } 7476 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7477 case Intrinsic::VPID: \ 7478 ResOPC = ISD::VPSD; \ 7479 break; 7480 #include "llvm/IR/VPIntrinsics.def" 7481 } 7482 7483 if (!ResOPC) 7484 llvm_unreachable( 7485 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7486 7487 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7488 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7489 if (VPIntrin.getFastMathFlags().allowReassoc()) 7490 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7491 : ISD::VP_REDUCE_FMUL; 7492 } 7493 7494 return *ResOPC; 7495 } 7496 7497 void SelectionDAGBuilder::visitVPLoad( 7498 const VPIntrinsic &VPIntrin, EVT VT, 7499 const SmallVectorImpl<SDValue> &OpValues) { 7500 SDLoc DL = getCurSDLoc(); 7501 Value *PtrOperand = VPIntrin.getArgOperand(0); 7502 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7503 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7504 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7505 SDValue LD; 7506 // Do not serialize variable-length loads of constant memory with 7507 // anything. 7508 if (!Alignment) 7509 Alignment = DAG.getEVTAlign(VT); 7510 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7511 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7512 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7513 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7514 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7515 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7516 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7517 MMO, false /*IsExpanding */); 7518 if (AddToChain) 7519 PendingLoads.push_back(LD.getValue(1)); 7520 setValue(&VPIntrin, LD); 7521 } 7522 7523 void SelectionDAGBuilder::visitVPGather( 7524 const VPIntrinsic &VPIntrin, EVT VT, 7525 const SmallVectorImpl<SDValue> &OpValues) { 7526 SDLoc DL = getCurSDLoc(); 7527 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7528 Value *PtrOperand = VPIntrin.getArgOperand(0); 7529 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7530 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7531 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7532 SDValue LD; 7533 if (!Alignment) 7534 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7535 unsigned AS = 7536 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7537 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7538 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7539 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7540 SDValue Base, Index, Scale; 7541 ISD::MemIndexType IndexType; 7542 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7543 this, VPIntrin.getParent(), 7544 VT.getScalarStoreSize()); 7545 if (!UniformBase) { 7546 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7547 Index = getValue(PtrOperand); 7548 IndexType = ISD::SIGNED_SCALED; 7549 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7550 } 7551 EVT IdxVT = Index.getValueType(); 7552 EVT EltTy = IdxVT.getVectorElementType(); 7553 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7554 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7555 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7556 } 7557 LD = DAG.getGatherVP( 7558 DAG.getVTList(VT, MVT::Other), VT, DL, 7559 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7560 IndexType); 7561 PendingLoads.push_back(LD.getValue(1)); 7562 setValue(&VPIntrin, LD); 7563 } 7564 7565 void SelectionDAGBuilder::visitVPStore( 7566 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7567 SDLoc DL = getCurSDLoc(); 7568 Value *PtrOperand = VPIntrin.getArgOperand(1); 7569 EVT VT = OpValues[0].getValueType(); 7570 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7571 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7572 SDValue ST; 7573 if (!Alignment) 7574 Alignment = DAG.getEVTAlign(VT); 7575 SDValue Ptr = OpValues[1]; 7576 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7577 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7578 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7579 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7580 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7581 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7582 /* IsTruncating */ false, /*IsCompressing*/ false); 7583 DAG.setRoot(ST); 7584 setValue(&VPIntrin, ST); 7585 } 7586 7587 void SelectionDAGBuilder::visitVPScatter( 7588 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7589 SDLoc DL = getCurSDLoc(); 7590 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7591 Value *PtrOperand = VPIntrin.getArgOperand(1); 7592 EVT VT = OpValues[0].getValueType(); 7593 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7594 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7595 SDValue ST; 7596 if (!Alignment) 7597 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7598 unsigned AS = 7599 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7600 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7601 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7602 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7603 SDValue Base, Index, Scale; 7604 ISD::MemIndexType IndexType; 7605 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7606 this, VPIntrin.getParent(), 7607 VT.getScalarStoreSize()); 7608 if (!UniformBase) { 7609 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7610 Index = getValue(PtrOperand); 7611 IndexType = ISD::SIGNED_SCALED; 7612 Scale = 7613 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7614 } 7615 EVT IdxVT = Index.getValueType(); 7616 EVT EltTy = IdxVT.getVectorElementType(); 7617 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7618 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7619 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7620 } 7621 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7622 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7623 OpValues[2], OpValues[3]}, 7624 MMO, IndexType); 7625 DAG.setRoot(ST); 7626 setValue(&VPIntrin, ST); 7627 } 7628 7629 void SelectionDAGBuilder::visitVPStridedLoad( 7630 const VPIntrinsic &VPIntrin, EVT VT, 7631 const SmallVectorImpl<SDValue> &OpValues) { 7632 SDLoc DL = getCurSDLoc(); 7633 Value *PtrOperand = VPIntrin.getArgOperand(0); 7634 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7635 if (!Alignment) 7636 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7637 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7638 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7639 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7640 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7641 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7642 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7643 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7644 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7645 7646 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7647 OpValues[2], OpValues[3], MMO, 7648 false /*IsExpanding*/); 7649 7650 if (AddToChain) 7651 PendingLoads.push_back(LD.getValue(1)); 7652 setValue(&VPIntrin, LD); 7653 } 7654 7655 void SelectionDAGBuilder::visitVPStridedStore( 7656 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7657 SDLoc DL = getCurSDLoc(); 7658 Value *PtrOperand = VPIntrin.getArgOperand(1); 7659 EVT VT = OpValues[0].getValueType(); 7660 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7661 if (!Alignment) 7662 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7663 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7664 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7665 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7666 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7667 7668 SDValue ST = DAG.getStridedStoreVP( 7669 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7670 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7671 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7672 /*IsCompressing*/ false); 7673 7674 DAG.setRoot(ST); 7675 setValue(&VPIntrin, ST); 7676 } 7677 7678 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7680 SDLoc DL = getCurSDLoc(); 7681 7682 ISD::CondCode Condition; 7683 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7684 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7685 if (IsFP) { 7686 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7687 // flags, but calls that don't return floating-point types can't be 7688 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7689 Condition = getFCmpCondCode(CondCode); 7690 if (TM.Options.NoNaNsFPMath) 7691 Condition = getFCmpCodeWithoutNaN(Condition); 7692 } else { 7693 Condition = getICmpCondCode(CondCode); 7694 } 7695 7696 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7697 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7698 // #2 is the condition code 7699 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7700 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7701 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7702 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7703 "Unexpected target EVL type"); 7704 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7705 7706 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7707 VPIntrin.getType()); 7708 setValue(&VPIntrin, 7709 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7710 } 7711 7712 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7713 const VPIntrinsic &VPIntrin) { 7714 SDLoc DL = getCurSDLoc(); 7715 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7716 7717 auto IID = VPIntrin.getIntrinsicID(); 7718 7719 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7720 return visitVPCmp(*CmpI); 7721 7722 SmallVector<EVT, 4> ValueVTs; 7723 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7724 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7725 SDVTList VTs = DAG.getVTList(ValueVTs); 7726 7727 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7728 7729 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7730 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7731 "Unexpected target EVL type"); 7732 7733 // Request operands. 7734 SmallVector<SDValue, 7> OpValues; 7735 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7736 auto Op = getValue(VPIntrin.getArgOperand(I)); 7737 if (I == EVLParamPos) 7738 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7739 OpValues.push_back(Op); 7740 } 7741 7742 switch (Opcode) { 7743 default: { 7744 SDNodeFlags SDFlags; 7745 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7746 SDFlags.copyFMF(*FPMO); 7747 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7748 setValue(&VPIntrin, Result); 7749 break; 7750 } 7751 case ISD::VP_LOAD: 7752 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7753 break; 7754 case ISD::VP_GATHER: 7755 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7756 break; 7757 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7758 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7759 break; 7760 case ISD::VP_STORE: 7761 visitVPStore(VPIntrin, OpValues); 7762 break; 7763 case ISD::VP_SCATTER: 7764 visitVPScatter(VPIntrin, OpValues); 7765 break; 7766 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7767 visitVPStridedStore(VPIntrin, OpValues); 7768 break; 7769 case ISD::VP_FMULADD: { 7770 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7771 SDNodeFlags SDFlags; 7772 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7773 SDFlags.copyFMF(*FPMO); 7774 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7775 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7776 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7777 } else { 7778 SDValue Mul = DAG.getNode( 7779 ISD::VP_FMUL, DL, VTs, 7780 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7781 SDValue Add = 7782 DAG.getNode(ISD::VP_FADD, DL, VTs, 7783 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7784 setValue(&VPIntrin, Add); 7785 } 7786 break; 7787 } 7788 case ISD::VP_INTTOPTR: { 7789 SDValue N = OpValues[0]; 7790 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7791 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7792 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7793 OpValues[2]); 7794 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7795 OpValues[2]); 7796 setValue(&VPIntrin, N); 7797 break; 7798 } 7799 case ISD::VP_PTRTOINT: { 7800 SDValue N = OpValues[0]; 7801 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7802 VPIntrin.getType()); 7803 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7804 VPIntrin.getOperand(0)->getType()); 7805 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7806 OpValues[2]); 7807 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7808 OpValues[2]); 7809 setValue(&VPIntrin, N); 7810 break; 7811 } 7812 case ISD::VP_ABS: 7813 case ISD::VP_CTLZ: 7814 case ISD::VP_CTLZ_ZERO_UNDEF: 7815 case ISD::VP_CTTZ: 7816 case ISD::VP_CTTZ_ZERO_UNDEF: { 7817 SDValue Result = 7818 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7819 setValue(&VPIntrin, Result); 7820 break; 7821 } 7822 } 7823 } 7824 7825 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7826 const BasicBlock *EHPadBB, 7827 MCSymbol *&BeginLabel) { 7828 MachineFunction &MF = DAG.getMachineFunction(); 7829 MachineModuleInfo &MMI = MF.getMMI(); 7830 7831 // Insert a label before the invoke call to mark the try range. This can be 7832 // used to detect deletion of the invoke via the MachineModuleInfo. 7833 BeginLabel = MMI.getContext().createTempSymbol(); 7834 7835 // For SjLj, keep track of which landing pads go with which invokes 7836 // so as to maintain the ordering of pads in the LSDA. 7837 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7838 if (CallSiteIndex) { 7839 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7840 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7841 7842 // Now that the call site is handled, stop tracking it. 7843 MMI.setCurrentCallSite(0); 7844 } 7845 7846 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7847 } 7848 7849 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7850 const BasicBlock *EHPadBB, 7851 MCSymbol *BeginLabel) { 7852 assert(BeginLabel && "BeginLabel should've been set"); 7853 7854 MachineFunction &MF = DAG.getMachineFunction(); 7855 MachineModuleInfo &MMI = MF.getMMI(); 7856 7857 // Insert a label at the end of the invoke call to mark the try range. This 7858 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7859 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7860 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7861 7862 // Inform MachineModuleInfo of range. 7863 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7864 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7865 // actually use outlined funclets and their LSDA info style. 7866 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7867 assert(II && "II should've been set"); 7868 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7869 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7870 } else if (!isScopedEHPersonality(Pers)) { 7871 assert(EHPadBB); 7872 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7873 } 7874 7875 return Chain; 7876 } 7877 7878 std::pair<SDValue, SDValue> 7879 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7880 const BasicBlock *EHPadBB) { 7881 MCSymbol *BeginLabel = nullptr; 7882 7883 if (EHPadBB) { 7884 // Both PendingLoads and PendingExports must be flushed here; 7885 // this call might not return. 7886 (void)getRoot(); 7887 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7888 CLI.setChain(getRoot()); 7889 } 7890 7891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7892 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7893 7894 assert((CLI.IsTailCall || Result.second.getNode()) && 7895 "Non-null chain expected with non-tail call!"); 7896 assert((Result.second.getNode() || !Result.first.getNode()) && 7897 "Null value expected with tail call!"); 7898 7899 if (!Result.second.getNode()) { 7900 // As a special case, a null chain means that a tail call has been emitted 7901 // and the DAG root is already updated. 7902 HasTailCall = true; 7903 7904 // Since there's no actual continuation from this block, nothing can be 7905 // relying on us setting vregs for them. 7906 PendingExports.clear(); 7907 } else { 7908 DAG.setRoot(Result.second); 7909 } 7910 7911 if (EHPadBB) { 7912 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7913 BeginLabel)); 7914 } 7915 7916 return Result; 7917 } 7918 7919 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7920 bool isTailCall, 7921 bool isMustTailCall, 7922 const BasicBlock *EHPadBB) { 7923 auto &DL = DAG.getDataLayout(); 7924 FunctionType *FTy = CB.getFunctionType(); 7925 Type *RetTy = CB.getType(); 7926 7927 TargetLowering::ArgListTy Args; 7928 Args.reserve(CB.arg_size()); 7929 7930 const Value *SwiftErrorVal = nullptr; 7931 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7932 7933 if (isTailCall) { 7934 // Avoid emitting tail calls in functions with the disable-tail-calls 7935 // attribute. 7936 auto *Caller = CB.getParent()->getParent(); 7937 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7938 "true" && !isMustTailCall) 7939 isTailCall = false; 7940 7941 // We can't tail call inside a function with a swifterror argument. Lowering 7942 // does not support this yet. It would have to move into the swifterror 7943 // register before the call. 7944 if (TLI.supportSwiftError() && 7945 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7946 isTailCall = false; 7947 } 7948 7949 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7950 TargetLowering::ArgListEntry Entry; 7951 const Value *V = *I; 7952 7953 // Skip empty types 7954 if (V->getType()->isEmptyTy()) 7955 continue; 7956 7957 SDValue ArgNode = getValue(V); 7958 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7959 7960 Entry.setAttributes(&CB, I - CB.arg_begin()); 7961 7962 // Use swifterror virtual register as input to the call. 7963 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7964 SwiftErrorVal = V; 7965 // We find the virtual register for the actual swifterror argument. 7966 // Instead of using the Value, we use the virtual register instead. 7967 Entry.Node = 7968 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7969 EVT(TLI.getPointerTy(DL))); 7970 } 7971 7972 Args.push_back(Entry); 7973 7974 // If we have an explicit sret argument that is an Instruction, (i.e., it 7975 // might point to function-local memory), we can't meaningfully tail-call. 7976 if (Entry.IsSRet && isa<Instruction>(V)) 7977 isTailCall = false; 7978 } 7979 7980 // If call site has a cfguardtarget operand bundle, create and add an 7981 // additional ArgListEntry. 7982 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7983 TargetLowering::ArgListEntry Entry; 7984 Value *V = Bundle->Inputs[0]; 7985 SDValue ArgNode = getValue(V); 7986 Entry.Node = ArgNode; 7987 Entry.Ty = V->getType(); 7988 Entry.IsCFGuardTarget = true; 7989 Args.push_back(Entry); 7990 } 7991 7992 // Check if target-independent constraints permit a tail call here. 7993 // Target-dependent constraints are checked within TLI->LowerCallTo. 7994 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7995 isTailCall = false; 7996 7997 // Disable tail calls if there is an swifterror argument. Targets have not 7998 // been updated to support tail calls. 7999 if (TLI.supportSwiftError() && SwiftErrorVal) 8000 isTailCall = false; 8001 8002 ConstantInt *CFIType = nullptr; 8003 if (CB.isIndirectCall()) { 8004 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8005 if (!TLI.supportKCFIBundles()) 8006 report_fatal_error( 8007 "Target doesn't support calls with kcfi operand bundles."); 8008 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8009 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8010 } 8011 } 8012 8013 TargetLowering::CallLoweringInfo CLI(DAG); 8014 CLI.setDebugLoc(getCurSDLoc()) 8015 .setChain(getRoot()) 8016 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8017 .setTailCall(isTailCall) 8018 .setConvergent(CB.isConvergent()) 8019 .setIsPreallocated( 8020 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8021 .setCFIType(CFIType); 8022 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8023 8024 if (Result.first.getNode()) { 8025 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8026 setValue(&CB, Result.first); 8027 } 8028 8029 // The last element of CLI.InVals has the SDValue for swifterror return. 8030 // Here we copy it to a virtual register and update SwiftErrorMap for 8031 // book-keeping. 8032 if (SwiftErrorVal && TLI.supportSwiftError()) { 8033 // Get the last element of InVals. 8034 SDValue Src = CLI.InVals.back(); 8035 Register VReg = 8036 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8037 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8038 DAG.setRoot(CopyNode); 8039 } 8040 } 8041 8042 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8043 SelectionDAGBuilder &Builder) { 8044 // Check to see if this load can be trivially constant folded, e.g. if the 8045 // input is from a string literal. 8046 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8047 // Cast pointer to the type we really want to load. 8048 Type *LoadTy = 8049 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8050 if (LoadVT.isVector()) 8051 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8052 8053 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8054 PointerType::getUnqual(LoadTy)); 8055 8056 if (const Constant *LoadCst = 8057 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8058 LoadTy, Builder.DAG.getDataLayout())) 8059 return Builder.getValue(LoadCst); 8060 } 8061 8062 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8063 // still constant memory, the input chain can be the entry node. 8064 SDValue Root; 8065 bool ConstantMemory = false; 8066 8067 // Do not serialize (non-volatile) loads of constant memory with anything. 8068 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8069 Root = Builder.DAG.getEntryNode(); 8070 ConstantMemory = true; 8071 } else { 8072 // Do not serialize non-volatile loads against each other. 8073 Root = Builder.DAG.getRoot(); 8074 } 8075 8076 SDValue Ptr = Builder.getValue(PtrVal); 8077 SDValue LoadVal = 8078 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8079 MachinePointerInfo(PtrVal), Align(1)); 8080 8081 if (!ConstantMemory) 8082 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8083 return LoadVal; 8084 } 8085 8086 /// Record the value for an instruction that produces an integer result, 8087 /// converting the type where necessary. 8088 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8089 SDValue Value, 8090 bool IsSigned) { 8091 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8092 I.getType(), true); 8093 if (IsSigned) 8094 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8095 else 8096 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8097 setValue(&I, Value); 8098 } 8099 8100 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8101 /// true and lower it. Otherwise return false, and it will be lowered like a 8102 /// normal call. 8103 /// The caller already checked that \p I calls the appropriate LibFunc with a 8104 /// correct prototype. 8105 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8106 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8107 const Value *Size = I.getArgOperand(2); 8108 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8109 if (CSize && CSize->getZExtValue() == 0) { 8110 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8111 I.getType(), true); 8112 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8113 return true; 8114 } 8115 8116 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8117 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8118 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8119 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8120 if (Res.first.getNode()) { 8121 processIntegerCallValue(I, Res.first, true); 8122 PendingLoads.push_back(Res.second); 8123 return true; 8124 } 8125 8126 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8127 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8128 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8129 return false; 8130 8131 // If the target has a fast compare for the given size, it will return a 8132 // preferred load type for that size. Require that the load VT is legal and 8133 // that the target supports unaligned loads of that type. Otherwise, return 8134 // INVALID. 8135 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8137 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8138 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8139 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8140 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8141 // TODO: Check alignment of src and dest ptrs. 8142 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8143 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8144 if (!TLI.isTypeLegal(LVT) || 8145 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8146 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8147 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8148 } 8149 8150 return LVT; 8151 }; 8152 8153 // This turns into unaligned loads. We only do this if the target natively 8154 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8155 // we'll only produce a small number of byte loads. 8156 MVT LoadVT; 8157 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8158 switch (NumBitsToCompare) { 8159 default: 8160 return false; 8161 case 16: 8162 LoadVT = MVT::i16; 8163 break; 8164 case 32: 8165 LoadVT = MVT::i32; 8166 break; 8167 case 64: 8168 case 128: 8169 case 256: 8170 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8171 break; 8172 } 8173 8174 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8175 return false; 8176 8177 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8178 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8179 8180 // Bitcast to a wide integer type if the loads are vectors. 8181 if (LoadVT.isVector()) { 8182 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8183 LoadL = DAG.getBitcast(CmpVT, LoadL); 8184 LoadR = DAG.getBitcast(CmpVT, LoadR); 8185 } 8186 8187 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8188 processIntegerCallValue(I, Cmp, false); 8189 return true; 8190 } 8191 8192 /// See if we can lower a memchr call into an optimized form. If so, return 8193 /// true and lower it. Otherwise return false, and it will be lowered like a 8194 /// normal call. 8195 /// The caller already checked that \p I calls the appropriate LibFunc with a 8196 /// correct prototype. 8197 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8198 const Value *Src = I.getArgOperand(0); 8199 const Value *Char = I.getArgOperand(1); 8200 const Value *Length = I.getArgOperand(2); 8201 8202 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8203 std::pair<SDValue, SDValue> Res = 8204 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8205 getValue(Src), getValue(Char), getValue(Length), 8206 MachinePointerInfo(Src)); 8207 if (Res.first.getNode()) { 8208 setValue(&I, Res.first); 8209 PendingLoads.push_back(Res.second); 8210 return true; 8211 } 8212 8213 return false; 8214 } 8215 8216 /// See if we can lower a mempcpy call into an optimized form. If so, return 8217 /// true and lower it. Otherwise return false, and it will be lowered like a 8218 /// normal call. 8219 /// The caller already checked that \p I calls the appropriate LibFunc with a 8220 /// correct prototype. 8221 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8222 SDValue Dst = getValue(I.getArgOperand(0)); 8223 SDValue Src = getValue(I.getArgOperand(1)); 8224 SDValue Size = getValue(I.getArgOperand(2)); 8225 8226 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8227 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8228 // DAG::getMemcpy needs Alignment to be defined. 8229 Align Alignment = std::min(DstAlign, SrcAlign); 8230 8231 bool isVol = false; 8232 SDLoc sdl = getCurSDLoc(); 8233 8234 // In the mempcpy context we need to pass in a false value for isTailCall 8235 // because the return pointer needs to be adjusted by the size of 8236 // the copied memory. 8237 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8238 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8239 /*isTailCall=*/false, 8240 MachinePointerInfo(I.getArgOperand(0)), 8241 MachinePointerInfo(I.getArgOperand(1)), 8242 I.getAAMetadata()); 8243 assert(MC.getNode() != nullptr && 8244 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8245 DAG.setRoot(MC); 8246 8247 // Check if Size needs to be truncated or extended. 8248 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8249 8250 // Adjust return pointer to point just past the last dst byte. 8251 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8252 Dst, Size); 8253 setValue(&I, DstPlusSize); 8254 return true; 8255 } 8256 8257 /// See if we can lower a strcpy call into an optimized form. If so, return 8258 /// true and lower it, otherwise return false and it will be lowered like a 8259 /// normal call. 8260 /// The caller already checked that \p I calls the appropriate LibFunc with a 8261 /// correct prototype. 8262 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8263 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8264 8265 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8266 std::pair<SDValue, SDValue> Res = 8267 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8268 getValue(Arg0), getValue(Arg1), 8269 MachinePointerInfo(Arg0), 8270 MachinePointerInfo(Arg1), isStpcpy); 8271 if (Res.first.getNode()) { 8272 setValue(&I, Res.first); 8273 DAG.setRoot(Res.second); 8274 return true; 8275 } 8276 8277 return false; 8278 } 8279 8280 /// See if we can lower a strcmp call into an optimized form. If so, return 8281 /// true and lower it, otherwise return false and it will be lowered like a 8282 /// normal call. 8283 /// The caller already checked that \p I calls the appropriate LibFunc with a 8284 /// correct prototype. 8285 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8286 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8287 8288 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8289 std::pair<SDValue, SDValue> Res = 8290 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8291 getValue(Arg0), getValue(Arg1), 8292 MachinePointerInfo(Arg0), 8293 MachinePointerInfo(Arg1)); 8294 if (Res.first.getNode()) { 8295 processIntegerCallValue(I, Res.first, true); 8296 PendingLoads.push_back(Res.second); 8297 return true; 8298 } 8299 8300 return false; 8301 } 8302 8303 /// See if we can lower a strlen call into an optimized form. If so, return 8304 /// true and lower it, otherwise return false and it will be lowered like a 8305 /// normal call. 8306 /// The caller already checked that \p I calls the appropriate LibFunc with a 8307 /// correct prototype. 8308 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8309 const Value *Arg0 = I.getArgOperand(0); 8310 8311 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8312 std::pair<SDValue, SDValue> Res = 8313 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8314 getValue(Arg0), MachinePointerInfo(Arg0)); 8315 if (Res.first.getNode()) { 8316 processIntegerCallValue(I, Res.first, false); 8317 PendingLoads.push_back(Res.second); 8318 return true; 8319 } 8320 8321 return false; 8322 } 8323 8324 /// See if we can lower a strnlen call into an optimized form. If so, return 8325 /// true and lower it, otherwise return false and it will be lowered like a 8326 /// normal call. 8327 /// The caller already checked that \p I calls the appropriate LibFunc with a 8328 /// correct prototype. 8329 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8330 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8331 8332 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8333 std::pair<SDValue, SDValue> Res = 8334 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8335 getValue(Arg0), getValue(Arg1), 8336 MachinePointerInfo(Arg0)); 8337 if (Res.first.getNode()) { 8338 processIntegerCallValue(I, Res.first, false); 8339 PendingLoads.push_back(Res.second); 8340 return true; 8341 } 8342 8343 return false; 8344 } 8345 8346 /// See if we can lower a unary floating-point operation into an SDNode with 8347 /// the specified Opcode. If so, return true and lower it, otherwise return 8348 /// false and it will be lowered like a normal call. 8349 /// The caller already checked that \p I calls the appropriate LibFunc with a 8350 /// correct prototype. 8351 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8352 unsigned Opcode) { 8353 // We already checked this call's prototype; verify it doesn't modify errno. 8354 if (!I.onlyReadsMemory()) 8355 return false; 8356 8357 SDNodeFlags Flags; 8358 Flags.copyFMF(cast<FPMathOperator>(I)); 8359 8360 SDValue Tmp = getValue(I.getArgOperand(0)); 8361 setValue(&I, 8362 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8363 return true; 8364 } 8365 8366 /// See if we can lower a binary floating-point operation into an SDNode with 8367 /// the specified Opcode. If so, return true and lower it. Otherwise return 8368 /// false, and it will be lowered like a normal call. 8369 /// The caller already checked that \p I calls the appropriate LibFunc with a 8370 /// correct prototype. 8371 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8372 unsigned Opcode) { 8373 // We already checked this call's prototype; verify it doesn't modify errno. 8374 if (!I.onlyReadsMemory()) 8375 return false; 8376 8377 SDNodeFlags Flags; 8378 Flags.copyFMF(cast<FPMathOperator>(I)); 8379 8380 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8381 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8382 EVT VT = Tmp0.getValueType(); 8383 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8384 return true; 8385 } 8386 8387 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8388 // Handle inline assembly differently. 8389 if (I.isInlineAsm()) { 8390 visitInlineAsm(I); 8391 return; 8392 } 8393 8394 diagnoseDontCall(I); 8395 8396 if (Function *F = I.getCalledFunction()) { 8397 if (F->isDeclaration()) { 8398 // Is this an LLVM intrinsic or a target-specific intrinsic? 8399 unsigned IID = F->getIntrinsicID(); 8400 if (!IID) 8401 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8402 IID = II->getIntrinsicID(F); 8403 8404 if (IID) { 8405 visitIntrinsicCall(I, IID); 8406 return; 8407 } 8408 } 8409 8410 // Check for well-known libc/libm calls. If the function is internal, it 8411 // can't be a library call. Don't do the check if marked as nobuiltin for 8412 // some reason or the call site requires strict floating point semantics. 8413 LibFunc Func; 8414 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8415 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8416 LibInfo->hasOptimizedCodeGen(Func)) { 8417 switch (Func) { 8418 default: break; 8419 case LibFunc_bcmp: 8420 if (visitMemCmpBCmpCall(I)) 8421 return; 8422 break; 8423 case LibFunc_copysign: 8424 case LibFunc_copysignf: 8425 case LibFunc_copysignl: 8426 // We already checked this call's prototype; verify it doesn't modify 8427 // errno. 8428 if (I.onlyReadsMemory()) { 8429 SDValue LHS = getValue(I.getArgOperand(0)); 8430 SDValue RHS = getValue(I.getArgOperand(1)); 8431 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8432 LHS.getValueType(), LHS, RHS)); 8433 return; 8434 } 8435 break; 8436 case LibFunc_fabs: 8437 case LibFunc_fabsf: 8438 case LibFunc_fabsl: 8439 if (visitUnaryFloatCall(I, ISD::FABS)) 8440 return; 8441 break; 8442 case LibFunc_fmin: 8443 case LibFunc_fminf: 8444 case LibFunc_fminl: 8445 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8446 return; 8447 break; 8448 case LibFunc_fmax: 8449 case LibFunc_fmaxf: 8450 case LibFunc_fmaxl: 8451 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8452 return; 8453 break; 8454 case LibFunc_sin: 8455 case LibFunc_sinf: 8456 case LibFunc_sinl: 8457 if (visitUnaryFloatCall(I, ISD::FSIN)) 8458 return; 8459 break; 8460 case LibFunc_cos: 8461 case LibFunc_cosf: 8462 case LibFunc_cosl: 8463 if (visitUnaryFloatCall(I, ISD::FCOS)) 8464 return; 8465 break; 8466 case LibFunc_sqrt: 8467 case LibFunc_sqrtf: 8468 case LibFunc_sqrtl: 8469 case LibFunc_sqrt_finite: 8470 case LibFunc_sqrtf_finite: 8471 case LibFunc_sqrtl_finite: 8472 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8473 return; 8474 break; 8475 case LibFunc_floor: 8476 case LibFunc_floorf: 8477 case LibFunc_floorl: 8478 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8479 return; 8480 break; 8481 case LibFunc_nearbyint: 8482 case LibFunc_nearbyintf: 8483 case LibFunc_nearbyintl: 8484 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8485 return; 8486 break; 8487 case LibFunc_ceil: 8488 case LibFunc_ceilf: 8489 case LibFunc_ceill: 8490 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8491 return; 8492 break; 8493 case LibFunc_rint: 8494 case LibFunc_rintf: 8495 case LibFunc_rintl: 8496 if (visitUnaryFloatCall(I, ISD::FRINT)) 8497 return; 8498 break; 8499 case LibFunc_round: 8500 case LibFunc_roundf: 8501 case LibFunc_roundl: 8502 if (visitUnaryFloatCall(I, ISD::FROUND)) 8503 return; 8504 break; 8505 case LibFunc_trunc: 8506 case LibFunc_truncf: 8507 case LibFunc_truncl: 8508 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8509 return; 8510 break; 8511 case LibFunc_log2: 8512 case LibFunc_log2f: 8513 case LibFunc_log2l: 8514 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8515 return; 8516 break; 8517 case LibFunc_exp2: 8518 case LibFunc_exp2f: 8519 case LibFunc_exp2l: 8520 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8521 return; 8522 break; 8523 case LibFunc_memcmp: 8524 if (visitMemCmpBCmpCall(I)) 8525 return; 8526 break; 8527 case LibFunc_mempcpy: 8528 if (visitMemPCpyCall(I)) 8529 return; 8530 break; 8531 case LibFunc_memchr: 8532 if (visitMemChrCall(I)) 8533 return; 8534 break; 8535 case LibFunc_strcpy: 8536 if (visitStrCpyCall(I, false)) 8537 return; 8538 break; 8539 case LibFunc_stpcpy: 8540 if (visitStrCpyCall(I, true)) 8541 return; 8542 break; 8543 case LibFunc_strcmp: 8544 if (visitStrCmpCall(I)) 8545 return; 8546 break; 8547 case LibFunc_strlen: 8548 if (visitStrLenCall(I)) 8549 return; 8550 break; 8551 case LibFunc_strnlen: 8552 if (visitStrNLenCall(I)) 8553 return; 8554 break; 8555 } 8556 } 8557 } 8558 8559 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8560 // have to do anything here to lower funclet bundles. 8561 // CFGuardTarget bundles are lowered in LowerCallTo. 8562 assert(!I.hasOperandBundlesOtherThan( 8563 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8564 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8565 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8566 "Cannot lower calls with arbitrary operand bundles!"); 8567 8568 SDValue Callee = getValue(I.getCalledOperand()); 8569 8570 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8571 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8572 else 8573 // Check if we can potentially perform a tail call. More detailed checking 8574 // is be done within LowerCallTo, after more information about the call is 8575 // known. 8576 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8577 } 8578 8579 namespace { 8580 8581 /// AsmOperandInfo - This contains information for each constraint that we are 8582 /// lowering. 8583 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8584 public: 8585 /// CallOperand - If this is the result output operand or a clobber 8586 /// this is null, otherwise it is the incoming operand to the CallInst. 8587 /// This gets modified as the asm is processed. 8588 SDValue CallOperand; 8589 8590 /// AssignedRegs - If this is a register or register class operand, this 8591 /// contains the set of register corresponding to the operand. 8592 RegsForValue AssignedRegs; 8593 8594 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8595 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8596 } 8597 8598 /// Whether or not this operand accesses memory 8599 bool hasMemory(const TargetLowering &TLI) const { 8600 // Indirect operand accesses access memory. 8601 if (isIndirect) 8602 return true; 8603 8604 for (const auto &Code : Codes) 8605 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8606 return true; 8607 8608 return false; 8609 } 8610 }; 8611 8612 8613 } // end anonymous namespace 8614 8615 /// Make sure that the output operand \p OpInfo and its corresponding input 8616 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8617 /// out). 8618 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8619 SDISelAsmOperandInfo &MatchingOpInfo, 8620 SelectionDAG &DAG) { 8621 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8622 return; 8623 8624 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8625 const auto &TLI = DAG.getTargetLoweringInfo(); 8626 8627 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8628 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8629 OpInfo.ConstraintVT); 8630 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8631 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8632 MatchingOpInfo.ConstraintVT); 8633 if ((OpInfo.ConstraintVT.isInteger() != 8634 MatchingOpInfo.ConstraintVT.isInteger()) || 8635 (MatchRC.second != InputRC.second)) { 8636 // FIXME: error out in a more elegant fashion 8637 report_fatal_error("Unsupported asm: input constraint" 8638 " with a matching output constraint of" 8639 " incompatible type!"); 8640 } 8641 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8642 } 8643 8644 /// Get a direct memory input to behave well as an indirect operand. 8645 /// This may introduce stores, hence the need for a \p Chain. 8646 /// \return The (possibly updated) chain. 8647 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8648 SDISelAsmOperandInfo &OpInfo, 8649 SelectionDAG &DAG) { 8650 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8651 8652 // If we don't have an indirect input, put it in the constpool if we can, 8653 // otherwise spill it to a stack slot. 8654 // TODO: This isn't quite right. We need to handle these according to 8655 // the addressing mode that the constraint wants. Also, this may take 8656 // an additional register for the computation and we don't want that 8657 // either. 8658 8659 // If the operand is a float, integer, or vector constant, spill to a 8660 // constant pool entry to get its address. 8661 const Value *OpVal = OpInfo.CallOperandVal; 8662 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8663 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8664 OpInfo.CallOperand = DAG.getConstantPool( 8665 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8666 return Chain; 8667 } 8668 8669 // Otherwise, create a stack slot and emit a store to it before the asm. 8670 Type *Ty = OpVal->getType(); 8671 auto &DL = DAG.getDataLayout(); 8672 uint64_t TySize = DL.getTypeAllocSize(Ty); 8673 MachineFunction &MF = DAG.getMachineFunction(); 8674 int SSFI = MF.getFrameInfo().CreateStackObject( 8675 TySize, DL.getPrefTypeAlign(Ty), false); 8676 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8677 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8678 MachinePointerInfo::getFixedStack(MF, SSFI), 8679 TLI.getMemValueType(DL, Ty)); 8680 OpInfo.CallOperand = StackSlot; 8681 8682 return Chain; 8683 } 8684 8685 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8686 /// specified operand. We prefer to assign virtual registers, to allow the 8687 /// register allocator to handle the assignment process. However, if the asm 8688 /// uses features that we can't model on machineinstrs, we have SDISel do the 8689 /// allocation. This produces generally horrible, but correct, code. 8690 /// 8691 /// OpInfo describes the operand 8692 /// RefOpInfo describes the matching operand if any, the operand otherwise 8693 static std::optional<unsigned> 8694 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8695 SDISelAsmOperandInfo &OpInfo, 8696 SDISelAsmOperandInfo &RefOpInfo) { 8697 LLVMContext &Context = *DAG.getContext(); 8698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8699 8700 MachineFunction &MF = DAG.getMachineFunction(); 8701 SmallVector<unsigned, 4> Regs; 8702 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8703 8704 // No work to do for memory/address operands. 8705 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8706 OpInfo.ConstraintType == TargetLowering::C_Address) 8707 return std::nullopt; 8708 8709 // If this is a constraint for a single physreg, or a constraint for a 8710 // register class, find it. 8711 unsigned AssignedReg; 8712 const TargetRegisterClass *RC; 8713 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8714 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8715 // RC is unset only on failure. Return immediately. 8716 if (!RC) 8717 return std::nullopt; 8718 8719 // Get the actual register value type. This is important, because the user 8720 // may have asked for (e.g.) the AX register in i32 type. We need to 8721 // remember that AX is actually i16 to get the right extension. 8722 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8723 8724 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8725 // If this is an FP operand in an integer register (or visa versa), or more 8726 // generally if the operand value disagrees with the register class we plan 8727 // to stick it in, fix the operand type. 8728 // 8729 // If this is an input value, the bitcast to the new type is done now. 8730 // Bitcast for output value is done at the end of visitInlineAsm(). 8731 if ((OpInfo.Type == InlineAsm::isOutput || 8732 OpInfo.Type == InlineAsm::isInput) && 8733 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8734 // Try to convert to the first EVT that the reg class contains. If the 8735 // types are identical size, use a bitcast to convert (e.g. two differing 8736 // vector types). Note: output bitcast is done at the end of 8737 // visitInlineAsm(). 8738 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8739 // Exclude indirect inputs while they are unsupported because the code 8740 // to perform the load is missing and thus OpInfo.CallOperand still 8741 // refers to the input address rather than the pointed-to value. 8742 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8743 OpInfo.CallOperand = 8744 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8745 OpInfo.ConstraintVT = RegVT; 8746 // If the operand is an FP value and we want it in integer registers, 8747 // use the corresponding integer type. This turns an f64 value into 8748 // i64, which can be passed with two i32 values on a 32-bit machine. 8749 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8750 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8751 if (OpInfo.Type == InlineAsm::isInput) 8752 OpInfo.CallOperand = 8753 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8754 OpInfo.ConstraintVT = VT; 8755 } 8756 } 8757 } 8758 8759 // No need to allocate a matching input constraint since the constraint it's 8760 // matching to has already been allocated. 8761 if (OpInfo.isMatchingInputConstraint()) 8762 return std::nullopt; 8763 8764 EVT ValueVT = OpInfo.ConstraintVT; 8765 if (OpInfo.ConstraintVT == MVT::Other) 8766 ValueVT = RegVT; 8767 8768 // Initialize NumRegs. 8769 unsigned NumRegs = 1; 8770 if (OpInfo.ConstraintVT != MVT::Other) 8771 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8772 8773 // If this is a constraint for a specific physical register, like {r17}, 8774 // assign it now. 8775 8776 // If this associated to a specific register, initialize iterator to correct 8777 // place. If virtual, make sure we have enough registers 8778 8779 // Initialize iterator if necessary 8780 TargetRegisterClass::iterator I = RC->begin(); 8781 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8782 8783 // Do not check for single registers. 8784 if (AssignedReg) { 8785 I = std::find(I, RC->end(), AssignedReg); 8786 if (I == RC->end()) { 8787 // RC does not contain the selected register, which indicates a 8788 // mismatch between the register and the required type/bitwidth. 8789 return {AssignedReg}; 8790 } 8791 } 8792 8793 for (; NumRegs; --NumRegs, ++I) { 8794 assert(I != RC->end() && "Ran out of registers to allocate!"); 8795 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8796 Regs.push_back(R); 8797 } 8798 8799 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8800 return std::nullopt; 8801 } 8802 8803 static unsigned 8804 findMatchingInlineAsmOperand(unsigned OperandNo, 8805 const std::vector<SDValue> &AsmNodeOperands) { 8806 // Scan until we find the definition we already emitted of this operand. 8807 unsigned CurOp = InlineAsm::Op_FirstOperand; 8808 for (; OperandNo; --OperandNo) { 8809 // Advance to the next operand. 8810 unsigned OpFlag = 8811 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8812 assert((InlineAsm::isRegDefKind(OpFlag) || 8813 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8814 InlineAsm::isMemKind(OpFlag)) && 8815 "Skipped past definitions?"); 8816 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8817 } 8818 return CurOp; 8819 } 8820 8821 namespace { 8822 8823 class ExtraFlags { 8824 unsigned Flags = 0; 8825 8826 public: 8827 explicit ExtraFlags(const CallBase &Call) { 8828 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8829 if (IA->hasSideEffects()) 8830 Flags |= InlineAsm::Extra_HasSideEffects; 8831 if (IA->isAlignStack()) 8832 Flags |= InlineAsm::Extra_IsAlignStack; 8833 if (Call.isConvergent()) 8834 Flags |= InlineAsm::Extra_IsConvergent; 8835 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8836 } 8837 8838 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8839 // Ideally, we would only check against memory constraints. However, the 8840 // meaning of an Other constraint can be target-specific and we can't easily 8841 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8842 // for Other constraints as well. 8843 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8844 OpInfo.ConstraintType == TargetLowering::C_Other) { 8845 if (OpInfo.Type == InlineAsm::isInput) 8846 Flags |= InlineAsm::Extra_MayLoad; 8847 else if (OpInfo.Type == InlineAsm::isOutput) 8848 Flags |= InlineAsm::Extra_MayStore; 8849 else if (OpInfo.Type == InlineAsm::isClobber) 8850 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8851 } 8852 } 8853 8854 unsigned get() const { return Flags; } 8855 }; 8856 8857 } // end anonymous namespace 8858 8859 static bool isFunction(SDValue Op) { 8860 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8861 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8862 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8863 8864 // In normal "call dllimport func" instruction (non-inlineasm) it force 8865 // indirect access by specifing call opcode. And usually specially print 8866 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8867 // not do in this way now. (In fact, this is similar with "Data Access" 8868 // action). So here we ignore dllimport function. 8869 if (Fn && !Fn->hasDLLImportStorageClass()) 8870 return true; 8871 } 8872 } 8873 return false; 8874 } 8875 8876 /// visitInlineAsm - Handle a call to an InlineAsm object. 8877 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8878 const BasicBlock *EHPadBB) { 8879 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8880 8881 /// ConstraintOperands - Information about all of the constraints. 8882 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8883 8884 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8885 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8886 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8887 8888 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8889 // AsmDialect, MayLoad, MayStore). 8890 bool HasSideEffect = IA->hasSideEffects(); 8891 ExtraFlags ExtraInfo(Call); 8892 8893 for (auto &T : TargetConstraints) { 8894 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8895 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8896 8897 if (OpInfo.CallOperandVal) 8898 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8899 8900 if (!HasSideEffect) 8901 HasSideEffect = OpInfo.hasMemory(TLI); 8902 8903 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8904 // FIXME: Could we compute this on OpInfo rather than T? 8905 8906 // Compute the constraint code and ConstraintType to use. 8907 TLI.ComputeConstraintToUse(T, SDValue()); 8908 8909 if (T.ConstraintType == TargetLowering::C_Immediate && 8910 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8911 // We've delayed emitting a diagnostic like the "n" constraint because 8912 // inlining could cause an integer showing up. 8913 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8914 "' expects an integer constant " 8915 "expression"); 8916 8917 ExtraInfo.update(T); 8918 } 8919 8920 // We won't need to flush pending loads if this asm doesn't touch 8921 // memory and is nonvolatile. 8922 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8923 8924 bool EmitEHLabels = isa<InvokeInst>(Call); 8925 if (EmitEHLabels) { 8926 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8927 } 8928 bool IsCallBr = isa<CallBrInst>(Call); 8929 8930 if (IsCallBr || EmitEHLabels) { 8931 // If this is a callbr or invoke we need to flush pending exports since 8932 // inlineasm_br and invoke are terminators. 8933 // We need to do this before nodes are glued to the inlineasm_br node. 8934 Chain = getControlRoot(); 8935 } 8936 8937 MCSymbol *BeginLabel = nullptr; 8938 if (EmitEHLabels) { 8939 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8940 } 8941 8942 int OpNo = -1; 8943 SmallVector<StringRef> AsmStrs; 8944 IA->collectAsmStrs(AsmStrs); 8945 8946 // Second pass over the constraints: compute which constraint option to use. 8947 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8948 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8949 OpNo++; 8950 8951 // If this is an output operand with a matching input operand, look up the 8952 // matching input. If their types mismatch, e.g. one is an integer, the 8953 // other is floating point, or their sizes are different, flag it as an 8954 // error. 8955 if (OpInfo.hasMatchingInput()) { 8956 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8957 patchMatchingInput(OpInfo, Input, DAG); 8958 } 8959 8960 // Compute the constraint code and ConstraintType to use. 8961 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8962 8963 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8964 OpInfo.Type == InlineAsm::isClobber) || 8965 OpInfo.ConstraintType == TargetLowering::C_Address) 8966 continue; 8967 8968 // In Linux PIC model, there are 4 cases about value/label addressing: 8969 // 8970 // 1: Function call or Label jmp inside the module. 8971 // 2: Data access (such as global variable, static variable) inside module. 8972 // 3: Function call or Label jmp outside the module. 8973 // 4: Data access (such as global variable) outside the module. 8974 // 8975 // Due to current llvm inline asm architecture designed to not "recognize" 8976 // the asm code, there are quite troubles for us to treat mem addressing 8977 // differently for same value/adress used in different instuctions. 8978 // For example, in pic model, call a func may in plt way or direclty 8979 // pc-related, but lea/mov a function adress may use got. 8980 // 8981 // Here we try to "recognize" function call for the case 1 and case 3 in 8982 // inline asm. And try to adjust the constraint for them. 8983 // 8984 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8985 // label, so here we don't handle jmp function label now, but we need to 8986 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8987 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8988 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8989 TM.getCodeModel() != CodeModel::Large) { 8990 OpInfo.isIndirect = false; 8991 OpInfo.ConstraintType = TargetLowering::C_Address; 8992 } 8993 8994 // If this is a memory input, and if the operand is not indirect, do what we 8995 // need to provide an address for the memory input. 8996 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8997 !OpInfo.isIndirect) { 8998 assert((OpInfo.isMultipleAlternative || 8999 (OpInfo.Type == InlineAsm::isInput)) && 9000 "Can only indirectify direct input operands!"); 9001 9002 // Memory operands really want the address of the value. 9003 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9004 9005 // There is no longer a Value* corresponding to this operand. 9006 OpInfo.CallOperandVal = nullptr; 9007 9008 // It is now an indirect operand. 9009 OpInfo.isIndirect = true; 9010 } 9011 9012 } 9013 9014 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9015 std::vector<SDValue> AsmNodeOperands; 9016 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9017 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9018 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9019 9020 // If we have a !srcloc metadata node associated with it, we want to attach 9021 // this to the ultimately generated inline asm machineinstr. To do this, we 9022 // pass in the third operand as this (potentially null) inline asm MDNode. 9023 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9024 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9025 9026 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9027 // bits as operand 3. 9028 AsmNodeOperands.push_back(DAG.getTargetConstant( 9029 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9030 9031 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9032 // this, assign virtual and physical registers for inputs and otput. 9033 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9034 // Assign Registers. 9035 SDISelAsmOperandInfo &RefOpInfo = 9036 OpInfo.isMatchingInputConstraint() 9037 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9038 : OpInfo; 9039 const auto RegError = 9040 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9041 if (RegError) { 9042 const MachineFunction &MF = DAG.getMachineFunction(); 9043 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9044 const char *RegName = TRI.getName(*RegError); 9045 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9046 "' allocated for constraint '" + 9047 Twine(OpInfo.ConstraintCode) + 9048 "' does not match required type"); 9049 return; 9050 } 9051 9052 auto DetectWriteToReservedRegister = [&]() { 9053 const MachineFunction &MF = DAG.getMachineFunction(); 9054 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9055 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9056 if (Register::isPhysicalRegister(Reg) && 9057 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9058 const char *RegName = TRI.getName(Reg); 9059 emitInlineAsmError(Call, "write to reserved register '" + 9060 Twine(RegName) + "'"); 9061 return true; 9062 } 9063 } 9064 return false; 9065 }; 9066 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9067 (OpInfo.Type == InlineAsm::isInput && 9068 !OpInfo.isMatchingInputConstraint())) && 9069 "Only address as input operand is allowed."); 9070 9071 switch (OpInfo.Type) { 9072 case InlineAsm::isOutput: 9073 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9074 unsigned ConstraintID = 9075 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9076 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9077 "Failed to convert memory constraint code to constraint id."); 9078 9079 // Add information to the INLINEASM node to know about this output. 9080 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9081 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9082 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9083 MVT::i32)); 9084 AsmNodeOperands.push_back(OpInfo.CallOperand); 9085 } else { 9086 // Otherwise, this outputs to a register (directly for C_Register / 9087 // C_RegisterClass, and a target-defined fashion for 9088 // C_Immediate/C_Other). Find a register that we can use. 9089 if (OpInfo.AssignedRegs.Regs.empty()) { 9090 emitInlineAsmError( 9091 Call, "couldn't allocate output register for constraint '" + 9092 Twine(OpInfo.ConstraintCode) + "'"); 9093 return; 9094 } 9095 9096 if (DetectWriteToReservedRegister()) 9097 return; 9098 9099 // Add information to the INLINEASM node to know that this register is 9100 // set. 9101 OpInfo.AssignedRegs.AddInlineAsmOperands( 9102 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9103 : InlineAsm::Kind_RegDef, 9104 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9105 } 9106 break; 9107 9108 case InlineAsm::isInput: 9109 case InlineAsm::isLabel: { 9110 SDValue InOperandVal = OpInfo.CallOperand; 9111 9112 if (OpInfo.isMatchingInputConstraint()) { 9113 // If this is required to match an output register we have already set, 9114 // just use its register. 9115 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9116 AsmNodeOperands); 9117 unsigned OpFlag = 9118 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9119 if (InlineAsm::isRegDefKind(OpFlag) || 9120 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9121 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9122 if (OpInfo.isIndirect) { 9123 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9124 emitInlineAsmError(Call, "inline asm not supported yet: " 9125 "don't know how to handle tied " 9126 "indirect register inputs"); 9127 return; 9128 } 9129 9130 SmallVector<unsigned, 4> Regs; 9131 MachineFunction &MF = DAG.getMachineFunction(); 9132 MachineRegisterInfo &MRI = MF.getRegInfo(); 9133 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9134 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9135 Register TiedReg = R->getReg(); 9136 MVT RegVT = R->getSimpleValueType(0); 9137 const TargetRegisterClass *RC = 9138 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9139 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9140 : TRI.getMinimalPhysRegClass(TiedReg); 9141 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9142 for (unsigned i = 0; i != NumRegs; ++i) 9143 Regs.push_back(MRI.createVirtualRegister(RC)); 9144 9145 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9146 9147 SDLoc dl = getCurSDLoc(); 9148 // Use the produced MatchedRegs object to 9149 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9150 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9151 true, OpInfo.getMatchedOperand(), dl, 9152 DAG, AsmNodeOperands); 9153 break; 9154 } 9155 9156 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9157 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9158 "Unexpected number of operands"); 9159 // Add information to the INLINEASM node to know about this input. 9160 // See InlineAsm.h isUseOperandTiedToDef. 9161 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9162 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9163 OpInfo.getMatchedOperand()); 9164 AsmNodeOperands.push_back(DAG.getTargetConstant( 9165 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9166 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9167 break; 9168 } 9169 9170 // Treat indirect 'X' constraint as memory. 9171 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9172 OpInfo.isIndirect) 9173 OpInfo.ConstraintType = TargetLowering::C_Memory; 9174 9175 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9176 OpInfo.ConstraintType == TargetLowering::C_Other) { 9177 std::vector<SDValue> Ops; 9178 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9179 Ops, DAG); 9180 if (Ops.empty()) { 9181 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9182 if (isa<ConstantSDNode>(InOperandVal)) { 9183 emitInlineAsmError(Call, "value out of range for constraint '" + 9184 Twine(OpInfo.ConstraintCode) + "'"); 9185 return; 9186 } 9187 9188 emitInlineAsmError(Call, 9189 "invalid operand for inline asm constraint '" + 9190 Twine(OpInfo.ConstraintCode) + "'"); 9191 return; 9192 } 9193 9194 // Add information to the INLINEASM node to know about this input. 9195 unsigned ResOpType = 9196 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9197 AsmNodeOperands.push_back(DAG.getTargetConstant( 9198 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9199 llvm::append_range(AsmNodeOperands, Ops); 9200 break; 9201 } 9202 9203 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9204 assert((OpInfo.isIndirect || 9205 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9206 "Operand must be indirect to be a mem!"); 9207 assert(InOperandVal.getValueType() == 9208 TLI.getPointerTy(DAG.getDataLayout()) && 9209 "Memory operands expect pointer values"); 9210 9211 unsigned ConstraintID = 9212 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9213 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9214 "Failed to convert memory constraint code to constraint id."); 9215 9216 // Add information to the INLINEASM node to know about this input. 9217 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9218 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9219 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9220 getCurSDLoc(), 9221 MVT::i32)); 9222 AsmNodeOperands.push_back(InOperandVal); 9223 break; 9224 } 9225 9226 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9227 assert(InOperandVal.getValueType() == 9228 TLI.getPointerTy(DAG.getDataLayout()) && 9229 "Address operands expect pointer values"); 9230 9231 unsigned ConstraintID = 9232 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9233 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9234 "Failed to convert memory constraint code to constraint id."); 9235 9236 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9237 9238 SDValue AsmOp = InOperandVal; 9239 if (isFunction(InOperandVal)) { 9240 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9241 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9242 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9243 InOperandVal.getValueType(), 9244 GA->getOffset()); 9245 } 9246 9247 // Add information to the INLINEASM node to know about this input. 9248 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9249 9250 AsmNodeOperands.push_back( 9251 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9252 9253 AsmNodeOperands.push_back(AsmOp); 9254 break; 9255 } 9256 9257 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9258 OpInfo.ConstraintType == TargetLowering::C_Register) && 9259 "Unknown constraint type!"); 9260 9261 // TODO: Support this. 9262 if (OpInfo.isIndirect) { 9263 emitInlineAsmError( 9264 Call, "Don't know how to handle indirect register inputs yet " 9265 "for constraint '" + 9266 Twine(OpInfo.ConstraintCode) + "'"); 9267 return; 9268 } 9269 9270 // Copy the input into the appropriate registers. 9271 if (OpInfo.AssignedRegs.Regs.empty()) { 9272 emitInlineAsmError(Call, 9273 "couldn't allocate input reg for constraint '" + 9274 Twine(OpInfo.ConstraintCode) + "'"); 9275 return; 9276 } 9277 9278 if (DetectWriteToReservedRegister()) 9279 return; 9280 9281 SDLoc dl = getCurSDLoc(); 9282 9283 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9284 &Call); 9285 9286 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9287 dl, DAG, AsmNodeOperands); 9288 break; 9289 } 9290 case InlineAsm::isClobber: 9291 // Add the clobbered value to the operand list, so that the register 9292 // allocator is aware that the physreg got clobbered. 9293 if (!OpInfo.AssignedRegs.Regs.empty()) 9294 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9295 false, 0, getCurSDLoc(), DAG, 9296 AsmNodeOperands); 9297 break; 9298 } 9299 } 9300 9301 // Finish up input operands. Set the input chain and add the flag last. 9302 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9303 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9304 9305 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9306 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9307 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9308 Glue = Chain.getValue(1); 9309 9310 // Do additional work to generate outputs. 9311 9312 SmallVector<EVT, 1> ResultVTs; 9313 SmallVector<SDValue, 1> ResultValues; 9314 SmallVector<SDValue, 8> OutChains; 9315 9316 llvm::Type *CallResultType = Call.getType(); 9317 ArrayRef<Type *> ResultTypes; 9318 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9319 ResultTypes = StructResult->elements(); 9320 else if (!CallResultType->isVoidTy()) 9321 ResultTypes = ArrayRef(CallResultType); 9322 9323 auto CurResultType = ResultTypes.begin(); 9324 auto handleRegAssign = [&](SDValue V) { 9325 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9326 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9327 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9328 ++CurResultType; 9329 // If the type of the inline asm call site return value is different but has 9330 // same size as the type of the asm output bitcast it. One example of this 9331 // is for vectors with different width / number of elements. This can 9332 // happen for register classes that can contain multiple different value 9333 // types. The preg or vreg allocated may not have the same VT as was 9334 // expected. 9335 // 9336 // This can also happen for a return value that disagrees with the register 9337 // class it is put in, eg. a double in a general-purpose register on a 9338 // 32-bit machine. 9339 if (ResultVT != V.getValueType() && 9340 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9341 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9342 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9343 V.getValueType().isInteger()) { 9344 // If a result value was tied to an input value, the computed result 9345 // may have a wider width than the expected result. Extract the 9346 // relevant portion. 9347 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9348 } 9349 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9350 ResultVTs.push_back(ResultVT); 9351 ResultValues.push_back(V); 9352 }; 9353 9354 // Deal with output operands. 9355 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9356 if (OpInfo.Type == InlineAsm::isOutput) { 9357 SDValue Val; 9358 // Skip trivial output operands. 9359 if (OpInfo.AssignedRegs.Regs.empty()) 9360 continue; 9361 9362 switch (OpInfo.ConstraintType) { 9363 case TargetLowering::C_Register: 9364 case TargetLowering::C_RegisterClass: 9365 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9366 Chain, &Glue, &Call); 9367 break; 9368 case TargetLowering::C_Immediate: 9369 case TargetLowering::C_Other: 9370 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9371 OpInfo, DAG); 9372 break; 9373 case TargetLowering::C_Memory: 9374 break; // Already handled. 9375 case TargetLowering::C_Address: 9376 break; // Silence warning. 9377 case TargetLowering::C_Unknown: 9378 assert(false && "Unexpected unknown constraint"); 9379 } 9380 9381 // Indirect output manifest as stores. Record output chains. 9382 if (OpInfo.isIndirect) { 9383 const Value *Ptr = OpInfo.CallOperandVal; 9384 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9385 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9386 MachinePointerInfo(Ptr)); 9387 OutChains.push_back(Store); 9388 } else { 9389 // generate CopyFromRegs to associated registers. 9390 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9391 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9392 for (const SDValue &V : Val->op_values()) 9393 handleRegAssign(V); 9394 } else 9395 handleRegAssign(Val); 9396 } 9397 } 9398 } 9399 9400 // Set results. 9401 if (!ResultValues.empty()) { 9402 assert(CurResultType == ResultTypes.end() && 9403 "Mismatch in number of ResultTypes"); 9404 assert(ResultValues.size() == ResultTypes.size() && 9405 "Mismatch in number of output operands in asm result"); 9406 9407 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9408 DAG.getVTList(ResultVTs), ResultValues); 9409 setValue(&Call, V); 9410 } 9411 9412 // Collect store chains. 9413 if (!OutChains.empty()) 9414 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9415 9416 if (EmitEHLabels) { 9417 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9418 } 9419 9420 // Only Update Root if inline assembly has a memory effect. 9421 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9422 EmitEHLabels) 9423 DAG.setRoot(Chain); 9424 } 9425 9426 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9427 const Twine &Message) { 9428 LLVMContext &Ctx = *DAG.getContext(); 9429 Ctx.emitError(&Call, Message); 9430 9431 // Make sure we leave the DAG in a valid state 9432 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9433 SmallVector<EVT, 1> ValueVTs; 9434 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9435 9436 if (ValueVTs.empty()) 9437 return; 9438 9439 SmallVector<SDValue, 1> Ops; 9440 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9441 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9442 9443 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9444 } 9445 9446 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9447 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9448 MVT::Other, getRoot(), 9449 getValue(I.getArgOperand(0)), 9450 DAG.getSrcValue(I.getArgOperand(0)))); 9451 } 9452 9453 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9455 const DataLayout &DL = DAG.getDataLayout(); 9456 SDValue V = DAG.getVAArg( 9457 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9458 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9459 DL.getABITypeAlign(I.getType()).value()); 9460 DAG.setRoot(V.getValue(1)); 9461 9462 if (I.getType()->isPointerTy()) 9463 V = DAG.getPtrExtOrTrunc( 9464 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9465 setValue(&I, V); 9466 } 9467 9468 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9469 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9470 MVT::Other, getRoot(), 9471 getValue(I.getArgOperand(0)), 9472 DAG.getSrcValue(I.getArgOperand(0)))); 9473 } 9474 9475 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9476 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9477 MVT::Other, getRoot(), 9478 getValue(I.getArgOperand(0)), 9479 getValue(I.getArgOperand(1)), 9480 DAG.getSrcValue(I.getArgOperand(0)), 9481 DAG.getSrcValue(I.getArgOperand(1)))); 9482 } 9483 9484 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9485 const Instruction &I, 9486 SDValue Op) { 9487 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9488 if (!Range) 9489 return Op; 9490 9491 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9492 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9493 return Op; 9494 9495 APInt Lo = CR.getUnsignedMin(); 9496 if (!Lo.isMinValue()) 9497 return Op; 9498 9499 APInt Hi = CR.getUnsignedMax(); 9500 unsigned Bits = std::max(Hi.getActiveBits(), 9501 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9502 9503 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9504 9505 SDLoc SL = getCurSDLoc(); 9506 9507 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9508 DAG.getValueType(SmallVT)); 9509 unsigned NumVals = Op.getNode()->getNumValues(); 9510 if (NumVals == 1) 9511 return ZExt; 9512 9513 SmallVector<SDValue, 4> Ops; 9514 9515 Ops.push_back(ZExt); 9516 for (unsigned I = 1; I != NumVals; ++I) 9517 Ops.push_back(Op.getValue(I)); 9518 9519 return DAG.getMergeValues(Ops, SL); 9520 } 9521 9522 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9523 /// the call being lowered. 9524 /// 9525 /// This is a helper for lowering intrinsics that follow a target calling 9526 /// convention or require stack pointer adjustment. Only a subset of the 9527 /// intrinsic's operands need to participate in the calling convention. 9528 void SelectionDAGBuilder::populateCallLoweringInfo( 9529 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9530 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9531 bool IsPatchPoint) { 9532 TargetLowering::ArgListTy Args; 9533 Args.reserve(NumArgs); 9534 9535 // Populate the argument list. 9536 // Attributes for args start at offset 1, after the return attribute. 9537 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9538 ArgI != ArgE; ++ArgI) { 9539 const Value *V = Call->getOperand(ArgI); 9540 9541 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9542 9543 TargetLowering::ArgListEntry Entry; 9544 Entry.Node = getValue(V); 9545 Entry.Ty = V->getType(); 9546 Entry.setAttributes(Call, ArgI); 9547 Args.push_back(Entry); 9548 } 9549 9550 CLI.setDebugLoc(getCurSDLoc()) 9551 .setChain(getRoot()) 9552 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9553 .setDiscardResult(Call->use_empty()) 9554 .setIsPatchPoint(IsPatchPoint) 9555 .setIsPreallocated( 9556 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9557 } 9558 9559 /// Add a stack map intrinsic call's live variable operands to a stackmap 9560 /// or patchpoint target node's operand list. 9561 /// 9562 /// Constants are converted to TargetConstants purely as an optimization to 9563 /// avoid constant materialization and register allocation. 9564 /// 9565 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9566 /// generate addess computation nodes, and so FinalizeISel can convert the 9567 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9568 /// address materialization and register allocation, but may also be required 9569 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9570 /// alloca in the entry block, then the runtime may assume that the alloca's 9571 /// StackMap location can be read immediately after compilation and that the 9572 /// location is valid at any point during execution (this is similar to the 9573 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9574 /// only available in a register, then the runtime would need to trap when 9575 /// execution reaches the StackMap in order to read the alloca's location. 9576 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9577 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9578 SelectionDAGBuilder &Builder) { 9579 SelectionDAG &DAG = Builder.DAG; 9580 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9581 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9582 9583 // Things on the stack are pointer-typed, meaning that they are already 9584 // legal and can be emitted directly to target nodes. 9585 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9586 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9587 } else { 9588 // Otherwise emit a target independent node to be legalised. 9589 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9590 } 9591 } 9592 } 9593 9594 /// Lower llvm.experimental.stackmap. 9595 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9596 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9597 // [live variables...]) 9598 9599 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9600 9601 SDValue Chain, InGlue, Callee; 9602 SmallVector<SDValue, 32> Ops; 9603 9604 SDLoc DL = getCurSDLoc(); 9605 Callee = getValue(CI.getCalledOperand()); 9606 9607 // The stackmap intrinsic only records the live variables (the arguments 9608 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9609 // intrinsic, this won't be lowered to a function call. This means we don't 9610 // have to worry about calling conventions and target specific lowering code. 9611 // Instead we perform the call lowering right here. 9612 // 9613 // chain, flag = CALLSEQ_START(chain, 0, 0) 9614 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9615 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9616 // 9617 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9618 InGlue = Chain.getValue(1); 9619 9620 // Add the STACKMAP operands, starting with DAG house-keeping. 9621 Ops.push_back(Chain); 9622 Ops.push_back(InGlue); 9623 9624 // Add the <id>, <numShadowBytes> operands. 9625 // 9626 // These do not require legalisation, and can be emitted directly to target 9627 // constant nodes. 9628 SDValue ID = getValue(CI.getArgOperand(0)); 9629 assert(ID.getValueType() == MVT::i64); 9630 SDValue IDConst = DAG.getTargetConstant( 9631 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9632 Ops.push_back(IDConst); 9633 9634 SDValue Shad = getValue(CI.getArgOperand(1)); 9635 assert(Shad.getValueType() == MVT::i32); 9636 SDValue ShadConst = DAG.getTargetConstant( 9637 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9638 Ops.push_back(ShadConst); 9639 9640 // Add the live variables. 9641 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9642 9643 // Create the STACKMAP node. 9644 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9645 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9646 InGlue = Chain.getValue(1); 9647 9648 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9649 9650 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9651 9652 // Set the root to the target-lowered call chain. 9653 DAG.setRoot(Chain); 9654 9655 // Inform the Frame Information that we have a stackmap in this function. 9656 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9657 } 9658 9659 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9660 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9661 const BasicBlock *EHPadBB) { 9662 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9663 // i32 <numBytes>, 9664 // i8* <target>, 9665 // i32 <numArgs>, 9666 // [Args...], 9667 // [live variables...]) 9668 9669 CallingConv::ID CC = CB.getCallingConv(); 9670 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9671 bool HasDef = !CB.getType()->isVoidTy(); 9672 SDLoc dl = getCurSDLoc(); 9673 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9674 9675 // Handle immediate and symbolic callees. 9676 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9677 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9678 /*isTarget=*/true); 9679 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9680 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9681 SDLoc(SymbolicCallee), 9682 SymbolicCallee->getValueType(0)); 9683 9684 // Get the real number of arguments participating in the call <numArgs> 9685 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9686 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9687 9688 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9689 // Intrinsics include all meta-operands up to but not including CC. 9690 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9691 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9692 "Not enough arguments provided to the patchpoint intrinsic"); 9693 9694 // For AnyRegCC the arguments are lowered later on manually. 9695 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9696 Type *ReturnTy = 9697 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9698 9699 TargetLowering::CallLoweringInfo CLI(DAG); 9700 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9701 ReturnTy, true); 9702 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9703 9704 SDNode *CallEnd = Result.second.getNode(); 9705 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9706 CallEnd = CallEnd->getOperand(0).getNode(); 9707 9708 /// Get a call instruction from the call sequence chain. 9709 /// Tail calls are not allowed. 9710 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9711 "Expected a callseq node."); 9712 SDNode *Call = CallEnd->getOperand(0).getNode(); 9713 bool HasGlue = Call->getGluedNode(); 9714 9715 // Replace the target specific call node with the patchable intrinsic. 9716 SmallVector<SDValue, 8> Ops; 9717 9718 // Push the chain. 9719 Ops.push_back(*(Call->op_begin())); 9720 9721 // Optionally, push the glue (if any). 9722 if (HasGlue) 9723 Ops.push_back(*(Call->op_end() - 1)); 9724 9725 // Push the register mask info. 9726 if (HasGlue) 9727 Ops.push_back(*(Call->op_end() - 2)); 9728 else 9729 Ops.push_back(*(Call->op_end() - 1)); 9730 9731 // Add the <id> and <numBytes> constants. 9732 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9733 Ops.push_back(DAG.getTargetConstant( 9734 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9735 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9736 Ops.push_back(DAG.getTargetConstant( 9737 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9738 MVT::i32)); 9739 9740 // Add the callee. 9741 Ops.push_back(Callee); 9742 9743 // Adjust <numArgs> to account for any arguments that have been passed on the 9744 // stack instead. 9745 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9746 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9747 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9748 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9749 9750 // Add the calling convention 9751 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9752 9753 // Add the arguments we omitted previously. The register allocator should 9754 // place these in any free register. 9755 if (IsAnyRegCC) 9756 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9757 Ops.push_back(getValue(CB.getArgOperand(i))); 9758 9759 // Push the arguments from the call instruction. 9760 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9761 Ops.append(Call->op_begin() + 2, e); 9762 9763 // Push live variables for the stack map. 9764 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9765 9766 SDVTList NodeTys; 9767 if (IsAnyRegCC && HasDef) { 9768 // Create the return types based on the intrinsic definition 9769 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9770 SmallVector<EVT, 3> ValueVTs; 9771 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9772 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9773 9774 // There is always a chain and a glue type at the end 9775 ValueVTs.push_back(MVT::Other); 9776 ValueVTs.push_back(MVT::Glue); 9777 NodeTys = DAG.getVTList(ValueVTs); 9778 } else 9779 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9780 9781 // Replace the target specific call node with a PATCHPOINT node. 9782 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9783 9784 // Update the NodeMap. 9785 if (HasDef) { 9786 if (IsAnyRegCC) 9787 setValue(&CB, SDValue(PPV.getNode(), 0)); 9788 else 9789 setValue(&CB, Result.first); 9790 } 9791 9792 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9793 // call sequence. Furthermore the location of the chain and glue can change 9794 // when the AnyReg calling convention is used and the intrinsic returns a 9795 // value. 9796 if (IsAnyRegCC && HasDef) { 9797 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9798 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9799 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9800 } else 9801 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9802 DAG.DeleteNode(Call); 9803 9804 // Inform the Frame Information that we have a patchpoint in this function. 9805 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9806 } 9807 9808 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9809 unsigned Intrinsic) { 9810 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9811 SDValue Op1 = getValue(I.getArgOperand(0)); 9812 SDValue Op2; 9813 if (I.arg_size() > 1) 9814 Op2 = getValue(I.getArgOperand(1)); 9815 SDLoc dl = getCurSDLoc(); 9816 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9817 SDValue Res; 9818 SDNodeFlags SDFlags; 9819 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9820 SDFlags.copyFMF(*FPMO); 9821 9822 switch (Intrinsic) { 9823 case Intrinsic::vector_reduce_fadd: 9824 if (SDFlags.hasAllowReassociation()) 9825 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9826 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9827 SDFlags); 9828 else 9829 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9830 break; 9831 case Intrinsic::vector_reduce_fmul: 9832 if (SDFlags.hasAllowReassociation()) 9833 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9834 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9835 SDFlags); 9836 else 9837 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9838 break; 9839 case Intrinsic::vector_reduce_add: 9840 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9841 break; 9842 case Intrinsic::vector_reduce_mul: 9843 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9844 break; 9845 case Intrinsic::vector_reduce_and: 9846 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9847 break; 9848 case Intrinsic::vector_reduce_or: 9849 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9850 break; 9851 case Intrinsic::vector_reduce_xor: 9852 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9853 break; 9854 case Intrinsic::vector_reduce_smax: 9855 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9856 break; 9857 case Intrinsic::vector_reduce_smin: 9858 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9859 break; 9860 case Intrinsic::vector_reduce_umax: 9861 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9862 break; 9863 case Intrinsic::vector_reduce_umin: 9864 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9865 break; 9866 case Intrinsic::vector_reduce_fmax: 9867 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9868 break; 9869 case Intrinsic::vector_reduce_fmin: 9870 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9871 break; 9872 default: 9873 llvm_unreachable("Unhandled vector reduce intrinsic"); 9874 } 9875 setValue(&I, Res); 9876 } 9877 9878 /// Returns an AttributeList representing the attributes applied to the return 9879 /// value of the given call. 9880 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9881 SmallVector<Attribute::AttrKind, 2> Attrs; 9882 if (CLI.RetSExt) 9883 Attrs.push_back(Attribute::SExt); 9884 if (CLI.RetZExt) 9885 Attrs.push_back(Attribute::ZExt); 9886 if (CLI.IsInReg) 9887 Attrs.push_back(Attribute::InReg); 9888 9889 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9890 Attrs); 9891 } 9892 9893 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9894 /// implementation, which just calls LowerCall. 9895 /// FIXME: When all targets are 9896 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9897 std::pair<SDValue, SDValue> 9898 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9899 // Handle the incoming return values from the call. 9900 CLI.Ins.clear(); 9901 Type *OrigRetTy = CLI.RetTy; 9902 SmallVector<EVT, 4> RetTys; 9903 SmallVector<uint64_t, 4> Offsets; 9904 auto &DL = CLI.DAG.getDataLayout(); 9905 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9906 9907 if (CLI.IsPostTypeLegalization) { 9908 // If we are lowering a libcall after legalization, split the return type. 9909 SmallVector<EVT, 4> OldRetTys; 9910 SmallVector<uint64_t, 4> OldOffsets; 9911 RetTys.swap(OldRetTys); 9912 Offsets.swap(OldOffsets); 9913 9914 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9915 EVT RetVT = OldRetTys[i]; 9916 uint64_t Offset = OldOffsets[i]; 9917 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9918 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9919 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9920 RetTys.append(NumRegs, RegisterVT); 9921 for (unsigned j = 0; j != NumRegs; ++j) 9922 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9923 } 9924 } 9925 9926 SmallVector<ISD::OutputArg, 4> Outs; 9927 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9928 9929 bool CanLowerReturn = 9930 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9931 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9932 9933 SDValue DemoteStackSlot; 9934 int DemoteStackIdx = -100; 9935 if (!CanLowerReturn) { 9936 // FIXME: equivalent assert? 9937 // assert(!CS.hasInAllocaArgument() && 9938 // "sret demotion is incompatible with inalloca"); 9939 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9940 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9941 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9942 DemoteStackIdx = 9943 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9944 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9945 DL.getAllocaAddrSpace()); 9946 9947 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9948 ArgListEntry Entry; 9949 Entry.Node = DemoteStackSlot; 9950 Entry.Ty = StackSlotPtrType; 9951 Entry.IsSExt = false; 9952 Entry.IsZExt = false; 9953 Entry.IsInReg = false; 9954 Entry.IsSRet = true; 9955 Entry.IsNest = false; 9956 Entry.IsByVal = false; 9957 Entry.IsByRef = false; 9958 Entry.IsReturned = false; 9959 Entry.IsSwiftSelf = false; 9960 Entry.IsSwiftAsync = false; 9961 Entry.IsSwiftError = false; 9962 Entry.IsCFGuardTarget = false; 9963 Entry.Alignment = Alignment; 9964 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9965 CLI.NumFixedArgs += 1; 9966 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9967 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9968 9969 // sret demotion isn't compatible with tail-calls, since the sret argument 9970 // points into the callers stack frame. 9971 CLI.IsTailCall = false; 9972 } else { 9973 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9974 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9975 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9976 ISD::ArgFlagsTy Flags; 9977 if (NeedsRegBlock) { 9978 Flags.setInConsecutiveRegs(); 9979 if (I == RetTys.size() - 1) 9980 Flags.setInConsecutiveRegsLast(); 9981 } 9982 EVT VT = RetTys[I]; 9983 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9984 CLI.CallConv, VT); 9985 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9986 CLI.CallConv, VT); 9987 for (unsigned i = 0; i != NumRegs; ++i) { 9988 ISD::InputArg MyFlags; 9989 MyFlags.Flags = Flags; 9990 MyFlags.VT = RegisterVT; 9991 MyFlags.ArgVT = VT; 9992 MyFlags.Used = CLI.IsReturnValueUsed; 9993 if (CLI.RetTy->isPointerTy()) { 9994 MyFlags.Flags.setPointer(); 9995 MyFlags.Flags.setPointerAddrSpace( 9996 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9997 } 9998 if (CLI.RetSExt) 9999 MyFlags.Flags.setSExt(); 10000 if (CLI.RetZExt) 10001 MyFlags.Flags.setZExt(); 10002 if (CLI.IsInReg) 10003 MyFlags.Flags.setInReg(); 10004 CLI.Ins.push_back(MyFlags); 10005 } 10006 } 10007 } 10008 10009 // We push in swifterror return as the last element of CLI.Ins. 10010 ArgListTy &Args = CLI.getArgs(); 10011 if (supportSwiftError()) { 10012 for (const ArgListEntry &Arg : Args) { 10013 if (Arg.IsSwiftError) { 10014 ISD::InputArg MyFlags; 10015 MyFlags.VT = getPointerTy(DL); 10016 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10017 MyFlags.Flags.setSwiftError(); 10018 CLI.Ins.push_back(MyFlags); 10019 } 10020 } 10021 } 10022 10023 // Handle all of the outgoing arguments. 10024 CLI.Outs.clear(); 10025 CLI.OutVals.clear(); 10026 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10027 SmallVector<EVT, 4> ValueVTs; 10028 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10029 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10030 Type *FinalType = Args[i].Ty; 10031 if (Args[i].IsByVal) 10032 FinalType = Args[i].IndirectType; 10033 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10034 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10035 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10036 ++Value) { 10037 EVT VT = ValueVTs[Value]; 10038 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10039 SDValue Op = SDValue(Args[i].Node.getNode(), 10040 Args[i].Node.getResNo() + Value); 10041 ISD::ArgFlagsTy Flags; 10042 10043 // Certain targets (such as MIPS), may have a different ABI alignment 10044 // for a type depending on the context. Give the target a chance to 10045 // specify the alignment it wants. 10046 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10047 Flags.setOrigAlign(OriginalAlignment); 10048 10049 if (Args[i].Ty->isPointerTy()) { 10050 Flags.setPointer(); 10051 Flags.setPointerAddrSpace( 10052 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10053 } 10054 if (Args[i].IsZExt) 10055 Flags.setZExt(); 10056 if (Args[i].IsSExt) 10057 Flags.setSExt(); 10058 if (Args[i].IsInReg) { 10059 // If we are using vectorcall calling convention, a structure that is 10060 // passed InReg - is surely an HVA 10061 if (CLI.CallConv == CallingConv::X86_VectorCall && 10062 isa<StructType>(FinalType)) { 10063 // The first value of a structure is marked 10064 if (0 == Value) 10065 Flags.setHvaStart(); 10066 Flags.setHva(); 10067 } 10068 // Set InReg Flag 10069 Flags.setInReg(); 10070 } 10071 if (Args[i].IsSRet) 10072 Flags.setSRet(); 10073 if (Args[i].IsSwiftSelf) 10074 Flags.setSwiftSelf(); 10075 if (Args[i].IsSwiftAsync) 10076 Flags.setSwiftAsync(); 10077 if (Args[i].IsSwiftError) 10078 Flags.setSwiftError(); 10079 if (Args[i].IsCFGuardTarget) 10080 Flags.setCFGuardTarget(); 10081 if (Args[i].IsByVal) 10082 Flags.setByVal(); 10083 if (Args[i].IsByRef) 10084 Flags.setByRef(); 10085 if (Args[i].IsPreallocated) { 10086 Flags.setPreallocated(); 10087 // Set the byval flag for CCAssignFn callbacks that don't know about 10088 // preallocated. This way we can know how many bytes we should've 10089 // allocated and how many bytes a callee cleanup function will pop. If 10090 // we port preallocated to more targets, we'll have to add custom 10091 // preallocated handling in the various CC lowering callbacks. 10092 Flags.setByVal(); 10093 } 10094 if (Args[i].IsInAlloca) { 10095 Flags.setInAlloca(); 10096 // Set the byval flag for CCAssignFn callbacks that don't know about 10097 // inalloca. This way we can know how many bytes we should've allocated 10098 // and how many bytes a callee cleanup function will pop. If we port 10099 // inalloca to more targets, we'll have to add custom inalloca handling 10100 // in the various CC lowering callbacks. 10101 Flags.setByVal(); 10102 } 10103 Align MemAlign; 10104 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10105 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10106 Flags.setByValSize(FrameSize); 10107 10108 // info is not there but there are cases it cannot get right. 10109 if (auto MA = Args[i].Alignment) 10110 MemAlign = *MA; 10111 else 10112 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10113 } else if (auto MA = Args[i].Alignment) { 10114 MemAlign = *MA; 10115 } else { 10116 MemAlign = OriginalAlignment; 10117 } 10118 Flags.setMemAlign(MemAlign); 10119 if (Args[i].IsNest) 10120 Flags.setNest(); 10121 if (NeedsRegBlock) 10122 Flags.setInConsecutiveRegs(); 10123 10124 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10125 CLI.CallConv, VT); 10126 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10127 CLI.CallConv, VT); 10128 SmallVector<SDValue, 4> Parts(NumParts); 10129 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10130 10131 if (Args[i].IsSExt) 10132 ExtendKind = ISD::SIGN_EXTEND; 10133 else if (Args[i].IsZExt) 10134 ExtendKind = ISD::ZERO_EXTEND; 10135 10136 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10137 // for now. 10138 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10139 CanLowerReturn) { 10140 assert((CLI.RetTy == Args[i].Ty || 10141 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10142 CLI.RetTy->getPointerAddressSpace() == 10143 Args[i].Ty->getPointerAddressSpace())) && 10144 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10145 // Before passing 'returned' to the target lowering code, ensure that 10146 // either the register MVT and the actual EVT are the same size or that 10147 // the return value and argument are extended in the same way; in these 10148 // cases it's safe to pass the argument register value unchanged as the 10149 // return register value (although it's at the target's option whether 10150 // to do so) 10151 // TODO: allow code generation to take advantage of partially preserved 10152 // registers rather than clobbering the entire register when the 10153 // parameter extension method is not compatible with the return 10154 // extension method 10155 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10156 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10157 CLI.RetZExt == Args[i].IsZExt)) 10158 Flags.setReturned(); 10159 } 10160 10161 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10162 CLI.CallConv, ExtendKind); 10163 10164 for (unsigned j = 0; j != NumParts; ++j) { 10165 // if it isn't first piece, alignment must be 1 10166 // For scalable vectors the scalable part is currently handled 10167 // by individual targets, so we just use the known minimum size here. 10168 ISD::OutputArg MyFlags( 10169 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10170 i < CLI.NumFixedArgs, i, 10171 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10172 if (NumParts > 1 && j == 0) 10173 MyFlags.Flags.setSplit(); 10174 else if (j != 0) { 10175 MyFlags.Flags.setOrigAlign(Align(1)); 10176 if (j == NumParts - 1) 10177 MyFlags.Flags.setSplitEnd(); 10178 } 10179 10180 CLI.Outs.push_back(MyFlags); 10181 CLI.OutVals.push_back(Parts[j]); 10182 } 10183 10184 if (NeedsRegBlock && Value == NumValues - 1) 10185 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10186 } 10187 } 10188 10189 SmallVector<SDValue, 4> InVals; 10190 CLI.Chain = LowerCall(CLI, InVals); 10191 10192 // Update CLI.InVals to use outside of this function. 10193 CLI.InVals = InVals; 10194 10195 // Verify that the target's LowerCall behaved as expected. 10196 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10197 "LowerCall didn't return a valid chain!"); 10198 assert((!CLI.IsTailCall || InVals.empty()) && 10199 "LowerCall emitted a return value for a tail call!"); 10200 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10201 "LowerCall didn't emit the correct number of values!"); 10202 10203 // For a tail call, the return value is merely live-out and there aren't 10204 // any nodes in the DAG representing it. Return a special value to 10205 // indicate that a tail call has been emitted and no more Instructions 10206 // should be processed in the current block. 10207 if (CLI.IsTailCall) { 10208 CLI.DAG.setRoot(CLI.Chain); 10209 return std::make_pair(SDValue(), SDValue()); 10210 } 10211 10212 #ifndef NDEBUG 10213 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10214 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10215 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10216 "LowerCall emitted a value with the wrong type!"); 10217 } 10218 #endif 10219 10220 SmallVector<SDValue, 4> ReturnValues; 10221 if (!CanLowerReturn) { 10222 // The instruction result is the result of loading from the 10223 // hidden sret parameter. 10224 SmallVector<EVT, 1> PVTs; 10225 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10226 10227 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10228 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10229 EVT PtrVT = PVTs[0]; 10230 10231 unsigned NumValues = RetTys.size(); 10232 ReturnValues.resize(NumValues); 10233 SmallVector<SDValue, 4> Chains(NumValues); 10234 10235 // An aggregate return value cannot wrap around the address space, so 10236 // offsets to its parts don't wrap either. 10237 SDNodeFlags Flags; 10238 Flags.setNoUnsignedWrap(true); 10239 10240 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10241 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10242 for (unsigned i = 0; i < NumValues; ++i) { 10243 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10244 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10245 PtrVT), Flags); 10246 SDValue L = CLI.DAG.getLoad( 10247 RetTys[i], CLI.DL, CLI.Chain, Add, 10248 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10249 DemoteStackIdx, Offsets[i]), 10250 HiddenSRetAlign); 10251 ReturnValues[i] = L; 10252 Chains[i] = L.getValue(1); 10253 } 10254 10255 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10256 } else { 10257 // Collect the legal value parts into potentially illegal values 10258 // that correspond to the original function's return values. 10259 std::optional<ISD::NodeType> AssertOp; 10260 if (CLI.RetSExt) 10261 AssertOp = ISD::AssertSext; 10262 else if (CLI.RetZExt) 10263 AssertOp = ISD::AssertZext; 10264 unsigned CurReg = 0; 10265 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10266 EVT VT = RetTys[I]; 10267 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10268 CLI.CallConv, VT); 10269 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10270 CLI.CallConv, VT); 10271 10272 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10273 NumRegs, RegisterVT, VT, nullptr, 10274 CLI.CallConv, AssertOp)); 10275 CurReg += NumRegs; 10276 } 10277 10278 // For a function returning void, there is no return value. We can't create 10279 // such a node, so we just return a null return value in that case. In 10280 // that case, nothing will actually look at the value. 10281 if (ReturnValues.empty()) 10282 return std::make_pair(SDValue(), CLI.Chain); 10283 } 10284 10285 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10286 CLI.DAG.getVTList(RetTys), ReturnValues); 10287 return std::make_pair(Res, CLI.Chain); 10288 } 10289 10290 /// Places new result values for the node in Results (their number 10291 /// and types must exactly match those of the original return values of 10292 /// the node), or leaves Results empty, which indicates that the node is not 10293 /// to be custom lowered after all. 10294 void TargetLowering::LowerOperationWrapper(SDNode *N, 10295 SmallVectorImpl<SDValue> &Results, 10296 SelectionDAG &DAG) const { 10297 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10298 10299 if (!Res.getNode()) 10300 return; 10301 10302 // If the original node has one result, take the return value from 10303 // LowerOperation as is. It might not be result number 0. 10304 if (N->getNumValues() == 1) { 10305 Results.push_back(Res); 10306 return; 10307 } 10308 10309 // If the original node has multiple results, then the return node should 10310 // have the same number of results. 10311 assert((N->getNumValues() == Res->getNumValues()) && 10312 "Lowering returned the wrong number of results!"); 10313 10314 // Places new result values base on N result number. 10315 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10316 Results.push_back(Res.getValue(I)); 10317 } 10318 10319 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10320 llvm_unreachable("LowerOperation not implemented for this target!"); 10321 } 10322 10323 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10324 unsigned Reg, 10325 ISD::NodeType ExtendType) { 10326 SDValue Op = getNonRegisterValue(V); 10327 assert((Op.getOpcode() != ISD::CopyFromReg || 10328 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10329 "Copy from a reg to the same reg!"); 10330 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10331 10332 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10333 // If this is an InlineAsm we have to match the registers required, not the 10334 // notional registers required by the type. 10335 10336 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10337 std::nullopt); // This is not an ABI copy. 10338 SDValue Chain = DAG.getEntryNode(); 10339 10340 if (ExtendType == ISD::ANY_EXTEND) { 10341 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10342 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10343 ExtendType = PreferredExtendIt->second; 10344 } 10345 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10346 PendingExports.push_back(Chain); 10347 } 10348 10349 #include "llvm/CodeGen/SelectionDAGISel.h" 10350 10351 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10352 /// entry block, return true. This includes arguments used by switches, since 10353 /// the switch may expand into multiple basic blocks. 10354 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10355 // With FastISel active, we may be splitting blocks, so force creation 10356 // of virtual registers for all non-dead arguments. 10357 if (FastISel) 10358 return A->use_empty(); 10359 10360 const BasicBlock &Entry = A->getParent()->front(); 10361 for (const User *U : A->users()) 10362 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10363 return false; // Use not in entry block. 10364 10365 return true; 10366 } 10367 10368 using ArgCopyElisionMapTy = 10369 DenseMap<const Argument *, 10370 std::pair<const AllocaInst *, const StoreInst *>>; 10371 10372 /// Scan the entry block of the function in FuncInfo for arguments that look 10373 /// like copies into a local alloca. Record any copied arguments in 10374 /// ArgCopyElisionCandidates. 10375 static void 10376 findArgumentCopyElisionCandidates(const DataLayout &DL, 10377 FunctionLoweringInfo *FuncInfo, 10378 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10379 // Record the state of every static alloca used in the entry block. Argument 10380 // allocas are all used in the entry block, so we need approximately as many 10381 // entries as we have arguments. 10382 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10383 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10384 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10385 StaticAllocas.reserve(NumArgs * 2); 10386 10387 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10388 if (!V) 10389 return nullptr; 10390 V = V->stripPointerCasts(); 10391 const auto *AI = dyn_cast<AllocaInst>(V); 10392 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10393 return nullptr; 10394 auto Iter = StaticAllocas.insert({AI, Unknown}); 10395 return &Iter.first->second; 10396 }; 10397 10398 // Look for stores of arguments to static allocas. Look through bitcasts and 10399 // GEPs to handle type coercions, as long as the alloca is fully initialized 10400 // by the store. Any non-store use of an alloca escapes it and any subsequent 10401 // unanalyzed store might write it. 10402 // FIXME: Handle structs initialized with multiple stores. 10403 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10404 // Look for stores, and handle non-store uses conservatively. 10405 const auto *SI = dyn_cast<StoreInst>(&I); 10406 if (!SI) { 10407 // We will look through cast uses, so ignore them completely. 10408 if (I.isCast()) 10409 continue; 10410 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10411 // to allocas. 10412 if (I.isDebugOrPseudoInst()) 10413 continue; 10414 // This is an unknown instruction. Assume it escapes or writes to all 10415 // static alloca operands. 10416 for (const Use &U : I.operands()) { 10417 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10418 *Info = StaticAllocaInfo::Clobbered; 10419 } 10420 continue; 10421 } 10422 10423 // If the stored value is a static alloca, mark it as escaped. 10424 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10425 *Info = StaticAllocaInfo::Clobbered; 10426 10427 // Check if the destination is a static alloca. 10428 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10429 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10430 if (!Info) 10431 continue; 10432 const AllocaInst *AI = cast<AllocaInst>(Dst); 10433 10434 // Skip allocas that have been initialized or clobbered. 10435 if (*Info != StaticAllocaInfo::Unknown) 10436 continue; 10437 10438 // Check if the stored value is an argument, and that this store fully 10439 // initializes the alloca. 10440 // If the argument type has padding bits we can't directly forward a pointer 10441 // as the upper bits may contain garbage. 10442 // Don't elide copies from the same argument twice. 10443 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10444 const auto *Arg = dyn_cast<Argument>(Val); 10445 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10446 Arg->getType()->isEmptyTy() || 10447 DL.getTypeStoreSize(Arg->getType()) != 10448 DL.getTypeAllocSize(AI->getAllocatedType()) || 10449 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10450 ArgCopyElisionCandidates.count(Arg)) { 10451 *Info = StaticAllocaInfo::Clobbered; 10452 continue; 10453 } 10454 10455 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10456 << '\n'); 10457 10458 // Mark this alloca and store for argument copy elision. 10459 *Info = StaticAllocaInfo::Elidable; 10460 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10461 10462 // Stop scanning if we've seen all arguments. This will happen early in -O0 10463 // builds, which is useful, because -O0 builds have large entry blocks and 10464 // many allocas. 10465 if (ArgCopyElisionCandidates.size() == NumArgs) 10466 break; 10467 } 10468 } 10469 10470 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10471 /// ArgVal is a load from a suitable fixed stack object. 10472 static void tryToElideArgumentCopy( 10473 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10474 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10475 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10476 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10477 SDValue ArgVal, bool &ArgHasUses) { 10478 // Check if this is a load from a fixed stack object. 10479 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10480 if (!LNode) 10481 return; 10482 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10483 if (!FINode) 10484 return; 10485 10486 // Check that the fixed stack object is the right size and alignment. 10487 // Look at the alignment that the user wrote on the alloca instead of looking 10488 // at the stack object. 10489 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10490 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10491 const AllocaInst *AI = ArgCopyIter->second.first; 10492 int FixedIndex = FINode->getIndex(); 10493 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10494 int OldIndex = AllocaIndex; 10495 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10496 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10497 LLVM_DEBUG( 10498 dbgs() << " argument copy elision failed due to bad fixed stack " 10499 "object size\n"); 10500 return; 10501 } 10502 Align RequiredAlignment = AI->getAlign(); 10503 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10504 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10505 "greater than stack argument alignment (" 10506 << DebugStr(RequiredAlignment) << " vs " 10507 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10508 return; 10509 } 10510 10511 // Perform the elision. Delete the old stack object and replace its only use 10512 // in the variable info map. Mark the stack object as mutable. 10513 LLVM_DEBUG({ 10514 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10515 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10516 << '\n'; 10517 }); 10518 MFI.RemoveStackObject(OldIndex); 10519 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10520 AllocaIndex = FixedIndex; 10521 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10522 Chains.push_back(ArgVal.getValue(1)); 10523 10524 // Avoid emitting code for the store implementing the copy. 10525 const StoreInst *SI = ArgCopyIter->second.second; 10526 ElidedArgCopyInstrs.insert(SI); 10527 10528 // Check for uses of the argument again so that we can avoid exporting ArgVal 10529 // if it is't used by anything other than the store. 10530 for (const Value *U : Arg.users()) { 10531 if (U != SI) { 10532 ArgHasUses = true; 10533 break; 10534 } 10535 } 10536 } 10537 10538 void SelectionDAGISel::LowerArguments(const Function &F) { 10539 SelectionDAG &DAG = SDB->DAG; 10540 SDLoc dl = SDB->getCurSDLoc(); 10541 const DataLayout &DL = DAG.getDataLayout(); 10542 SmallVector<ISD::InputArg, 16> Ins; 10543 10544 // In Naked functions we aren't going to save any registers. 10545 if (F.hasFnAttribute(Attribute::Naked)) 10546 return; 10547 10548 if (!FuncInfo->CanLowerReturn) { 10549 // Put in an sret pointer parameter before all the other parameters. 10550 SmallVector<EVT, 1> ValueVTs; 10551 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10552 F.getReturnType()->getPointerTo( 10553 DAG.getDataLayout().getAllocaAddrSpace()), 10554 ValueVTs); 10555 10556 // NOTE: Assuming that a pointer will never break down to more than one VT 10557 // or one register. 10558 ISD::ArgFlagsTy Flags; 10559 Flags.setSRet(); 10560 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10561 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10562 ISD::InputArg::NoArgIndex, 0); 10563 Ins.push_back(RetArg); 10564 } 10565 10566 // Look for stores of arguments to static allocas. Mark such arguments with a 10567 // flag to ask the target to give us the memory location of that argument if 10568 // available. 10569 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10570 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10571 ArgCopyElisionCandidates); 10572 10573 // Set up the incoming argument description vector. 10574 for (const Argument &Arg : F.args()) { 10575 unsigned ArgNo = Arg.getArgNo(); 10576 SmallVector<EVT, 4> ValueVTs; 10577 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10578 bool isArgValueUsed = !Arg.use_empty(); 10579 unsigned PartBase = 0; 10580 Type *FinalType = Arg.getType(); 10581 if (Arg.hasAttribute(Attribute::ByVal)) 10582 FinalType = Arg.getParamByValType(); 10583 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10584 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10585 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10586 Value != NumValues; ++Value) { 10587 EVT VT = ValueVTs[Value]; 10588 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10589 ISD::ArgFlagsTy Flags; 10590 10591 10592 if (Arg.getType()->isPointerTy()) { 10593 Flags.setPointer(); 10594 Flags.setPointerAddrSpace( 10595 cast<PointerType>(Arg.getType())->getAddressSpace()); 10596 } 10597 if (Arg.hasAttribute(Attribute::ZExt)) 10598 Flags.setZExt(); 10599 if (Arg.hasAttribute(Attribute::SExt)) 10600 Flags.setSExt(); 10601 if (Arg.hasAttribute(Attribute::InReg)) { 10602 // If we are using vectorcall calling convention, a structure that is 10603 // passed InReg - is surely an HVA 10604 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10605 isa<StructType>(Arg.getType())) { 10606 // The first value of a structure is marked 10607 if (0 == Value) 10608 Flags.setHvaStart(); 10609 Flags.setHva(); 10610 } 10611 // Set InReg Flag 10612 Flags.setInReg(); 10613 } 10614 if (Arg.hasAttribute(Attribute::StructRet)) 10615 Flags.setSRet(); 10616 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10617 Flags.setSwiftSelf(); 10618 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10619 Flags.setSwiftAsync(); 10620 if (Arg.hasAttribute(Attribute::SwiftError)) 10621 Flags.setSwiftError(); 10622 if (Arg.hasAttribute(Attribute::ByVal)) 10623 Flags.setByVal(); 10624 if (Arg.hasAttribute(Attribute::ByRef)) 10625 Flags.setByRef(); 10626 if (Arg.hasAttribute(Attribute::InAlloca)) { 10627 Flags.setInAlloca(); 10628 // Set the byval flag for CCAssignFn callbacks that don't know about 10629 // inalloca. This way we can know how many bytes we should've allocated 10630 // and how many bytes a callee cleanup function will pop. If we port 10631 // inalloca to more targets, we'll have to add custom inalloca handling 10632 // in the various CC lowering callbacks. 10633 Flags.setByVal(); 10634 } 10635 if (Arg.hasAttribute(Attribute::Preallocated)) { 10636 Flags.setPreallocated(); 10637 // Set the byval flag for CCAssignFn callbacks that don't know about 10638 // preallocated. This way we can know how many bytes we should've 10639 // allocated and how many bytes a callee cleanup function will pop. If 10640 // we port preallocated to more targets, we'll have to add custom 10641 // preallocated handling in the various CC lowering callbacks. 10642 Flags.setByVal(); 10643 } 10644 10645 // Certain targets (such as MIPS), may have a different ABI alignment 10646 // for a type depending on the context. Give the target a chance to 10647 // specify the alignment it wants. 10648 const Align OriginalAlignment( 10649 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10650 Flags.setOrigAlign(OriginalAlignment); 10651 10652 Align MemAlign; 10653 Type *ArgMemTy = nullptr; 10654 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10655 Flags.isByRef()) { 10656 if (!ArgMemTy) 10657 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10658 10659 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10660 10661 // For in-memory arguments, size and alignment should be passed from FE. 10662 // BE will guess if this info is not there but there are cases it cannot 10663 // get right. 10664 if (auto ParamAlign = Arg.getParamStackAlign()) 10665 MemAlign = *ParamAlign; 10666 else if ((ParamAlign = Arg.getParamAlign())) 10667 MemAlign = *ParamAlign; 10668 else 10669 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10670 if (Flags.isByRef()) 10671 Flags.setByRefSize(MemSize); 10672 else 10673 Flags.setByValSize(MemSize); 10674 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10675 MemAlign = *ParamAlign; 10676 } else { 10677 MemAlign = OriginalAlignment; 10678 } 10679 Flags.setMemAlign(MemAlign); 10680 10681 if (Arg.hasAttribute(Attribute::Nest)) 10682 Flags.setNest(); 10683 if (NeedsRegBlock) 10684 Flags.setInConsecutiveRegs(); 10685 if (ArgCopyElisionCandidates.count(&Arg)) 10686 Flags.setCopyElisionCandidate(); 10687 if (Arg.hasAttribute(Attribute::Returned)) 10688 Flags.setReturned(); 10689 10690 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10691 *CurDAG->getContext(), F.getCallingConv(), VT); 10692 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10693 *CurDAG->getContext(), F.getCallingConv(), VT); 10694 for (unsigned i = 0; i != NumRegs; ++i) { 10695 // For scalable vectors, use the minimum size; individual targets 10696 // are responsible for handling scalable vector arguments and 10697 // return values. 10698 ISD::InputArg MyFlags( 10699 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10700 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10701 if (NumRegs > 1 && i == 0) 10702 MyFlags.Flags.setSplit(); 10703 // if it isn't first piece, alignment must be 1 10704 else if (i > 0) { 10705 MyFlags.Flags.setOrigAlign(Align(1)); 10706 if (i == NumRegs - 1) 10707 MyFlags.Flags.setSplitEnd(); 10708 } 10709 Ins.push_back(MyFlags); 10710 } 10711 if (NeedsRegBlock && Value == NumValues - 1) 10712 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10713 PartBase += VT.getStoreSize().getKnownMinValue(); 10714 } 10715 } 10716 10717 // Call the target to set up the argument values. 10718 SmallVector<SDValue, 8> InVals; 10719 SDValue NewRoot = TLI->LowerFormalArguments( 10720 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10721 10722 // Verify that the target's LowerFormalArguments behaved as expected. 10723 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10724 "LowerFormalArguments didn't return a valid chain!"); 10725 assert(InVals.size() == Ins.size() && 10726 "LowerFormalArguments didn't emit the correct number of values!"); 10727 LLVM_DEBUG({ 10728 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10729 assert(InVals[i].getNode() && 10730 "LowerFormalArguments emitted a null value!"); 10731 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10732 "LowerFormalArguments emitted a value with the wrong type!"); 10733 } 10734 }); 10735 10736 // Update the DAG with the new chain value resulting from argument lowering. 10737 DAG.setRoot(NewRoot); 10738 10739 // Set up the argument values. 10740 unsigned i = 0; 10741 if (!FuncInfo->CanLowerReturn) { 10742 // Create a virtual register for the sret pointer, and put in a copy 10743 // from the sret argument into it. 10744 SmallVector<EVT, 1> ValueVTs; 10745 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10746 F.getReturnType()->getPointerTo( 10747 DAG.getDataLayout().getAllocaAddrSpace()), 10748 ValueVTs); 10749 MVT VT = ValueVTs[0].getSimpleVT(); 10750 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10751 std::optional<ISD::NodeType> AssertOp; 10752 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10753 nullptr, F.getCallingConv(), AssertOp); 10754 10755 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10756 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10757 Register SRetReg = 10758 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10759 FuncInfo->DemoteRegister = SRetReg; 10760 NewRoot = 10761 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10762 DAG.setRoot(NewRoot); 10763 10764 // i indexes lowered arguments. Bump it past the hidden sret argument. 10765 ++i; 10766 } 10767 10768 SmallVector<SDValue, 4> Chains; 10769 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10770 for (const Argument &Arg : F.args()) { 10771 SmallVector<SDValue, 4> ArgValues; 10772 SmallVector<EVT, 4> ValueVTs; 10773 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10774 unsigned NumValues = ValueVTs.size(); 10775 if (NumValues == 0) 10776 continue; 10777 10778 bool ArgHasUses = !Arg.use_empty(); 10779 10780 // Elide the copying store if the target loaded this argument from a 10781 // suitable fixed stack object. 10782 if (Ins[i].Flags.isCopyElisionCandidate()) { 10783 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10784 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10785 InVals[i], ArgHasUses); 10786 } 10787 10788 // If this argument is unused then remember its value. It is used to generate 10789 // debugging information. 10790 bool isSwiftErrorArg = 10791 TLI->supportSwiftError() && 10792 Arg.hasAttribute(Attribute::SwiftError); 10793 if (!ArgHasUses && !isSwiftErrorArg) { 10794 SDB->setUnusedArgValue(&Arg, InVals[i]); 10795 10796 // Also remember any frame index for use in FastISel. 10797 if (FrameIndexSDNode *FI = 10798 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10799 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10800 } 10801 10802 for (unsigned Val = 0; Val != NumValues; ++Val) { 10803 EVT VT = ValueVTs[Val]; 10804 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10805 F.getCallingConv(), VT); 10806 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10807 *CurDAG->getContext(), F.getCallingConv(), VT); 10808 10809 // Even an apparent 'unused' swifterror argument needs to be returned. So 10810 // we do generate a copy for it that can be used on return from the 10811 // function. 10812 if (ArgHasUses || isSwiftErrorArg) { 10813 std::optional<ISD::NodeType> AssertOp; 10814 if (Arg.hasAttribute(Attribute::SExt)) 10815 AssertOp = ISD::AssertSext; 10816 else if (Arg.hasAttribute(Attribute::ZExt)) 10817 AssertOp = ISD::AssertZext; 10818 10819 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10820 PartVT, VT, nullptr, 10821 F.getCallingConv(), AssertOp)); 10822 } 10823 10824 i += NumParts; 10825 } 10826 10827 // We don't need to do anything else for unused arguments. 10828 if (ArgValues.empty()) 10829 continue; 10830 10831 // Note down frame index. 10832 if (FrameIndexSDNode *FI = 10833 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10834 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10835 10836 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10837 SDB->getCurSDLoc()); 10838 10839 SDB->setValue(&Arg, Res); 10840 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10841 // We want to associate the argument with the frame index, among 10842 // involved operands, that correspond to the lowest address. The 10843 // getCopyFromParts function, called earlier, is swapping the order of 10844 // the operands to BUILD_PAIR depending on endianness. The result of 10845 // that swapping is that the least significant bits of the argument will 10846 // be in the first operand of the BUILD_PAIR node, and the most 10847 // significant bits will be in the second operand. 10848 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10849 if (LoadSDNode *LNode = 10850 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10851 if (FrameIndexSDNode *FI = 10852 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10853 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10854 } 10855 10856 // Analyses past this point are naive and don't expect an assertion. 10857 if (Res.getOpcode() == ISD::AssertZext) 10858 Res = Res.getOperand(0); 10859 10860 // Update the SwiftErrorVRegDefMap. 10861 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10862 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10863 if (Register::isVirtualRegister(Reg)) 10864 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10865 Reg); 10866 } 10867 10868 // If this argument is live outside of the entry block, insert a copy from 10869 // wherever we got it to the vreg that other BB's will reference it as. 10870 if (Res.getOpcode() == ISD::CopyFromReg) { 10871 // If we can, though, try to skip creating an unnecessary vreg. 10872 // FIXME: This isn't very clean... it would be nice to make this more 10873 // general. 10874 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10875 if (Register::isVirtualRegister(Reg)) { 10876 FuncInfo->ValueMap[&Arg] = Reg; 10877 continue; 10878 } 10879 } 10880 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10881 FuncInfo->InitializeRegForValue(&Arg); 10882 SDB->CopyToExportRegsIfNeeded(&Arg); 10883 } 10884 } 10885 10886 if (!Chains.empty()) { 10887 Chains.push_back(NewRoot); 10888 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10889 } 10890 10891 DAG.setRoot(NewRoot); 10892 10893 assert(i == InVals.size() && "Argument register count mismatch!"); 10894 10895 // If any argument copy elisions occurred and we have debug info, update the 10896 // stale frame indices used in the dbg.declare variable info table. 10897 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10898 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10899 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10900 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10901 if (I != ArgCopyElisionFrameIndexMap.end()) 10902 VI.Slot = I->second; 10903 } 10904 } 10905 10906 // Finally, if the target has anything special to do, allow it to do so. 10907 emitFunctionEntryCode(); 10908 } 10909 10910 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10911 /// ensure constants are generated when needed. Remember the virtual registers 10912 /// that need to be added to the Machine PHI nodes as input. We cannot just 10913 /// directly add them, because expansion might result in multiple MBB's for one 10914 /// BB. As such, the start of the BB might correspond to a different MBB than 10915 /// the end. 10916 void 10917 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10918 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10919 10920 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10921 10922 // Check PHI nodes in successors that expect a value to be available from this 10923 // block. 10924 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10925 if (!isa<PHINode>(SuccBB->begin())) continue; 10926 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10927 10928 // If this terminator has multiple identical successors (common for 10929 // switches), only handle each succ once. 10930 if (!SuccsHandled.insert(SuccMBB).second) 10931 continue; 10932 10933 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10934 10935 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10936 // nodes and Machine PHI nodes, but the incoming operands have not been 10937 // emitted yet. 10938 for (const PHINode &PN : SuccBB->phis()) { 10939 // Ignore dead phi's. 10940 if (PN.use_empty()) 10941 continue; 10942 10943 // Skip empty types 10944 if (PN.getType()->isEmptyTy()) 10945 continue; 10946 10947 unsigned Reg; 10948 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10949 10950 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10951 unsigned &RegOut = ConstantsOut[C]; 10952 if (RegOut == 0) { 10953 RegOut = FuncInfo.CreateRegs(C); 10954 // We need to zero/sign extend ConstantInt phi operands to match 10955 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10956 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10957 if (auto *CI = dyn_cast<ConstantInt>(C)) 10958 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10959 : ISD::ZERO_EXTEND; 10960 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10961 } 10962 Reg = RegOut; 10963 } else { 10964 DenseMap<const Value *, Register>::iterator I = 10965 FuncInfo.ValueMap.find(PHIOp); 10966 if (I != FuncInfo.ValueMap.end()) 10967 Reg = I->second; 10968 else { 10969 assert(isa<AllocaInst>(PHIOp) && 10970 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10971 "Didn't codegen value into a register!??"); 10972 Reg = FuncInfo.CreateRegs(PHIOp); 10973 CopyValueToVirtualRegister(PHIOp, Reg); 10974 } 10975 } 10976 10977 // Remember that this register needs to added to the machine PHI node as 10978 // the input for this MBB. 10979 SmallVector<EVT, 4> ValueVTs; 10980 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10981 for (EVT VT : ValueVTs) { 10982 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10983 for (unsigned i = 0; i != NumRegisters; ++i) 10984 FuncInfo.PHINodesToUpdate.push_back( 10985 std::make_pair(&*MBBI++, Reg + i)); 10986 Reg += NumRegisters; 10987 } 10988 } 10989 } 10990 10991 ConstantsOut.clear(); 10992 } 10993 10994 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10995 MachineFunction::iterator I(MBB); 10996 if (++I == FuncInfo.MF->end()) 10997 return nullptr; 10998 return &*I; 10999 } 11000 11001 /// During lowering new call nodes can be created (such as memset, etc.). 11002 /// Those will become new roots of the current DAG, but complications arise 11003 /// when they are tail calls. In such cases, the call lowering will update 11004 /// the root, but the builder still needs to know that a tail call has been 11005 /// lowered in order to avoid generating an additional return. 11006 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11007 // If the node is null, we do have a tail call. 11008 if (MaybeTC.getNode() != nullptr) 11009 DAG.setRoot(MaybeTC); 11010 else 11011 HasTailCall = true; 11012 } 11013 11014 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11015 MachineBasicBlock *SwitchMBB, 11016 MachineBasicBlock *DefaultMBB) { 11017 MachineFunction *CurMF = FuncInfo.MF; 11018 MachineBasicBlock *NextMBB = nullptr; 11019 MachineFunction::iterator BBI(W.MBB); 11020 if (++BBI != FuncInfo.MF->end()) 11021 NextMBB = &*BBI; 11022 11023 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11024 11025 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11026 11027 if (Size == 2 && W.MBB == SwitchMBB) { 11028 // If any two of the cases has the same destination, and if one value 11029 // is the same as the other, but has one bit unset that the other has set, 11030 // use bit manipulation to do two compares at once. For example: 11031 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11032 // TODO: This could be extended to merge any 2 cases in switches with 3 11033 // cases. 11034 // TODO: Handle cases where W.CaseBB != SwitchBB. 11035 CaseCluster &Small = *W.FirstCluster; 11036 CaseCluster &Big = *W.LastCluster; 11037 11038 if (Small.Low == Small.High && Big.Low == Big.High && 11039 Small.MBB == Big.MBB) { 11040 const APInt &SmallValue = Small.Low->getValue(); 11041 const APInt &BigValue = Big.Low->getValue(); 11042 11043 // Check that there is only one bit different. 11044 APInt CommonBit = BigValue ^ SmallValue; 11045 if (CommonBit.isPowerOf2()) { 11046 SDValue CondLHS = getValue(Cond); 11047 EVT VT = CondLHS.getValueType(); 11048 SDLoc DL = getCurSDLoc(); 11049 11050 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11051 DAG.getConstant(CommonBit, DL, VT)); 11052 SDValue Cond = DAG.getSetCC( 11053 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11054 ISD::SETEQ); 11055 11056 // Update successor info. 11057 // Both Small and Big will jump to Small.BB, so we sum up the 11058 // probabilities. 11059 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11060 if (BPI) 11061 addSuccessorWithProb( 11062 SwitchMBB, DefaultMBB, 11063 // The default destination is the first successor in IR. 11064 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11065 else 11066 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11067 11068 // Insert the true branch. 11069 SDValue BrCond = 11070 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11071 DAG.getBasicBlock(Small.MBB)); 11072 // Insert the false branch. 11073 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11074 DAG.getBasicBlock(DefaultMBB)); 11075 11076 DAG.setRoot(BrCond); 11077 return; 11078 } 11079 } 11080 } 11081 11082 if (TM.getOptLevel() != CodeGenOpt::None) { 11083 // Here, we order cases by probability so the most likely case will be 11084 // checked first. However, two clusters can have the same probability in 11085 // which case their relative ordering is non-deterministic. So we use Low 11086 // as a tie-breaker as clusters are guaranteed to never overlap. 11087 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11088 [](const CaseCluster &a, const CaseCluster &b) { 11089 return a.Prob != b.Prob ? 11090 a.Prob > b.Prob : 11091 a.Low->getValue().slt(b.Low->getValue()); 11092 }); 11093 11094 // Rearrange the case blocks so that the last one falls through if possible 11095 // without changing the order of probabilities. 11096 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11097 --I; 11098 if (I->Prob > W.LastCluster->Prob) 11099 break; 11100 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11101 std::swap(*I, *W.LastCluster); 11102 break; 11103 } 11104 } 11105 } 11106 11107 // Compute total probability. 11108 BranchProbability DefaultProb = W.DefaultProb; 11109 BranchProbability UnhandledProbs = DefaultProb; 11110 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11111 UnhandledProbs += I->Prob; 11112 11113 MachineBasicBlock *CurMBB = W.MBB; 11114 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11115 bool FallthroughUnreachable = false; 11116 MachineBasicBlock *Fallthrough; 11117 if (I == W.LastCluster) { 11118 // For the last cluster, fall through to the default destination. 11119 Fallthrough = DefaultMBB; 11120 FallthroughUnreachable = isa<UnreachableInst>( 11121 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11122 } else { 11123 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11124 CurMF->insert(BBI, Fallthrough); 11125 // Put Cond in a virtual register to make it available from the new blocks. 11126 ExportFromCurrentBlock(Cond); 11127 } 11128 UnhandledProbs -= I->Prob; 11129 11130 switch (I->Kind) { 11131 case CC_JumpTable: { 11132 // FIXME: Optimize away range check based on pivot comparisons. 11133 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11134 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11135 11136 // The jump block hasn't been inserted yet; insert it here. 11137 MachineBasicBlock *JumpMBB = JT->MBB; 11138 CurMF->insert(BBI, JumpMBB); 11139 11140 auto JumpProb = I->Prob; 11141 auto FallthroughProb = UnhandledProbs; 11142 11143 // If the default statement is a target of the jump table, we evenly 11144 // distribute the default probability to successors of CurMBB. Also 11145 // update the probability on the edge from JumpMBB to Fallthrough. 11146 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11147 SE = JumpMBB->succ_end(); 11148 SI != SE; ++SI) { 11149 if (*SI == DefaultMBB) { 11150 JumpProb += DefaultProb / 2; 11151 FallthroughProb -= DefaultProb / 2; 11152 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11153 JumpMBB->normalizeSuccProbs(); 11154 break; 11155 } 11156 } 11157 11158 if (FallthroughUnreachable) 11159 JTH->FallthroughUnreachable = true; 11160 11161 if (!JTH->FallthroughUnreachable) 11162 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11163 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11164 CurMBB->normalizeSuccProbs(); 11165 11166 // The jump table header will be inserted in our current block, do the 11167 // range check, and fall through to our fallthrough block. 11168 JTH->HeaderBB = CurMBB; 11169 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11170 11171 // If we're in the right place, emit the jump table header right now. 11172 if (CurMBB == SwitchMBB) { 11173 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11174 JTH->Emitted = true; 11175 } 11176 break; 11177 } 11178 case CC_BitTests: { 11179 // FIXME: Optimize away range check based on pivot comparisons. 11180 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11181 11182 // The bit test blocks haven't been inserted yet; insert them here. 11183 for (BitTestCase &BTC : BTB->Cases) 11184 CurMF->insert(BBI, BTC.ThisBB); 11185 11186 // Fill in fields of the BitTestBlock. 11187 BTB->Parent = CurMBB; 11188 BTB->Default = Fallthrough; 11189 11190 BTB->DefaultProb = UnhandledProbs; 11191 // If the cases in bit test don't form a contiguous range, we evenly 11192 // distribute the probability on the edge to Fallthrough to two 11193 // successors of CurMBB. 11194 if (!BTB->ContiguousRange) { 11195 BTB->Prob += DefaultProb / 2; 11196 BTB->DefaultProb -= DefaultProb / 2; 11197 } 11198 11199 if (FallthroughUnreachable) 11200 BTB->FallthroughUnreachable = true; 11201 11202 // If we're in the right place, emit the bit test header right now. 11203 if (CurMBB == SwitchMBB) { 11204 visitBitTestHeader(*BTB, SwitchMBB); 11205 BTB->Emitted = true; 11206 } 11207 break; 11208 } 11209 case CC_Range: { 11210 const Value *RHS, *LHS, *MHS; 11211 ISD::CondCode CC; 11212 if (I->Low == I->High) { 11213 // Check Cond == I->Low. 11214 CC = ISD::SETEQ; 11215 LHS = Cond; 11216 RHS=I->Low; 11217 MHS = nullptr; 11218 } else { 11219 // Check I->Low <= Cond <= I->High. 11220 CC = ISD::SETLE; 11221 LHS = I->Low; 11222 MHS = Cond; 11223 RHS = I->High; 11224 } 11225 11226 // If Fallthrough is unreachable, fold away the comparison. 11227 if (FallthroughUnreachable) 11228 CC = ISD::SETTRUE; 11229 11230 // The false probability is the sum of all unhandled cases. 11231 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11232 getCurSDLoc(), I->Prob, UnhandledProbs); 11233 11234 if (CurMBB == SwitchMBB) 11235 visitSwitchCase(CB, SwitchMBB); 11236 else 11237 SL->SwitchCases.push_back(CB); 11238 11239 break; 11240 } 11241 } 11242 CurMBB = Fallthrough; 11243 } 11244 } 11245 11246 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11247 CaseClusterIt First, 11248 CaseClusterIt Last) { 11249 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11250 if (X.Prob != CC.Prob) 11251 return X.Prob > CC.Prob; 11252 11253 // Ties are broken by comparing the case value. 11254 return X.Low->getValue().slt(CC.Low->getValue()); 11255 }); 11256 } 11257 11258 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11259 const SwitchWorkListItem &W, 11260 Value *Cond, 11261 MachineBasicBlock *SwitchMBB) { 11262 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11263 "Clusters not sorted?"); 11264 11265 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11266 11267 // Balance the tree based on branch probabilities to create a near-optimal (in 11268 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11269 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11270 CaseClusterIt LastLeft = W.FirstCluster; 11271 CaseClusterIt FirstRight = W.LastCluster; 11272 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11273 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11274 11275 // Move LastLeft and FirstRight towards each other from opposite directions to 11276 // find a partitioning of the clusters which balances the probability on both 11277 // sides. If LeftProb and RightProb are equal, alternate which side is 11278 // taken to ensure 0-probability nodes are distributed evenly. 11279 unsigned I = 0; 11280 while (LastLeft + 1 < FirstRight) { 11281 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11282 LeftProb += (++LastLeft)->Prob; 11283 else 11284 RightProb += (--FirstRight)->Prob; 11285 I++; 11286 } 11287 11288 while (true) { 11289 // Our binary search tree differs from a typical BST in that ours can have up 11290 // to three values in each leaf. The pivot selection above doesn't take that 11291 // into account, which means the tree might require more nodes and be less 11292 // efficient. We compensate for this here. 11293 11294 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11295 unsigned NumRight = W.LastCluster - FirstRight + 1; 11296 11297 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11298 // If one side has less than 3 clusters, and the other has more than 3, 11299 // consider taking a cluster from the other side. 11300 11301 if (NumLeft < NumRight) { 11302 // Consider moving the first cluster on the right to the left side. 11303 CaseCluster &CC = *FirstRight; 11304 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11305 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11306 if (LeftSideRank <= RightSideRank) { 11307 // Moving the cluster to the left does not demote it. 11308 ++LastLeft; 11309 ++FirstRight; 11310 continue; 11311 } 11312 } else { 11313 assert(NumRight < NumLeft); 11314 // Consider moving the last element on the left to the right side. 11315 CaseCluster &CC = *LastLeft; 11316 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11317 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11318 if (RightSideRank <= LeftSideRank) { 11319 // Moving the cluster to the right does not demot it. 11320 --LastLeft; 11321 --FirstRight; 11322 continue; 11323 } 11324 } 11325 } 11326 break; 11327 } 11328 11329 assert(LastLeft + 1 == FirstRight); 11330 assert(LastLeft >= W.FirstCluster); 11331 assert(FirstRight <= W.LastCluster); 11332 11333 // Use the first element on the right as pivot since we will make less-than 11334 // comparisons against it. 11335 CaseClusterIt PivotCluster = FirstRight; 11336 assert(PivotCluster > W.FirstCluster); 11337 assert(PivotCluster <= W.LastCluster); 11338 11339 CaseClusterIt FirstLeft = W.FirstCluster; 11340 CaseClusterIt LastRight = W.LastCluster; 11341 11342 const ConstantInt *Pivot = PivotCluster->Low; 11343 11344 // New blocks will be inserted immediately after the current one. 11345 MachineFunction::iterator BBI(W.MBB); 11346 ++BBI; 11347 11348 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11349 // we can branch to its destination directly if it's squeezed exactly in 11350 // between the known lower bound and Pivot - 1. 11351 MachineBasicBlock *LeftMBB; 11352 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11353 FirstLeft->Low == W.GE && 11354 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11355 LeftMBB = FirstLeft->MBB; 11356 } else { 11357 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11358 FuncInfo.MF->insert(BBI, LeftMBB); 11359 WorkList.push_back( 11360 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11361 // Put Cond in a virtual register to make it available from the new blocks. 11362 ExportFromCurrentBlock(Cond); 11363 } 11364 11365 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11366 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11367 // directly if RHS.High equals the current upper bound. 11368 MachineBasicBlock *RightMBB; 11369 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11370 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11371 RightMBB = FirstRight->MBB; 11372 } else { 11373 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11374 FuncInfo.MF->insert(BBI, RightMBB); 11375 WorkList.push_back( 11376 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11377 // Put Cond in a virtual register to make it available from the new blocks. 11378 ExportFromCurrentBlock(Cond); 11379 } 11380 11381 // Create the CaseBlock record that will be used to lower the branch. 11382 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11383 getCurSDLoc(), LeftProb, RightProb); 11384 11385 if (W.MBB == SwitchMBB) 11386 visitSwitchCase(CB, SwitchMBB); 11387 else 11388 SL->SwitchCases.push_back(CB); 11389 } 11390 11391 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11392 // from the swith statement. 11393 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11394 BranchProbability PeeledCaseProb) { 11395 if (PeeledCaseProb == BranchProbability::getOne()) 11396 return BranchProbability::getZero(); 11397 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11398 11399 uint32_t Numerator = CaseProb.getNumerator(); 11400 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11401 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11402 } 11403 11404 // Try to peel the top probability case if it exceeds the threshold. 11405 // Return current MachineBasicBlock for the switch statement if the peeling 11406 // does not occur. 11407 // If the peeling is performed, return the newly created MachineBasicBlock 11408 // for the peeled switch statement. Also update Clusters to remove the peeled 11409 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11410 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11411 const SwitchInst &SI, CaseClusterVector &Clusters, 11412 BranchProbability &PeeledCaseProb) { 11413 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11414 // Don't perform if there is only one cluster or optimizing for size. 11415 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11416 TM.getOptLevel() == CodeGenOpt::None || 11417 SwitchMBB->getParent()->getFunction().hasMinSize()) 11418 return SwitchMBB; 11419 11420 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11421 unsigned PeeledCaseIndex = 0; 11422 bool SwitchPeeled = false; 11423 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11424 CaseCluster &CC = Clusters[Index]; 11425 if (CC.Prob < TopCaseProb) 11426 continue; 11427 TopCaseProb = CC.Prob; 11428 PeeledCaseIndex = Index; 11429 SwitchPeeled = true; 11430 } 11431 if (!SwitchPeeled) 11432 return SwitchMBB; 11433 11434 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11435 << TopCaseProb << "\n"); 11436 11437 // Record the MBB for the peeled switch statement. 11438 MachineFunction::iterator BBI(SwitchMBB); 11439 ++BBI; 11440 MachineBasicBlock *PeeledSwitchMBB = 11441 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11442 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11443 11444 ExportFromCurrentBlock(SI.getCondition()); 11445 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11446 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11447 nullptr, nullptr, TopCaseProb.getCompl()}; 11448 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11449 11450 Clusters.erase(PeeledCaseIt); 11451 for (CaseCluster &CC : Clusters) { 11452 LLVM_DEBUG( 11453 dbgs() << "Scale the probablity for one cluster, before scaling: " 11454 << CC.Prob << "\n"); 11455 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11456 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11457 } 11458 PeeledCaseProb = TopCaseProb; 11459 return PeeledSwitchMBB; 11460 } 11461 11462 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11463 // Extract cases from the switch. 11464 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11465 CaseClusterVector Clusters; 11466 Clusters.reserve(SI.getNumCases()); 11467 for (auto I : SI.cases()) { 11468 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11469 const ConstantInt *CaseVal = I.getCaseValue(); 11470 BranchProbability Prob = 11471 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11472 : BranchProbability(1, SI.getNumCases() + 1); 11473 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11474 } 11475 11476 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11477 11478 // Cluster adjacent cases with the same destination. We do this at all 11479 // optimization levels because it's cheap to do and will make codegen faster 11480 // if there are many clusters. 11481 sortAndRangeify(Clusters); 11482 11483 // The branch probablity of the peeled case. 11484 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11485 MachineBasicBlock *PeeledSwitchMBB = 11486 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11487 11488 // If there is only the default destination, jump there directly. 11489 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11490 if (Clusters.empty()) { 11491 assert(PeeledSwitchMBB == SwitchMBB); 11492 SwitchMBB->addSuccessor(DefaultMBB); 11493 if (DefaultMBB != NextBlock(SwitchMBB)) { 11494 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11495 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11496 } 11497 return; 11498 } 11499 11500 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11501 SL->findBitTestClusters(Clusters, &SI); 11502 11503 LLVM_DEBUG({ 11504 dbgs() << "Case clusters: "; 11505 for (const CaseCluster &C : Clusters) { 11506 if (C.Kind == CC_JumpTable) 11507 dbgs() << "JT:"; 11508 if (C.Kind == CC_BitTests) 11509 dbgs() << "BT:"; 11510 11511 C.Low->getValue().print(dbgs(), true); 11512 if (C.Low != C.High) { 11513 dbgs() << '-'; 11514 C.High->getValue().print(dbgs(), true); 11515 } 11516 dbgs() << ' '; 11517 } 11518 dbgs() << '\n'; 11519 }); 11520 11521 assert(!Clusters.empty()); 11522 SwitchWorkList WorkList; 11523 CaseClusterIt First = Clusters.begin(); 11524 CaseClusterIt Last = Clusters.end() - 1; 11525 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11526 // Scale the branchprobability for DefaultMBB if the peel occurs and 11527 // DefaultMBB is not replaced. 11528 if (PeeledCaseProb != BranchProbability::getZero() && 11529 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11530 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11531 WorkList.push_back( 11532 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11533 11534 while (!WorkList.empty()) { 11535 SwitchWorkListItem W = WorkList.pop_back_val(); 11536 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11537 11538 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11539 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11540 // For optimized builds, lower large range as a balanced binary tree. 11541 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11542 continue; 11543 } 11544 11545 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11546 } 11547 } 11548 11549 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11551 auto DL = getCurSDLoc(); 11552 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11553 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11554 } 11555 11556 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11557 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11558 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11559 11560 SDLoc DL = getCurSDLoc(); 11561 SDValue V = getValue(I.getOperand(0)); 11562 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11563 11564 if (VT.isScalableVector()) { 11565 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11566 return; 11567 } 11568 11569 // Use VECTOR_SHUFFLE for the fixed-length vector 11570 // to maintain existing behavior. 11571 SmallVector<int, 8> Mask; 11572 unsigned NumElts = VT.getVectorMinNumElements(); 11573 for (unsigned i = 0; i != NumElts; ++i) 11574 Mask.push_back(NumElts - 1 - i); 11575 11576 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11577 } 11578 11579 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11580 auto DL = getCurSDLoc(); 11581 SDValue InVec = getValue(I.getOperand(0)); 11582 EVT OutVT = 11583 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11584 11585 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11586 11587 // ISD Node needs the input vectors split into two equal parts 11588 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11589 DAG.getVectorIdxConstant(0, DL)); 11590 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11591 DAG.getVectorIdxConstant(OutNumElts, DL)); 11592 11593 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11594 // legalisation and combines. 11595 if (OutVT.isFixedLengthVector()) { 11596 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11597 createStrideMask(0, 2, OutNumElts)); 11598 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11599 createStrideMask(1, 2, OutNumElts)); 11600 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11601 setValue(&I, Res); 11602 return; 11603 } 11604 11605 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11606 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11607 setValue(&I, Res); 11608 return; 11609 } 11610 11611 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11612 auto DL = getCurSDLoc(); 11613 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11614 SDValue InVec0 = getValue(I.getOperand(0)); 11615 SDValue InVec1 = getValue(I.getOperand(1)); 11616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11617 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11618 11619 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11620 // legalisation and combines. 11621 if (OutVT.isFixedLengthVector()) { 11622 unsigned NumElts = InVT.getVectorMinNumElements(); 11623 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11624 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11625 createInterleaveMask(NumElts, 2))); 11626 return; 11627 } 11628 11629 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11630 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11631 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11632 Res.getValue(1)); 11633 setValue(&I, Res); 11634 return; 11635 } 11636 11637 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11638 SmallVector<EVT, 4> ValueVTs; 11639 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11640 ValueVTs); 11641 unsigned NumValues = ValueVTs.size(); 11642 if (NumValues == 0) return; 11643 11644 SmallVector<SDValue, 4> Values(NumValues); 11645 SDValue Op = getValue(I.getOperand(0)); 11646 11647 for (unsigned i = 0; i != NumValues; ++i) 11648 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11649 SDValue(Op.getNode(), Op.getResNo() + i)); 11650 11651 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11652 DAG.getVTList(ValueVTs), Values)); 11653 } 11654 11655 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11657 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11658 11659 SDLoc DL = getCurSDLoc(); 11660 SDValue V1 = getValue(I.getOperand(0)); 11661 SDValue V2 = getValue(I.getOperand(1)); 11662 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11663 11664 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11665 if (VT.isScalableVector()) { 11666 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11667 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11668 DAG.getConstant(Imm, DL, IdxVT))); 11669 return; 11670 } 11671 11672 unsigned NumElts = VT.getVectorNumElements(); 11673 11674 uint64_t Idx = (NumElts + Imm) % NumElts; 11675 11676 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11677 SmallVector<int, 8> Mask; 11678 for (unsigned i = 0; i < NumElts; ++i) 11679 Mask.push_back(Idx + i); 11680 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11681 } 11682 11683 // Consider the following MIR after SelectionDAG, which produces output in 11684 // phyregs in the first case or virtregs in the second case. 11685 // 11686 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11687 // %5:gr32 = COPY $ebx 11688 // %6:gr32 = COPY $edx 11689 // %1:gr32 = COPY %6:gr32 11690 // %0:gr32 = COPY %5:gr32 11691 // 11692 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11693 // %1:gr32 = COPY %6:gr32 11694 // %0:gr32 = COPY %5:gr32 11695 // 11696 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11697 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11698 // 11699 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11700 // to a single virtreg (such as %0). The remaining outputs monotonically 11701 // increase in virtreg number from there. If a callbr has no outputs, then it 11702 // should not have a corresponding callbr landingpad; in fact, the callbr 11703 // landingpad would not even be able to refer to such a callbr. 11704 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11705 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11706 // There is definitely at least one copy. 11707 assert(MI->getOpcode() == TargetOpcode::COPY && 11708 "start of copy chain MUST be COPY"); 11709 Reg = MI->getOperand(1).getReg(); 11710 MI = MRI.def_begin(Reg)->getParent(); 11711 // There may be an optional second copy. 11712 if (MI->getOpcode() == TargetOpcode::COPY) { 11713 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11714 Reg = MI->getOperand(1).getReg(); 11715 assert(Reg.isPhysical() && "expected COPY of physical register"); 11716 MI = MRI.def_begin(Reg)->getParent(); 11717 } 11718 // The start of the chain must be an INLINEASM_BR. 11719 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11720 "end of copy chain MUST be INLINEASM_BR"); 11721 return Reg; 11722 } 11723 11724 // We must do this walk rather than the simpler 11725 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11726 // otherwise we will end up with copies of virtregs only valid along direct 11727 // edges. 11728 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11729 SmallVector<EVT, 8> ResultVTs; 11730 SmallVector<SDValue, 8> ResultValues; 11731 const auto *CBR = 11732 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11733 11734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11735 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11736 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11737 11738 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11739 SDValue Chain = DAG.getRoot(); 11740 11741 // Re-parse the asm constraints string. 11742 TargetLowering::AsmOperandInfoVector TargetConstraints = 11743 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11744 for (auto &T : TargetConstraints) { 11745 SDISelAsmOperandInfo OpInfo(T); 11746 if (OpInfo.Type != InlineAsm::isOutput) 11747 continue; 11748 11749 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11750 // individual constraint. 11751 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11752 11753 switch (OpInfo.ConstraintType) { 11754 case TargetLowering::C_Register: 11755 case TargetLowering::C_RegisterClass: { 11756 // Fill in OpInfo.AssignedRegs.Regs. 11757 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11758 11759 // getRegistersForValue may produce 1 to many registers based on whether 11760 // the OpInfo.ConstraintVT is legal on the target or not. 11761 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11762 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11763 if (Register::isPhysicalRegister(OriginalDef)) 11764 FuncInfo.MBB->addLiveIn(OriginalDef); 11765 // Update the assigned registers to use the original defs. 11766 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11767 } 11768 11769 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11770 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11771 ResultValues.push_back(V); 11772 ResultVTs.push_back(OpInfo.ConstraintVT); 11773 break; 11774 } 11775 case TargetLowering::C_Other: { 11776 SDValue Flag; 11777 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11778 OpInfo, DAG); 11779 ++InitialDef; 11780 ResultValues.push_back(V); 11781 ResultVTs.push_back(OpInfo.ConstraintVT); 11782 break; 11783 } 11784 default: 11785 break; 11786 } 11787 } 11788 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11789 DAG.getVTList(ResultVTs), ResultValues); 11790 setValue(&I, V); 11791 } 11792