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/Triple.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/Analysis/BranchProbabilityInfo.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/Loads.h" 28 #include "llvm/Analysis/MemoryLocation.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueTracking.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/Transforms/Utils/Local.h" 100 #include <cstddef> 101 #include <iterator> 102 #include <limits> 103 #include <optional> 104 #include <tuple> 105 106 using namespace llvm; 107 using namespace PatternMatch; 108 using namespace SwitchCG; 109 110 #define DEBUG_TYPE "isel" 111 112 /// LimitFloatPrecision - Generate low-precision inline sequences for 113 /// some float libcalls (6, 8 or 12 bits). 114 static unsigned LimitFloatPrecision; 115 116 static cl::opt<bool> 117 InsertAssertAlign("insert-assert-align", cl::init(true), 118 cl::desc("Insert the experimental `assertalign` node."), 119 cl::ReallyHidden); 120 121 static cl::opt<unsigned, true> 122 LimitFPPrecision("limit-float-precision", 123 cl::desc("Generate low-precision inline sequences " 124 "for some float libcalls"), 125 cl::location(LimitFloatPrecision), cl::Hidden, 126 cl::init(0)); 127 128 static cl::opt<unsigned> SwitchPeelThreshold( 129 "switch-peel-threshold", cl::Hidden, cl::init(66), 130 cl::desc("Set the case probability threshold for peeling the case from a " 131 "switch statement. A value greater than 100 will void this " 132 "optimization")); 133 134 // Limit the width of DAG chains. This is important in general to prevent 135 // DAG-based analysis from blowing up. For example, alias analysis and 136 // load clustering may not complete in reasonable time. It is difficult to 137 // recognize and avoid this situation within each individual analysis, and 138 // future analyses are likely to have the same behavior. Limiting DAG width is 139 // the safe approach and will be especially important with global DAGs. 140 // 141 // MaxParallelChains default is arbitrarily high to avoid affecting 142 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 143 // sequence over this should have been converted to llvm.memcpy by the 144 // frontend. It is easy to induce this behavior with .ll code such as: 145 // %buffer = alloca [4096 x i8] 146 // %data = load [4096 x i8]* %argPtr 147 // store [4096 x i8] %data, [4096 x i8]* %buffer 148 static const unsigned MaxParallelChains = 64; 149 150 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 151 const SDValue *Parts, unsigned NumParts, 152 MVT PartVT, EVT ValueVT, const Value *V, 153 std::optional<CallingConv::ID> CC); 154 155 /// getCopyFromParts - Create a value that contains the specified legal parts 156 /// combined into the value they represent. If the parts combine to a type 157 /// larger than ValueVT then AssertOp can be used to specify whether the extra 158 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 159 /// (ISD::AssertSext). 160 static SDValue 161 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 162 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 163 std::optional<CallingConv::ID> CC = std::nullopt, 164 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 165 // Let the target assemble the parts if it wants to 166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 167 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 168 PartVT, ValueVT, CC)) 169 return Val; 170 171 if (ValueVT.isVector()) 172 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 173 CC); 174 175 assert(NumParts > 0 && "No parts to assemble!"); 176 SDValue Val = Parts[0]; 177 178 if (NumParts > 1) { 179 // Assemble the value from multiple parts. 180 if (ValueVT.isInteger()) { 181 unsigned PartBits = PartVT.getSizeInBits(); 182 unsigned ValueBits = ValueVT.getSizeInBits(); 183 184 // Assemble the power of 2 part. 185 unsigned RoundParts = llvm::bit_floor(NumParts); 186 unsigned RoundBits = PartBits * RoundParts; 187 EVT RoundVT = RoundBits == ValueBits ? 188 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 189 SDValue Lo, Hi; 190 191 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 192 193 if (RoundParts > 2) { 194 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 195 PartVT, HalfVT, V); 196 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 197 RoundParts / 2, PartVT, HalfVT, V); 198 } else { 199 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 200 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 201 } 202 203 if (DAG.getDataLayout().isBigEndian()) 204 std::swap(Lo, Hi); 205 206 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 207 208 if (RoundParts < NumParts) { 209 // Assemble the trailing non-power-of-2 part. 210 unsigned OddParts = NumParts - RoundParts; 211 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 212 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 213 OddVT, V, CC); 214 215 // Combine the round and odd parts. 216 Lo = Val; 217 if (DAG.getDataLayout().isBigEndian()) 218 std::swap(Lo, Hi); 219 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 220 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 221 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 222 DAG.getConstant(Lo.getValueSizeInBits(), DL, 223 TLI.getShiftAmountTy( 224 TotalVT, DAG.getDataLayout()))); 225 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 226 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 227 } 228 } else if (PartVT.isFloatingPoint()) { 229 // FP split into multiple FP parts (for ppcf128) 230 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 231 "Unexpected split"); 232 SDValue Lo, Hi; 233 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 235 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 236 std::swap(Lo, Hi); 237 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 238 } else { 239 // FP split into integer parts (soft fp) 240 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 241 !PartVT.isVector() && "Unexpected split"); 242 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 243 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 244 } 245 } 246 247 // There is now one part, held in Val. Correct it to match ValueVT. 248 // PartEVT is the type of the register class that holds the value. 249 // ValueVT is the type of the inline asm operation. 250 EVT PartEVT = Val.getValueType(); 251 252 if (PartEVT == ValueVT) 253 return Val; 254 255 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 256 ValueVT.bitsLT(PartEVT)) { 257 // For an FP value in an integer part, we need to truncate to the right 258 // width first. 259 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 260 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 261 } 262 263 // Handle types that have the same size. 264 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 265 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 266 267 // Handle types with different sizes. 268 if (PartEVT.isInteger() && ValueVT.isInteger()) { 269 if (ValueVT.bitsLT(PartEVT)) { 270 // For a truncate, see if we have any information to 271 // indicate whether the truncated bits will always be 272 // zero or sign-extension. 273 if (AssertOp) 274 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 275 DAG.getValueType(ValueVT)); 276 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 277 } 278 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 279 } 280 281 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 282 // FP_ROUND's are always exact here. 283 if (ValueVT.bitsLT(Val.getValueType())) 284 return DAG.getNode( 285 ISD::FP_ROUND, DL, ValueVT, Val, 286 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 287 288 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 289 } 290 291 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 292 // then truncating. 293 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 294 ValueVT.bitsLT(PartEVT)) { 295 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 296 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 297 } 298 299 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 300 } 301 302 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 303 const Twine &ErrMsg) { 304 const Instruction *I = dyn_cast_or_null<Instruction>(V); 305 if (!V) 306 return Ctx.emitError(ErrMsg); 307 308 const char *AsmError = ", possible invalid constraint for vector type"; 309 if (const CallInst *CI = dyn_cast<CallInst>(I)) 310 if (CI->isInlineAsm()) 311 return Ctx.emitError(I, ErrMsg + AsmError); 312 313 return Ctx.emitError(I, ErrMsg); 314 } 315 316 /// getCopyFromPartsVector - Create a value that contains the specified legal 317 /// parts combined into the value they represent. If the parts combine to a 318 /// type larger than ValueVT then AssertOp can be used to specify whether the 319 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 320 /// ValueVT (ISD::AssertSext). 321 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 322 const SDValue *Parts, unsigned NumParts, 323 MVT PartVT, EVT ValueVT, const Value *V, 324 std::optional<CallingConv::ID> CallConv) { 325 assert(ValueVT.isVector() && "Not a vector value"); 326 assert(NumParts > 0 && "No parts to assemble!"); 327 const bool IsABIRegCopy = CallConv.has_value(); 328 329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 330 SDValue Val = Parts[0]; 331 332 // Handle a multi-element vector. 333 if (NumParts > 1) { 334 EVT IntermediateVT; 335 MVT RegisterVT; 336 unsigned NumIntermediates; 337 unsigned NumRegs; 338 339 if (IsABIRegCopy) { 340 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 341 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 342 NumIntermediates, RegisterVT); 343 } else { 344 NumRegs = 345 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 346 NumIntermediates, RegisterVT); 347 } 348 349 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 350 NumParts = NumRegs; // Silence a compiler warning. 351 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 352 assert(RegisterVT.getSizeInBits() == 353 Parts[0].getSimpleValueType().getSizeInBits() && 354 "Part type sizes don't match!"); 355 356 // Assemble the parts into intermediate operands. 357 SmallVector<SDValue, 8> Ops(NumIntermediates); 358 if (NumIntermediates == NumParts) { 359 // If the register was not expanded, truncate or copy the value, 360 // as appropriate. 361 for (unsigned i = 0; i != NumParts; ++i) 362 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 363 PartVT, IntermediateVT, V, CallConv); 364 } else if (NumParts > 0) { 365 // If the intermediate type was expanded, build the intermediate 366 // operands from the parts. 367 assert(NumParts % NumIntermediates == 0 && 368 "Must expand into a divisible number of parts!"); 369 unsigned Factor = NumParts / NumIntermediates; 370 for (unsigned i = 0; i != NumIntermediates; ++i) 371 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 372 PartVT, IntermediateVT, V, CallConv); 373 } 374 375 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 376 // intermediate operands. 377 EVT BuiltVectorTy = 378 IntermediateVT.isVector() 379 ? EVT::getVectorVT( 380 *DAG.getContext(), IntermediateVT.getScalarType(), 381 IntermediateVT.getVectorElementCount() * NumParts) 382 : EVT::getVectorVT(*DAG.getContext(), 383 IntermediateVT.getScalarType(), 384 NumIntermediates); 385 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 386 : ISD::BUILD_VECTOR, 387 DL, BuiltVectorTy, Ops); 388 } 389 390 // There is now one part, held in Val. Correct it to match ValueVT. 391 EVT PartEVT = Val.getValueType(); 392 393 if (PartEVT == ValueVT) 394 return Val; 395 396 if (PartEVT.isVector()) { 397 // Vector/Vector bitcast. 398 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 399 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 400 401 // If the parts vector has more elements than the value vector, then we 402 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 403 // Extract the elements we want. 404 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 405 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 406 ValueVT.getVectorElementCount().getKnownMinValue()) && 407 (PartEVT.getVectorElementCount().isScalable() == 408 ValueVT.getVectorElementCount().isScalable()) && 409 "Cannot narrow, it would be a lossy transformation"); 410 PartEVT = 411 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 412 ValueVT.getVectorElementCount()); 413 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 414 DAG.getVectorIdxConstant(0, DL)); 415 if (PartEVT == ValueVT) 416 return Val; 417 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 } 420 421 // Promoted vector extract 422 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 423 } 424 425 // Trivial bitcast if the types are the same size and the destination 426 // vector type is legal. 427 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 428 TLI.isTypeLegal(ValueVT)) 429 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 430 431 if (ValueVT.getVectorNumElements() != 1) { 432 // Certain ABIs require that vectors are passed as integers. For vectors 433 // are the same size, this is an obvious bitcast. 434 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 } else if (ValueVT.bitsLT(PartEVT)) { 437 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 438 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 439 // Drop the extra bits. 440 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 441 return DAG.getBitcast(ValueVT, Val); 442 } 443 444 diagnosePossiblyInvalidConstraint( 445 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 446 return DAG.getUNDEF(ValueVT); 447 } 448 449 // Handle cases such as i8 -> <1 x i1> 450 EVT ValueSVT = ValueVT.getVectorElementType(); 451 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 452 unsigned ValueSize = ValueSVT.getSizeInBits(); 453 if (ValueSize == PartEVT.getSizeInBits()) { 454 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 455 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 456 // It's possible a scalar floating point type gets softened to integer and 457 // then promoted to a larger integer. If PartEVT is the larger integer 458 // we need to truncate it and then bitcast to the FP type. 459 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 461 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 462 Val = DAG.getBitcast(ValueSVT, Val); 463 } else { 464 Val = ValueVT.isFloatingPoint() 465 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 466 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 467 } 468 } 469 470 return DAG.getBuildVector(ValueVT, DL, Val); 471 } 472 473 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 474 SDValue Val, SDValue *Parts, unsigned NumParts, 475 MVT PartVT, const Value *V, 476 std::optional<CallingConv::ID> CallConv); 477 478 /// getCopyToParts - Create a series of nodes that contain the specified value 479 /// split into legal parts. If the parts contain more bits than Val, then, for 480 /// integers, ExtendKind can be used to specify how to generate the extra bits. 481 static void 482 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 483 unsigned NumParts, MVT PartVT, const Value *V, 484 std::optional<CallingConv::ID> CallConv = std::nullopt, 485 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 486 // Let the target split the parts if it wants to 487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 488 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 489 CallConv)) 490 return; 491 EVT ValueVT = Val.getValueType(); 492 493 // Handle the vector case separately. 494 if (ValueVT.isVector()) 495 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 496 CallConv); 497 498 unsigned PartBits = PartVT.getSizeInBits(); 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 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 515 // If the parts cover more bits than the value has, promote the value. 516 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 517 assert(NumParts == 1 && "Do not know what to promote to!"); 518 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 519 } else { 520 if (ValueVT.isFloatingPoint()) { 521 // FP values need to be bitcast, then extended if they are being put 522 // into a larger container. 523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 524 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 525 } 526 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 527 ValueVT.isInteger() && 528 "Unknown mismatch!"); 529 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 530 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 531 if (PartVT == MVT::x86mmx) 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } 534 } else if (PartBits == ValueVT.getSizeInBits()) { 535 // Different types of the same size. 536 assert(NumParts == 1 && PartEVT != ValueVT); 537 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 538 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 539 // If the parts cover less bits than value has, truncate the value. 540 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 541 ValueVT.isInteger() && 542 "Unknown mismatch!"); 543 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 544 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 545 if (PartVT == MVT::x86mmx) 546 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 547 } 548 549 // The value may have changed - recompute ValueVT. 550 ValueVT = Val.getValueType(); 551 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 552 "Failed to tile the value with PartVT!"); 553 554 if (NumParts == 1) { 555 if (PartEVT != ValueVT) { 556 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 557 "scalar-to-vector conversion failed"); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } 560 561 Parts[0] = Val; 562 return; 563 } 564 565 // Expand the value into multiple parts. 566 if (NumParts & (NumParts - 1)) { 567 // The number of parts is not a power of 2. Split off and copy the tail. 568 assert(PartVT.isInteger() && ValueVT.isInteger() && 569 "Do not know what to expand to!"); 570 unsigned RoundParts = llvm::bit_floor(NumParts); 571 unsigned RoundBits = RoundParts * PartBits; 572 unsigned OddParts = NumParts - RoundParts; 573 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 574 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 575 576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 577 CallConv); 578 579 if (DAG.getDataLayout().isBigEndian()) 580 // The odd parts were reversed by getCopyToParts - unreverse them. 581 std::reverse(Parts + RoundParts, Parts + NumParts); 582 583 NumParts = RoundParts; 584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 586 } 587 588 // The number of parts is a power of 2. Repeatedly bisect the value using 589 // EXTRACT_ELEMENT. 590 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 591 EVT::getIntegerVT(*DAG.getContext(), 592 ValueVT.getSizeInBits()), 593 Val); 594 595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 596 for (unsigned i = 0; i < NumParts; i += StepSize) { 597 unsigned ThisBits = StepSize * PartBits / 2; 598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 599 SDValue &Part0 = Parts[i]; 600 SDValue &Part1 = Parts[i+StepSize/2]; 601 602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 606 607 if (ThisBits == PartBits && ThisVT != PartVT) { 608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 610 } 611 } 612 } 613 614 if (DAG.getDataLayout().isBigEndian()) 615 std::reverse(Parts, Parts + OrigNumParts); 616 } 617 618 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 619 const SDLoc &DL, EVT PartVT) { 620 if (!PartVT.isVector()) 621 return SDValue(); 622 623 EVT ValueVT = Val.getValueType(); 624 ElementCount PartNumElts = PartVT.getVectorElementCount(); 625 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 626 627 // We only support widening vectors with equivalent element types and 628 // fixed/scalable properties. If a target needs to widen a fixed-length type 629 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 630 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 631 PartNumElts.isScalable() != ValueNumElts.isScalable() || 632 PartVT.getVectorElementType() != ValueVT.getVectorElementType()) 633 return SDValue(); 634 635 // Widening a scalable vector to another scalable vector is done by inserting 636 // the vector into a larger undef one. 637 if (PartNumElts.isScalable()) 638 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 639 Val, DAG.getVectorIdxConstant(0, DL)); 640 641 EVT ElementVT = PartVT.getVectorElementType(); 642 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 643 // undef elements. 644 SmallVector<SDValue, 16> Ops; 645 DAG.ExtractVectorElements(Val, Ops); 646 SDValue EltUndef = DAG.getUNDEF(ElementVT); 647 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 648 649 // FIXME: Use CONCAT for 2x -> 4x. 650 return DAG.getBuildVector(PartVT, DL, Ops); 651 } 652 653 /// getCopyToPartsVector - Create a series of nodes that contain the specified 654 /// value split into legal parts. 655 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 656 SDValue Val, SDValue *Parts, unsigned NumParts, 657 MVT PartVT, const Value *V, 658 std::optional<CallingConv::ID> CallConv) { 659 EVT ValueVT = Val.getValueType(); 660 assert(ValueVT.isVector() && "Not a vector"); 661 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 662 const bool IsABIRegCopy = CallConv.has_value(); 663 664 if (NumParts == 1) { 665 EVT PartEVT = PartVT; 666 if (PartEVT == ValueVT) { 667 // Nothing to do. 668 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 669 // Bitconvert vector->vector case. 670 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 671 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 672 Val = Widened; 673 } else if (PartVT.isVector() && 674 PartEVT.getVectorElementType().bitsGE( 675 ValueVT.getVectorElementType()) && 676 PartEVT.getVectorElementCount() == 677 ValueVT.getVectorElementCount()) { 678 679 // Promoted vector extract 680 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 681 } else if (PartEVT.isVector() && 682 PartEVT.getVectorElementType() != 683 ValueVT.getVectorElementType() && 684 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 685 TargetLowering::TypeWidenVector) { 686 // Combination of widening and promotion. 687 EVT WidenVT = 688 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 689 PartVT.getVectorElementCount()); 690 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 691 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 692 } else { 693 // Don't extract an integer from a float vector. This can happen if the 694 // FP type gets softened to integer and then promoted. The promotion 695 // prevents it from being picked up by the earlier bitcast case. 696 if (ValueVT.getVectorElementCount().isScalar() && 697 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 698 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 699 DAG.getVectorIdxConstant(0, DL)); 700 } else { 701 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 702 assert(PartVT.getFixedSizeInBits() > ValueSize && 703 "lossy conversion of vector to scalar type"); 704 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 705 Val = DAG.getBitcast(IntermediateType, Val); 706 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 707 } 708 } 709 710 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 711 Parts[0] = Val; 712 return; 713 } 714 715 // Handle a multi-element vector. 716 EVT IntermediateVT; 717 MVT RegisterVT; 718 unsigned NumIntermediates; 719 unsigned NumRegs; 720 if (IsABIRegCopy) { 721 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 722 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 723 RegisterVT); 724 } else { 725 NumRegs = 726 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 727 NumIntermediates, RegisterVT); 728 } 729 730 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 731 NumParts = NumRegs; // Silence a compiler warning. 732 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 733 734 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 735 "Mixing scalable and fixed vectors when copying in parts"); 736 737 std::optional<ElementCount> DestEltCnt; 738 739 if (IntermediateVT.isVector()) 740 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 741 else 742 DestEltCnt = ElementCount::getFixed(NumIntermediates); 743 744 EVT BuiltVectorTy = EVT::getVectorVT( 745 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 746 747 if (ValueVT == BuiltVectorTy) { 748 // Nothing to do. 749 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 750 // Bitconvert vector->vector case. 751 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 752 } else { 753 if (BuiltVectorTy.getVectorElementType().bitsGT( 754 ValueVT.getVectorElementType())) { 755 // Integer promotion. 756 ValueVT = EVT::getVectorVT(*DAG.getContext(), 757 BuiltVectorTy.getVectorElementType(), 758 ValueVT.getVectorElementCount()); 759 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 760 } 761 762 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 763 Val = Widened; 764 } 765 } 766 767 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 768 769 // Split the vector into intermediate operands. 770 SmallVector<SDValue, 8> Ops(NumIntermediates); 771 for (unsigned i = 0; i != NumIntermediates; ++i) { 772 if (IntermediateVT.isVector()) { 773 // This does something sensible for scalable vectors - see the 774 // definition of EXTRACT_SUBVECTOR for further details. 775 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 776 Ops[i] = 777 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 778 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 779 } else { 780 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 781 DAG.getVectorIdxConstant(i, DL)); 782 } 783 } 784 785 // Split the intermediate operands into legal parts. 786 if (NumParts == NumIntermediates) { 787 // If the register was not expanded, promote or copy the value, 788 // as appropriate. 789 for (unsigned i = 0; i != NumParts; ++i) 790 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 791 } else if (NumParts > 0) { 792 // If the intermediate type was expanded, split each the value into 793 // legal parts. 794 assert(NumIntermediates != 0 && "division by zero"); 795 assert(NumParts % NumIntermediates == 0 && 796 "Must expand into a divisible number of parts!"); 797 unsigned Factor = NumParts / NumIntermediates; 798 for (unsigned i = 0; i != NumIntermediates; ++i) 799 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 800 CallConv); 801 } 802 } 803 804 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 805 EVT valuevt, std::optional<CallingConv::ID> CC) 806 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 807 RegCount(1, regs.size()), CallConv(CC) {} 808 809 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 810 const DataLayout &DL, unsigned Reg, Type *Ty, 811 std::optional<CallingConv::ID> CC) { 812 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 813 814 CallConv = CC; 815 816 for (EVT ValueVT : ValueVTs) { 817 unsigned NumRegs = 818 isABIMangled() 819 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 820 : TLI.getNumRegisters(Context, ValueVT); 821 MVT RegisterVT = 822 isABIMangled() 823 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 824 : TLI.getRegisterType(Context, ValueVT); 825 for (unsigned i = 0; i != NumRegs; ++i) 826 Regs.push_back(Reg + i); 827 RegVTs.push_back(RegisterVT); 828 RegCount.push_back(NumRegs); 829 Reg += NumRegs; 830 } 831 } 832 833 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 834 FunctionLoweringInfo &FuncInfo, 835 const SDLoc &dl, SDValue &Chain, 836 SDValue *Flag, const Value *V) const { 837 // A Value with type {} or [0 x %t] needs no registers. 838 if (ValueVTs.empty()) 839 return SDValue(); 840 841 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 842 843 // Assemble the legal parts into the final values. 844 SmallVector<SDValue, 4> Values(ValueVTs.size()); 845 SmallVector<SDValue, 8> Parts; 846 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 847 // Copy the legal parts from the registers. 848 EVT ValueVT = ValueVTs[Value]; 849 unsigned NumRegs = RegCount[Value]; 850 MVT RegisterVT = isABIMangled() 851 ? TLI.getRegisterTypeForCallingConv( 852 *DAG.getContext(), *CallConv, RegVTs[Value]) 853 : RegVTs[Value]; 854 855 Parts.resize(NumRegs); 856 for (unsigned i = 0; i != NumRegs; ++i) { 857 SDValue P; 858 if (!Flag) { 859 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 860 } else { 861 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 862 *Flag = P.getValue(2); 863 } 864 865 Chain = P.getValue(1); 866 Parts[i] = P; 867 868 // If the source register was virtual and if we know something about it, 869 // add an assert node. 870 if (!Register::isVirtualRegister(Regs[Part + i]) || 871 !RegisterVT.isInteger()) 872 continue; 873 874 const FunctionLoweringInfo::LiveOutInfo *LOI = 875 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 876 if (!LOI) 877 continue; 878 879 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 880 unsigned NumSignBits = LOI->NumSignBits; 881 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 882 883 if (NumZeroBits == RegSize) { 884 // The current value is a zero. 885 // Explicitly express that as it would be easier for 886 // optimizations to kick in. 887 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 888 continue; 889 } 890 891 // FIXME: We capture more information than the dag can represent. For 892 // now, just use the tightest assertzext/assertsext possible. 893 bool isSExt; 894 EVT FromVT(MVT::Other); 895 if (NumZeroBits) { 896 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 897 isSExt = false; 898 } else if (NumSignBits > 1) { 899 FromVT = 900 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 901 isSExt = true; 902 } else { 903 continue; 904 } 905 // Add an assertion node. 906 assert(FromVT != MVT::Other); 907 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 908 RegisterVT, P, DAG.getValueType(FromVT)); 909 } 910 911 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 912 RegisterVT, ValueVT, V, CallConv); 913 Part += NumRegs; 914 Parts.clear(); 915 } 916 917 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 918 } 919 920 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 921 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 922 const Value *V, 923 ISD::NodeType PreferredExtendType) const { 924 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 925 ISD::NodeType ExtendKind = PreferredExtendType; 926 927 // Get the list of the values's legal parts. 928 unsigned NumRegs = Regs.size(); 929 SmallVector<SDValue, 8> Parts(NumRegs); 930 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 931 unsigned NumParts = RegCount[Value]; 932 933 MVT RegisterVT = isABIMangled() 934 ? TLI.getRegisterTypeForCallingConv( 935 *DAG.getContext(), *CallConv, RegVTs[Value]) 936 : RegVTs[Value]; 937 938 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 939 ExtendKind = ISD::ZERO_EXTEND; 940 941 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 942 NumParts, RegisterVT, V, CallConv, ExtendKind); 943 Part += NumParts; 944 } 945 946 // Copy the parts into the registers. 947 SmallVector<SDValue, 8> Chains(NumRegs); 948 for (unsigned i = 0; i != NumRegs; ++i) { 949 SDValue Part; 950 if (!Flag) { 951 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 952 } else { 953 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 954 *Flag = Part.getValue(1); 955 } 956 957 Chains[i] = Part.getValue(0); 958 } 959 960 if (NumRegs == 1 || Flag) 961 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 962 // flagged to it. That is the CopyToReg nodes and the user are considered 963 // a single scheduling unit. If we create a TokenFactor and return it as 964 // chain, then the TokenFactor is both a predecessor (operand) of the 965 // user as well as a successor (the TF operands are flagged to the user). 966 // c1, f1 = CopyToReg 967 // c2, f2 = CopyToReg 968 // c3 = TokenFactor c1, c2 969 // ... 970 // = op c3, ..., f2 971 Chain = Chains[NumRegs-1]; 972 else 973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 974 } 975 976 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 977 unsigned MatchingIdx, const SDLoc &dl, 978 SelectionDAG &DAG, 979 std::vector<SDValue> &Ops) const { 980 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 981 982 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 983 if (HasMatching) 984 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 985 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 986 // Put the register class of the virtual registers in the flag word. That 987 // way, later passes can recompute register class constraints for inline 988 // assembly as well as normal instructions. 989 // Don't do this for tied operands that can use the regclass information 990 // from the def. 991 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 992 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 993 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 994 } 995 996 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 997 Ops.push_back(Res); 998 999 if (Code == InlineAsm::Kind_Clobber) { 1000 // Clobbers should always have a 1:1 mapping with registers, and may 1001 // reference registers that have illegal (e.g. vector) types. Hence, we 1002 // shouldn't try to apply any sort of splitting logic to them. 1003 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1004 "No 1:1 mapping from clobbers to regs?"); 1005 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1006 (void)SP; 1007 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1008 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1009 assert( 1010 (Regs[I] != SP || 1011 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1012 "If we clobbered the stack pointer, MFI should know about it."); 1013 } 1014 return; 1015 } 1016 1017 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1018 MVT RegisterVT = RegVTs[Value]; 1019 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1020 RegisterVT); 1021 for (unsigned i = 0; i != NumRegs; ++i) { 1022 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1023 unsigned TheReg = Regs[Reg++]; 1024 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1025 } 1026 } 1027 } 1028 1029 SmallVector<std::pair<unsigned, TypeSize>, 4> 1030 RegsForValue::getRegsAndSizes() const { 1031 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1032 unsigned I = 0; 1033 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1034 unsigned RegCount = std::get<0>(CountAndVT); 1035 MVT RegisterVT = std::get<1>(CountAndVT); 1036 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1037 for (unsigned E = I + RegCount; I != E; ++I) 1038 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1039 } 1040 return OutVec; 1041 } 1042 1043 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1044 AssumptionCache *ac, 1045 const TargetLibraryInfo *li) { 1046 AA = aa; 1047 AC = ac; 1048 GFI = gfi; 1049 LibInfo = li; 1050 Context = DAG.getContext(); 1051 LPadToCallSiteMap.clear(); 1052 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1053 } 1054 1055 void SelectionDAGBuilder::clear() { 1056 NodeMap.clear(); 1057 UnusedArgNodeMap.clear(); 1058 PendingLoads.clear(); 1059 PendingExports.clear(); 1060 PendingConstrainedFP.clear(); 1061 PendingConstrainedFPStrict.clear(); 1062 CurInst = nullptr; 1063 HasTailCall = false; 1064 SDNodeOrder = LowestSDNodeOrder; 1065 StatepointLowering.clear(); 1066 } 1067 1068 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1069 DanglingDebugInfoMap.clear(); 1070 } 1071 1072 // Update DAG root to include dependencies on Pending chains. 1073 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1074 SDValue Root = DAG.getRoot(); 1075 1076 if (Pending.empty()) 1077 return Root; 1078 1079 // Add current root to PendingChains, unless we already indirectly 1080 // depend on it. 1081 if (Root.getOpcode() != ISD::EntryToken) { 1082 unsigned i = 0, e = Pending.size(); 1083 for (; i != e; ++i) { 1084 assert(Pending[i].getNode()->getNumOperands() > 1); 1085 if (Pending[i].getNode()->getOperand(0) == Root) 1086 break; // Don't add the root if we already indirectly depend on it. 1087 } 1088 1089 if (i == e) 1090 Pending.push_back(Root); 1091 } 1092 1093 if (Pending.size() == 1) 1094 Root = Pending[0]; 1095 else 1096 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1097 1098 DAG.setRoot(Root); 1099 Pending.clear(); 1100 return Root; 1101 } 1102 1103 SDValue SelectionDAGBuilder::getMemoryRoot() { 1104 return updateRoot(PendingLoads); 1105 } 1106 1107 SDValue SelectionDAGBuilder::getRoot() { 1108 // Chain up all pending constrained intrinsics together with all 1109 // pending loads, by simply appending them to PendingLoads and 1110 // then calling getMemoryRoot(). 1111 PendingLoads.reserve(PendingLoads.size() + 1112 PendingConstrainedFP.size() + 1113 PendingConstrainedFPStrict.size()); 1114 PendingLoads.append(PendingConstrainedFP.begin(), 1115 PendingConstrainedFP.end()); 1116 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1117 PendingConstrainedFPStrict.end()); 1118 PendingConstrainedFP.clear(); 1119 PendingConstrainedFPStrict.clear(); 1120 return getMemoryRoot(); 1121 } 1122 1123 SDValue SelectionDAGBuilder::getControlRoot() { 1124 // We need to emit pending fpexcept.strict constrained intrinsics, 1125 // so append them to the PendingExports list. 1126 PendingExports.append(PendingConstrainedFPStrict.begin(), 1127 PendingConstrainedFPStrict.end()); 1128 PendingConstrainedFPStrict.clear(); 1129 return updateRoot(PendingExports); 1130 } 1131 1132 void SelectionDAGBuilder::visit(const Instruction &I) { 1133 // Set up outgoing PHI node register values before emitting the terminator. 1134 if (I.isTerminator()) { 1135 HandlePHINodesInSuccessorBlocks(I.getParent()); 1136 } 1137 1138 // Add SDDbgValue nodes for any var locs here. Do so before updating 1139 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1140 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1141 // Add SDDbgValue nodes for any var locs here. Do so before updating 1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1143 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1144 It != End; ++It) { 1145 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1146 dropDanglingDebugInfo(Var, It->Expr); 1147 if (!handleDebugValue(It->V, Var, It->Expr, It->DL, SDNodeOrder, 1148 /*IsVariadic=*/false)) 1149 addDanglingDebugInfo(It, SDNodeOrder); 1150 } 1151 } 1152 1153 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1154 if (!isa<DbgInfoIntrinsic>(I)) 1155 ++SDNodeOrder; 1156 1157 CurInst = &I; 1158 1159 // Set inserted listener only if required. 1160 bool NodeInserted = false; 1161 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1162 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1163 if (PCSectionsMD) { 1164 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1165 DAG, [&](SDNode *) { NodeInserted = true; }); 1166 } 1167 1168 visit(I.getOpcode(), I); 1169 1170 if (!I.isTerminator() && !HasTailCall && 1171 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1172 CopyToExportRegsIfNeeded(&I); 1173 1174 // Handle metadata. 1175 if (PCSectionsMD) { 1176 auto It = NodeMap.find(&I); 1177 if (It != NodeMap.end()) { 1178 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1179 } else if (NodeInserted) { 1180 // This should not happen; if it does, don't let it go unnoticed so we can 1181 // fix it. Relevant visit*() function is probably missing a setValue(). 1182 errs() << "warning: loosing !pcsections metadata [" 1183 << I.getModule()->getName() << "]\n"; 1184 LLVM_DEBUG(I.dump()); 1185 assert(false); 1186 } 1187 } 1188 1189 CurInst = nullptr; 1190 } 1191 1192 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1193 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1194 } 1195 1196 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1197 // Note: this doesn't use InstVisitor, because it has to work with 1198 // ConstantExpr's in addition to instructions. 1199 switch (Opcode) { 1200 default: llvm_unreachable("Unknown instruction type encountered!"); 1201 // Build the switch statement using the Instruction.def file. 1202 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1203 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1204 #include "llvm/IR/Instruction.def" 1205 } 1206 } 1207 1208 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1209 unsigned Order) { 1210 DanglingDebugInfoMap[VarLoc->V].emplace_back(VarLoc, Order); 1211 } 1212 1213 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1214 unsigned Order) { 1215 // We treat variadic dbg_values differently at this stage. 1216 if (DI->hasArgList()) { 1217 // For variadic dbg_values we will now insert an undef. 1218 // FIXME: We can potentially recover these! 1219 SmallVector<SDDbgOperand, 2> Locs; 1220 for (const Value *V : DI->getValues()) { 1221 auto Undef = UndefValue::get(V->getType()); 1222 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1223 } 1224 SDDbgValue *SDV = DAG.getDbgValueList( 1225 DI->getVariable(), DI->getExpression(), Locs, {}, 1226 /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true); 1227 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1228 } else { 1229 // TODO: Dangling debug info will eventually either be resolved or produce 1230 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1231 // between the original dbg.value location and its resolved DBG_VALUE, 1232 // which we should ideally fill with an extra Undef DBG_VALUE. 1233 assert(DI->getNumVariableLocationOps() == 1 && 1234 "DbgValueInst without an ArgList should have a single location " 1235 "operand."); 1236 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1237 } 1238 } 1239 1240 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1241 const DIExpression *Expr) { 1242 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1243 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1244 DIExpression *DanglingExpr = DDI.getExpression(); 1245 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1246 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1247 << "\n"); 1248 return true; 1249 } 1250 return false; 1251 }; 1252 1253 for (auto &DDIMI : DanglingDebugInfoMap) { 1254 DanglingDebugInfoVector &DDIV = DDIMI.second; 1255 1256 // If debug info is to be dropped, run it through final checks to see 1257 // whether it can be salvaged. 1258 for (auto &DDI : DDIV) 1259 if (isMatchingDbgValue(DDI)) 1260 salvageUnresolvedDbgValue(DDI); 1261 1262 erase_if(DDIV, isMatchingDbgValue); 1263 } 1264 } 1265 1266 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1267 // generate the debug data structures now that we've seen its definition. 1268 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1269 SDValue Val) { 1270 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1271 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1272 return; 1273 1274 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1275 for (auto &DDI : DDIV) { 1276 DebugLoc DL = DDI.getDebugLoc(); 1277 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1278 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1279 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1280 DIExpression *Expr = DDI.getExpression(); 1281 assert(Variable->isValidLocationForIntrinsic(DL) && 1282 "Expected inlined-at fields to agree"); 1283 SDDbgValue *SDV; 1284 if (Val.getNode()) { 1285 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1286 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1287 // we couldn't resolve it directly when examining the DbgValue intrinsic 1288 // in the first place we should not be more successful here). Unless we 1289 // have some test case that prove this to be correct we should avoid 1290 // calling EmitFuncArgumentDbgValue here. 1291 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1292 FuncArgumentDbgValueKind::Value, Val)) { 1293 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1294 << "\n"); 1295 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1296 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1297 // inserted after the definition of Val when emitting the instructions 1298 // after ISel. An alternative could be to teach 1299 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1300 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1301 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1302 << ValSDNodeOrder << "\n"); 1303 SDV = getDbgValue(Val, Variable, Expr, DL, 1304 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1305 DAG.AddDbgValue(SDV, false); 1306 } else 1307 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1308 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1309 } else { 1310 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1311 auto Undef = UndefValue::get(V->getType()); 1312 auto SDV = 1313 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1314 DAG.AddDbgValue(SDV, false); 1315 } 1316 } 1317 DDIV.clear(); 1318 } 1319 1320 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1321 // TODO: For the variadic implementation, instead of only checking the fail 1322 // state of `handleDebugValue`, we need know specifically which values were 1323 // invalid, so that we attempt to salvage only those values when processing 1324 // a DIArgList. 1325 Value *V = DDI.getVariableLocationOp(0); 1326 Value *OrigV = V; 1327 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1328 DIExpression *Expr = DDI.getExpression(); 1329 DebugLoc DL = DDI.getDebugLoc(); 1330 unsigned SDOrder = DDI.getSDNodeOrder(); 1331 1332 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1333 // that DW_OP_stack_value is desired. 1334 bool StackValue = true; 1335 1336 // Can this Value can be encoded without any further work? 1337 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1338 return; 1339 1340 // Attempt to salvage back through as many instructions as possible. Bail if 1341 // a non-instruction is seen, such as a constant expression or global 1342 // variable. FIXME: Further work could recover those too. 1343 while (isa<Instruction>(V)) { 1344 Instruction &VAsInst = *cast<Instruction>(V); 1345 // Temporary "0", awaiting real implementation. 1346 SmallVector<uint64_t, 16> Ops; 1347 SmallVector<Value *, 4> AdditionalValues; 1348 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1349 AdditionalValues); 1350 // If we cannot salvage any further, and haven't yet found a suitable debug 1351 // expression, bail out. 1352 if (!V) 1353 break; 1354 1355 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1356 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1357 // here for variadic dbg_values, remove that condition. 1358 if (!AdditionalValues.empty()) 1359 break; 1360 1361 // New value and expr now represent this debuginfo. 1362 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1363 1364 // Some kind of simplification occurred: check whether the operand of the 1365 // salvaged debug expression can be encoded in this DAG. 1366 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1367 LLVM_DEBUG( 1368 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1369 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1370 return; 1371 } 1372 } 1373 1374 // This was the final opportunity to salvage this debug information, and it 1375 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1376 // any earlier variable location. 1377 assert(OrigV && "V shouldn't be null"); 1378 auto *Undef = UndefValue::get(OrigV->getType()); 1379 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1380 DAG.AddDbgValue(SDV, false); 1381 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1382 << "\n"); 1383 } 1384 1385 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1386 DILocalVariable *Var, 1387 DIExpression *Expr, DebugLoc DbgLoc, 1388 unsigned Order, bool IsVariadic) { 1389 if (Values.empty()) 1390 return true; 1391 SmallVector<SDDbgOperand> LocationOps; 1392 SmallVector<SDNode *> Dependencies; 1393 for (const Value *V : Values) { 1394 // Constant value. 1395 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1396 isa<ConstantPointerNull>(V)) { 1397 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1398 continue; 1399 } 1400 1401 // Look through IntToPtr constants. 1402 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1403 if (CE->getOpcode() == Instruction::IntToPtr) { 1404 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1405 continue; 1406 } 1407 1408 // If the Value is a frame index, we can create a FrameIndex debug value 1409 // without relying on the DAG at all. 1410 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1411 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1412 if (SI != FuncInfo.StaticAllocaMap.end()) { 1413 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1414 continue; 1415 } 1416 } 1417 1418 // Do not use getValue() in here; we don't want to generate code at 1419 // this point if it hasn't been done yet. 1420 SDValue N = NodeMap[V]; 1421 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1422 N = UnusedArgNodeMap[V]; 1423 if (N.getNode()) { 1424 // Only emit func arg dbg value for non-variadic dbg.values for now. 1425 if (!IsVariadic && 1426 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1427 FuncArgumentDbgValueKind::Value, N)) 1428 return true; 1429 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1430 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1431 // describe stack slot locations. 1432 // 1433 // Consider "int x = 0; int *px = &x;". There are two kinds of 1434 // interesting debug values here after optimization: 1435 // 1436 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1437 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1438 // 1439 // Both describe the direct values of their associated variables. 1440 Dependencies.push_back(N.getNode()); 1441 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1442 continue; 1443 } 1444 LocationOps.emplace_back( 1445 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1446 continue; 1447 } 1448 1449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1450 // Special rules apply for the first dbg.values of parameter variables in a 1451 // function. Identify them by the fact they reference Argument Values, that 1452 // they're parameters, and they are parameters of the current function. We 1453 // need to let them dangle until they get an SDNode. 1454 bool IsParamOfFunc = 1455 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1456 if (IsParamOfFunc) 1457 return false; 1458 1459 // The value is not used in this block yet (or it would have an SDNode). 1460 // We still want the value to appear for the user if possible -- if it has 1461 // an associated VReg, we can refer to that instead. 1462 auto VMI = FuncInfo.ValueMap.find(V); 1463 if (VMI != FuncInfo.ValueMap.end()) { 1464 unsigned Reg = VMI->second; 1465 // If this is a PHI node, it may be split up into several MI PHI nodes 1466 // (in FunctionLoweringInfo::set). 1467 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1468 V->getType(), std::nullopt); 1469 if (RFV.occupiesMultipleRegs()) { 1470 // FIXME: We could potentially support variadic dbg_values here. 1471 if (IsVariadic) 1472 return false; 1473 unsigned Offset = 0; 1474 unsigned BitsToDescribe = 0; 1475 if (auto VarSize = Var->getSizeInBits()) 1476 BitsToDescribe = *VarSize; 1477 if (auto Fragment = Expr->getFragmentInfo()) 1478 BitsToDescribe = Fragment->SizeInBits; 1479 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1480 // Bail out if all bits are described already. 1481 if (Offset >= BitsToDescribe) 1482 break; 1483 // TODO: handle scalable vectors. 1484 unsigned RegisterSize = RegAndSize.second; 1485 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1486 ? BitsToDescribe - Offset 1487 : RegisterSize; 1488 auto FragmentExpr = DIExpression::createFragmentExpression( 1489 Expr, Offset, FragmentSize); 1490 if (!FragmentExpr) 1491 continue; 1492 SDDbgValue *SDV = DAG.getVRegDbgValue( 1493 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1494 DAG.AddDbgValue(SDV, false); 1495 Offset += RegisterSize; 1496 } 1497 return true; 1498 } 1499 // We can use simple vreg locations for variadic dbg_values as well. 1500 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1501 continue; 1502 } 1503 // We failed to create a SDDbgOperand for V. 1504 return false; 1505 } 1506 1507 // We have created a SDDbgOperand for each Value in Values. 1508 // Should use Order instead of SDNodeOrder? 1509 assert(!LocationOps.empty()); 1510 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1511 /*IsIndirect=*/false, DbgLoc, 1512 SDNodeOrder, IsVariadic); 1513 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1514 return true; 1515 } 1516 1517 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1518 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1519 for (auto &Pair : DanglingDebugInfoMap) 1520 for (auto &DDI : Pair.second) 1521 salvageUnresolvedDbgValue(DDI); 1522 clearDanglingDebugInfo(); 1523 } 1524 1525 /// getCopyFromRegs - If there was virtual register allocated for the value V 1526 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1527 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1528 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1529 SDValue Result; 1530 1531 if (It != FuncInfo.ValueMap.end()) { 1532 Register InReg = It->second; 1533 1534 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1535 DAG.getDataLayout(), InReg, Ty, 1536 std::nullopt); // This is not an ABI copy. 1537 SDValue Chain = DAG.getEntryNode(); 1538 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1539 V); 1540 resolveDanglingDebugInfo(V, Result); 1541 } 1542 1543 return Result; 1544 } 1545 1546 /// getValue - Return an SDValue for the given Value. 1547 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1548 // If we already have an SDValue for this value, use it. It's important 1549 // to do this first, so that we don't create a CopyFromReg if we already 1550 // have a regular SDValue. 1551 SDValue &N = NodeMap[V]; 1552 if (N.getNode()) return N; 1553 1554 // If there's a virtual register allocated and initialized for this 1555 // value, use it. 1556 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1557 return copyFromReg; 1558 1559 // Otherwise create a new SDValue and remember it. 1560 SDValue Val = getValueImpl(V); 1561 NodeMap[V] = Val; 1562 resolveDanglingDebugInfo(V, Val); 1563 return Val; 1564 } 1565 1566 /// getNonRegisterValue - Return an SDValue for the given Value, but 1567 /// don't look in FuncInfo.ValueMap for a virtual register. 1568 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1569 // If we already have an SDValue for this value, use it. 1570 SDValue &N = NodeMap[V]; 1571 if (N.getNode()) { 1572 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1573 // Remove the debug location from the node as the node is about to be used 1574 // in a location which may differ from the original debug location. This 1575 // is relevant to Constant and ConstantFP nodes because they can appear 1576 // as constant expressions inside PHI nodes. 1577 N->setDebugLoc(DebugLoc()); 1578 } 1579 return N; 1580 } 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 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1590 /// Create an SDValue for the given value. 1591 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1593 1594 if (const Constant *C = dyn_cast<Constant>(V)) { 1595 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1596 1597 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1598 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1599 1600 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1601 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1602 1603 if (isa<ConstantPointerNull>(C)) { 1604 unsigned AS = V->getType()->getPointerAddressSpace(); 1605 return DAG.getConstant(0, getCurSDLoc(), 1606 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1607 } 1608 1609 if (match(C, m_VScale(DAG.getDataLayout()))) 1610 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1611 1612 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1613 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1614 1615 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1616 return DAG.getUNDEF(VT); 1617 1618 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1619 visit(CE->getOpcode(), *CE); 1620 SDValue N1 = NodeMap[V]; 1621 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1622 return N1; 1623 } 1624 1625 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1626 SmallVector<SDValue, 4> Constants; 1627 for (const Use &U : C->operands()) { 1628 SDNode *Val = getValue(U).getNode(); 1629 // If the operand is an empty aggregate, there are no values. 1630 if (!Val) continue; 1631 // Add each leaf value from the operand to the Constants list 1632 // to form a flattened list of all the values. 1633 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1634 Constants.push_back(SDValue(Val, i)); 1635 } 1636 1637 return DAG.getMergeValues(Constants, getCurSDLoc()); 1638 } 1639 1640 if (const ConstantDataSequential *CDS = 1641 dyn_cast<ConstantDataSequential>(C)) { 1642 SmallVector<SDValue, 4> Ops; 1643 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1644 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1645 // Add each leaf value from the operand to the Constants list 1646 // to form a flattened list of all the values. 1647 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1648 Ops.push_back(SDValue(Val, i)); 1649 } 1650 1651 if (isa<ArrayType>(CDS->getType())) 1652 return DAG.getMergeValues(Ops, getCurSDLoc()); 1653 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1654 } 1655 1656 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1657 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1658 "Unknown struct or array constant!"); 1659 1660 SmallVector<EVT, 4> ValueVTs; 1661 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1662 unsigned NumElts = ValueVTs.size(); 1663 if (NumElts == 0) 1664 return SDValue(); // empty struct 1665 SmallVector<SDValue, 4> Constants(NumElts); 1666 for (unsigned i = 0; i != NumElts; ++i) { 1667 EVT EltVT = ValueVTs[i]; 1668 if (isa<UndefValue>(C)) 1669 Constants[i] = DAG.getUNDEF(EltVT); 1670 else if (EltVT.isFloatingPoint()) 1671 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1672 else 1673 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1674 } 1675 1676 return DAG.getMergeValues(Constants, getCurSDLoc()); 1677 } 1678 1679 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1680 return DAG.getBlockAddress(BA, VT); 1681 1682 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1683 return getValue(Equiv->getGlobalValue()); 1684 1685 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1686 return getValue(NC->getGlobalValue()); 1687 1688 VectorType *VecTy = cast<VectorType>(V->getType()); 1689 1690 // Now that we know the number and type of the elements, get that number of 1691 // elements into the Ops array based on what kind of constant it is. 1692 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1693 SmallVector<SDValue, 16> Ops; 1694 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1695 for (unsigned i = 0; i != NumElements; ++i) 1696 Ops.push_back(getValue(CV->getOperand(i))); 1697 1698 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1699 } 1700 1701 if (isa<ConstantAggregateZero>(C)) { 1702 EVT EltVT = 1703 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1704 1705 SDValue Op; 1706 if (EltVT.isFloatingPoint()) 1707 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1708 else 1709 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1710 1711 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1712 } 1713 1714 llvm_unreachable("Unknown vector constant"); 1715 } 1716 1717 // If this is a static alloca, generate it as the frameindex instead of 1718 // computation. 1719 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1720 DenseMap<const AllocaInst*, int>::iterator SI = 1721 FuncInfo.StaticAllocaMap.find(AI); 1722 if (SI != FuncInfo.StaticAllocaMap.end()) 1723 return DAG.getFrameIndex( 1724 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1725 } 1726 1727 // If this is an instruction which fast-isel has deferred, select it now. 1728 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1729 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1730 1731 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1732 Inst->getType(), std::nullopt); 1733 SDValue Chain = DAG.getEntryNode(); 1734 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1735 } 1736 1737 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1738 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1739 1740 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1741 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1742 1743 llvm_unreachable("Can't get register for value!"); 1744 } 1745 1746 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1747 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1748 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1749 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1750 bool IsSEH = isAsynchronousEHPersonality(Pers); 1751 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1752 if (!IsSEH) 1753 CatchPadMBB->setIsEHScopeEntry(); 1754 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1755 if (IsMSVCCXX || IsCoreCLR) 1756 CatchPadMBB->setIsEHFuncletEntry(); 1757 } 1758 1759 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1760 // Update machine-CFG edge. 1761 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1762 FuncInfo.MBB->addSuccessor(TargetMBB); 1763 TargetMBB->setIsEHCatchretTarget(true); 1764 DAG.getMachineFunction().setHasEHCatchret(true); 1765 1766 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1767 bool IsSEH = isAsynchronousEHPersonality(Pers); 1768 if (IsSEH) { 1769 // If this is not a fall-through branch or optimizations are switched off, 1770 // emit the branch. 1771 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1772 TM.getOptLevel() == CodeGenOpt::None) 1773 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1774 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1775 return; 1776 } 1777 1778 // Figure out the funclet membership for the catchret's successor. 1779 // This will be used by the FuncletLayout pass to determine how to order the 1780 // BB's. 1781 // A 'catchret' returns to the outer scope's color. 1782 Value *ParentPad = I.getCatchSwitchParentPad(); 1783 const BasicBlock *SuccessorColor; 1784 if (isa<ConstantTokenNone>(ParentPad)) 1785 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1786 else 1787 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1788 assert(SuccessorColor && "No parent funclet for catchret!"); 1789 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1790 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1791 1792 // Create the terminator node. 1793 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1794 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1795 DAG.getBasicBlock(SuccessorColorMBB)); 1796 DAG.setRoot(Ret); 1797 } 1798 1799 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1800 // Don't emit any special code for the cleanuppad instruction. It just marks 1801 // the start of an EH scope/funclet. 1802 FuncInfo.MBB->setIsEHScopeEntry(); 1803 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1804 if (Pers != EHPersonality::Wasm_CXX) { 1805 FuncInfo.MBB->setIsEHFuncletEntry(); 1806 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1807 } 1808 } 1809 1810 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1811 // not match, it is OK to add only the first unwind destination catchpad to the 1812 // successors, because there will be at least one invoke instruction within the 1813 // catch scope that points to the next unwind destination, if one exists, so 1814 // CFGSort cannot mess up with BB sorting order. 1815 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1816 // call within them, and catchpads only consisting of 'catch (...)' have a 1817 // '__cxa_end_catch' call within them, both of which generate invokes in case 1818 // the next unwind destination exists, i.e., the next unwind destination is not 1819 // the caller.) 1820 // 1821 // Having at most one EH pad successor is also simpler and helps later 1822 // transformations. 1823 // 1824 // For example, 1825 // current: 1826 // invoke void @foo to ... unwind label %catch.dispatch 1827 // catch.dispatch: 1828 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1829 // catch.start: 1830 // ... 1831 // ... in this BB or some other child BB dominated by this BB there will be an 1832 // invoke that points to 'next' BB as an unwind destination 1833 // 1834 // next: ; We don't need to add this to 'current' BB's successor 1835 // ... 1836 static void findWasmUnwindDestinations( 1837 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1838 BranchProbability Prob, 1839 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1840 &UnwindDests) { 1841 while (EHPadBB) { 1842 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1843 if (isa<CleanupPadInst>(Pad)) { 1844 // Stop on cleanup pads. 1845 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1846 UnwindDests.back().first->setIsEHScopeEntry(); 1847 break; 1848 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1849 // Add the catchpad handlers to the possible destinations. We don't 1850 // continue to the unwind destination of the catchswitch for wasm. 1851 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1852 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1853 UnwindDests.back().first->setIsEHScopeEntry(); 1854 } 1855 break; 1856 } else { 1857 continue; 1858 } 1859 } 1860 } 1861 1862 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1863 /// many places it could ultimately go. In the IR, we have a single unwind 1864 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1865 /// This function skips over imaginary basic blocks that hold catchswitch 1866 /// instructions, and finds all the "real" machine 1867 /// basic block destinations. As those destinations may not be successors of 1868 /// EHPadBB, here we also calculate the edge probability to those destinations. 1869 /// The passed-in Prob is the edge probability to EHPadBB. 1870 static void findUnwindDestinations( 1871 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1872 BranchProbability Prob, 1873 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1874 &UnwindDests) { 1875 EHPersonality Personality = 1876 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1877 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1878 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1879 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1880 bool IsSEH = isAsynchronousEHPersonality(Personality); 1881 1882 if (IsWasmCXX) { 1883 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1884 assert(UnwindDests.size() <= 1 && 1885 "There should be at most one unwind destination for wasm"); 1886 return; 1887 } 1888 1889 while (EHPadBB) { 1890 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1891 BasicBlock *NewEHPadBB = nullptr; 1892 if (isa<LandingPadInst>(Pad)) { 1893 // Stop on landingpads. They are not funclets. 1894 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1895 break; 1896 } else if (isa<CleanupPadInst>(Pad)) { 1897 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1898 // personalities. 1899 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1900 UnwindDests.back().first->setIsEHScopeEntry(); 1901 UnwindDests.back().first->setIsEHFuncletEntry(); 1902 break; 1903 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1904 // Add the catchpad handlers to the possible destinations. 1905 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1906 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1907 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1908 if (IsMSVCCXX || IsCoreCLR) 1909 UnwindDests.back().first->setIsEHFuncletEntry(); 1910 if (!IsSEH) 1911 UnwindDests.back().first->setIsEHScopeEntry(); 1912 } 1913 NewEHPadBB = CatchSwitch->getUnwindDest(); 1914 } else { 1915 continue; 1916 } 1917 1918 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1919 if (BPI && NewEHPadBB) 1920 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1921 EHPadBB = NewEHPadBB; 1922 } 1923 } 1924 1925 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1926 // Update successor info. 1927 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1928 auto UnwindDest = I.getUnwindDest(); 1929 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1930 BranchProbability UnwindDestProb = 1931 (BPI && UnwindDest) 1932 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1933 : BranchProbability::getZero(); 1934 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1935 for (auto &UnwindDest : UnwindDests) { 1936 UnwindDest.first->setIsEHPad(); 1937 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1938 } 1939 FuncInfo.MBB->normalizeSuccProbs(); 1940 1941 // Create the terminator node. 1942 SDValue Ret = 1943 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1944 DAG.setRoot(Ret); 1945 } 1946 1947 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1948 report_fatal_error("visitCatchSwitch not yet implemented!"); 1949 } 1950 1951 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1953 auto &DL = DAG.getDataLayout(); 1954 SDValue Chain = getControlRoot(); 1955 SmallVector<ISD::OutputArg, 8> Outs; 1956 SmallVector<SDValue, 8> OutVals; 1957 1958 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1959 // lower 1960 // 1961 // %val = call <ty> @llvm.experimental.deoptimize() 1962 // ret <ty> %val 1963 // 1964 // differently. 1965 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1966 LowerDeoptimizingReturn(); 1967 return; 1968 } 1969 1970 if (!FuncInfo.CanLowerReturn) { 1971 unsigned DemoteReg = FuncInfo.DemoteRegister; 1972 const Function *F = I.getParent()->getParent(); 1973 1974 // Emit a store of the return value through the virtual register. 1975 // Leave Outs empty so that LowerReturn won't try to load return 1976 // registers the usual way. 1977 SmallVector<EVT, 1> PtrValueVTs; 1978 ComputeValueVTs(TLI, DL, 1979 F->getReturnType()->getPointerTo( 1980 DAG.getDataLayout().getAllocaAddrSpace()), 1981 PtrValueVTs); 1982 1983 SDValue RetPtr = 1984 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 1985 SDValue RetOp = getValue(I.getOperand(0)); 1986 1987 SmallVector<EVT, 4> ValueVTs, MemVTs; 1988 SmallVector<uint64_t, 4> Offsets; 1989 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1990 &Offsets); 1991 unsigned NumValues = ValueVTs.size(); 1992 1993 SmallVector<SDValue, 4> Chains(NumValues); 1994 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1995 for (unsigned i = 0; i != NumValues; ++i) { 1996 // An aggregate return value cannot wrap around the address space, so 1997 // offsets to its parts don't wrap either. 1998 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1999 TypeSize::Fixed(Offsets[i])); 2000 2001 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2002 if (MemVTs[i] != ValueVTs[i]) 2003 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2004 Chains[i] = DAG.getStore( 2005 Chain, getCurSDLoc(), Val, 2006 // FIXME: better loc info would be nice. 2007 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2008 commonAlignment(BaseAlign, Offsets[i])); 2009 } 2010 2011 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2012 MVT::Other, Chains); 2013 } else if (I.getNumOperands() != 0) { 2014 SmallVector<EVT, 4> ValueVTs; 2015 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2016 unsigned NumValues = ValueVTs.size(); 2017 if (NumValues) { 2018 SDValue RetOp = getValue(I.getOperand(0)); 2019 2020 const Function *F = I.getParent()->getParent(); 2021 2022 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2023 I.getOperand(0)->getType(), F->getCallingConv(), 2024 /*IsVarArg*/ false, DL); 2025 2026 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2027 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2028 ExtendKind = ISD::SIGN_EXTEND; 2029 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2030 ExtendKind = ISD::ZERO_EXTEND; 2031 2032 LLVMContext &Context = F->getContext(); 2033 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2034 2035 for (unsigned j = 0; j != NumValues; ++j) { 2036 EVT VT = ValueVTs[j]; 2037 2038 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2039 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2040 2041 CallingConv::ID CC = F->getCallingConv(); 2042 2043 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2044 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2045 SmallVector<SDValue, 4> Parts(NumParts); 2046 getCopyToParts(DAG, getCurSDLoc(), 2047 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2048 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2049 2050 // 'inreg' on function refers to return value 2051 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2052 if (RetInReg) 2053 Flags.setInReg(); 2054 2055 if (I.getOperand(0)->getType()->isPointerTy()) { 2056 Flags.setPointer(); 2057 Flags.setPointerAddrSpace( 2058 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2059 } 2060 2061 if (NeedsRegBlock) { 2062 Flags.setInConsecutiveRegs(); 2063 if (j == NumValues - 1) 2064 Flags.setInConsecutiveRegsLast(); 2065 } 2066 2067 // Propagate extension type if any 2068 if (ExtendKind == ISD::SIGN_EXTEND) 2069 Flags.setSExt(); 2070 else if (ExtendKind == ISD::ZERO_EXTEND) 2071 Flags.setZExt(); 2072 2073 for (unsigned i = 0; i < NumParts; ++i) { 2074 Outs.push_back(ISD::OutputArg(Flags, 2075 Parts[i].getValueType().getSimpleVT(), 2076 VT, /*isfixed=*/true, 0, 0)); 2077 OutVals.push_back(Parts[i]); 2078 } 2079 } 2080 } 2081 } 2082 2083 // Push in swifterror virtual register as the last element of Outs. This makes 2084 // sure swifterror virtual register will be returned in the swifterror 2085 // physical register. 2086 const Function *F = I.getParent()->getParent(); 2087 if (TLI.supportSwiftError() && 2088 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2089 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2090 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2091 Flags.setSwiftError(); 2092 Outs.push_back(ISD::OutputArg( 2093 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2094 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2095 // Create SDNode for the swifterror virtual register. 2096 OutVals.push_back( 2097 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2098 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2099 EVT(TLI.getPointerTy(DL)))); 2100 } 2101 2102 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2103 CallingConv::ID CallConv = 2104 DAG.getMachineFunction().getFunction().getCallingConv(); 2105 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2106 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2107 2108 // Verify that the target's LowerReturn behaved as expected. 2109 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2110 "LowerReturn didn't return a valid chain!"); 2111 2112 // Update the DAG with the new chain value resulting from return lowering. 2113 DAG.setRoot(Chain); 2114 } 2115 2116 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2117 /// created for it, emit nodes to copy the value into the virtual 2118 /// registers. 2119 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2120 // Skip empty types 2121 if (V->getType()->isEmptyTy()) 2122 return; 2123 2124 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2125 if (VMI != FuncInfo.ValueMap.end()) { 2126 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 2127 CopyValueToVirtualRegister(V, VMI->second); 2128 } 2129 } 2130 2131 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2132 /// the current basic block, add it to ValueMap now so that we'll get a 2133 /// CopyTo/FromReg. 2134 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2135 // No need to export constants. 2136 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2137 2138 // Already exported? 2139 if (FuncInfo.isExportedInst(V)) return; 2140 2141 Register Reg = FuncInfo.InitializeRegForValue(V); 2142 CopyValueToVirtualRegister(V, Reg); 2143 } 2144 2145 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2146 const BasicBlock *FromBB) { 2147 // The operands of the setcc have to be in this block. We don't know 2148 // how to export them from some other block. 2149 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2150 // Can export from current BB. 2151 if (VI->getParent() == FromBB) 2152 return true; 2153 2154 // Is already exported, noop. 2155 return FuncInfo.isExportedInst(V); 2156 } 2157 2158 // If this is an argument, we can export it if the BB is the entry block or 2159 // if it is already exported. 2160 if (isa<Argument>(V)) { 2161 if (FromBB->isEntryBlock()) 2162 return true; 2163 2164 // Otherwise, can only export this if it is already exported. 2165 return FuncInfo.isExportedInst(V); 2166 } 2167 2168 // Otherwise, constants can always be exported. 2169 return true; 2170 } 2171 2172 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2173 BranchProbability 2174 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2175 const MachineBasicBlock *Dst) const { 2176 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2177 const BasicBlock *SrcBB = Src->getBasicBlock(); 2178 const BasicBlock *DstBB = Dst->getBasicBlock(); 2179 if (!BPI) { 2180 // If BPI is not available, set the default probability as 1 / N, where N is 2181 // the number of successors. 2182 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2183 return BranchProbability(1, SuccSize); 2184 } 2185 return BPI->getEdgeProbability(SrcBB, DstBB); 2186 } 2187 2188 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2189 MachineBasicBlock *Dst, 2190 BranchProbability Prob) { 2191 if (!FuncInfo.BPI) 2192 Src->addSuccessorWithoutProb(Dst); 2193 else { 2194 if (Prob.isUnknown()) 2195 Prob = getEdgeProbability(Src, Dst); 2196 Src->addSuccessor(Dst, Prob); 2197 } 2198 } 2199 2200 static bool InBlock(const Value *V, const BasicBlock *BB) { 2201 if (const Instruction *I = dyn_cast<Instruction>(V)) 2202 return I->getParent() == BB; 2203 return true; 2204 } 2205 2206 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2207 /// This function emits a branch and is used at the leaves of an OR or an 2208 /// AND operator tree. 2209 void 2210 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2211 MachineBasicBlock *TBB, 2212 MachineBasicBlock *FBB, 2213 MachineBasicBlock *CurBB, 2214 MachineBasicBlock *SwitchBB, 2215 BranchProbability TProb, 2216 BranchProbability FProb, 2217 bool InvertCond) { 2218 const BasicBlock *BB = CurBB->getBasicBlock(); 2219 2220 // If the leaf of the tree is a comparison, merge the condition into 2221 // the caseblock. 2222 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2223 // The operands of the cmp have to be in this block. We don't know 2224 // how to export them from some other block. If this is the first block 2225 // of the sequence, no exporting is needed. 2226 if (CurBB == SwitchBB || 2227 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2228 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2229 ISD::CondCode Condition; 2230 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2231 ICmpInst::Predicate Pred = 2232 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2233 Condition = getICmpCondCode(Pred); 2234 } else { 2235 const FCmpInst *FC = cast<FCmpInst>(Cond); 2236 FCmpInst::Predicate Pred = 2237 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2238 Condition = getFCmpCondCode(Pred); 2239 if (TM.Options.NoNaNsFPMath) 2240 Condition = getFCmpCodeWithoutNaN(Condition); 2241 } 2242 2243 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2244 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2245 SL->SwitchCases.push_back(CB); 2246 return; 2247 } 2248 } 2249 2250 // Create a CaseBlock record representing this branch. 2251 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2252 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2253 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2254 SL->SwitchCases.push_back(CB); 2255 } 2256 2257 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2258 MachineBasicBlock *TBB, 2259 MachineBasicBlock *FBB, 2260 MachineBasicBlock *CurBB, 2261 MachineBasicBlock *SwitchBB, 2262 Instruction::BinaryOps Opc, 2263 BranchProbability TProb, 2264 BranchProbability FProb, 2265 bool InvertCond) { 2266 // Skip over not part of the tree and remember to invert op and operands at 2267 // next level. 2268 Value *NotCond; 2269 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2270 InBlock(NotCond, CurBB->getBasicBlock())) { 2271 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2272 !InvertCond); 2273 return; 2274 } 2275 2276 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2277 const Value *BOpOp0, *BOpOp1; 2278 // Compute the effective opcode for Cond, taking into account whether it needs 2279 // to be inverted, e.g. 2280 // and (not (or A, B)), C 2281 // gets lowered as 2282 // and (and (not A, not B), C) 2283 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2284 if (BOp) { 2285 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2286 ? Instruction::And 2287 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2288 ? Instruction::Or 2289 : (Instruction::BinaryOps)0); 2290 if (InvertCond) { 2291 if (BOpc == Instruction::And) 2292 BOpc = Instruction::Or; 2293 else if (BOpc == Instruction::Or) 2294 BOpc = Instruction::And; 2295 } 2296 } 2297 2298 // If this node is not part of the or/and tree, emit it as a branch. 2299 // Note that all nodes in the tree should have same opcode. 2300 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2301 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2302 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2303 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2304 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2305 TProb, FProb, InvertCond); 2306 return; 2307 } 2308 2309 // Create TmpBB after CurBB. 2310 MachineFunction::iterator BBI(CurBB); 2311 MachineFunction &MF = DAG.getMachineFunction(); 2312 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2313 CurBB->getParent()->insert(++BBI, TmpBB); 2314 2315 if (Opc == Instruction::Or) { 2316 // Codegen X | Y as: 2317 // BB1: 2318 // jmp_if_X TBB 2319 // jmp TmpBB 2320 // TmpBB: 2321 // jmp_if_Y TBB 2322 // jmp FBB 2323 // 2324 2325 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2326 // The requirement is that 2327 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2328 // = TrueProb for original BB. 2329 // Assuming the original probabilities are A and B, one choice is to set 2330 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2331 // A/(1+B) and 2B/(1+B). This choice assumes that 2332 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2333 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2334 // TmpBB, but the math is more complicated. 2335 2336 auto NewTrueProb = TProb / 2; 2337 auto NewFalseProb = TProb / 2 + FProb; 2338 // Emit the LHS condition. 2339 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2340 NewFalseProb, InvertCond); 2341 2342 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2343 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2344 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2345 // Emit the RHS condition into TmpBB. 2346 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2347 Probs[1], InvertCond); 2348 } else { 2349 assert(Opc == Instruction::And && "Unknown merge op!"); 2350 // Codegen X & Y as: 2351 // BB1: 2352 // jmp_if_X TmpBB 2353 // jmp FBB 2354 // TmpBB: 2355 // jmp_if_Y TBB 2356 // jmp FBB 2357 // 2358 // This requires creation of TmpBB after CurBB. 2359 2360 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2361 // The requirement is that 2362 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2363 // = FalseProb for original BB. 2364 // Assuming the original probabilities are A and B, one choice is to set 2365 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2366 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2367 // TrueProb for BB1 * FalseProb for TmpBB. 2368 2369 auto NewTrueProb = TProb + FProb / 2; 2370 auto NewFalseProb = FProb / 2; 2371 // Emit the LHS condition. 2372 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2373 NewFalseProb, InvertCond); 2374 2375 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2376 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2377 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2378 // Emit the RHS condition into TmpBB. 2379 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2380 Probs[1], InvertCond); 2381 } 2382 } 2383 2384 /// If the set of cases should be emitted as a series of branches, return true. 2385 /// If we should emit this as a bunch of and/or'd together conditions, return 2386 /// false. 2387 bool 2388 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2389 if (Cases.size() != 2) return true; 2390 2391 // If this is two comparisons of the same values or'd or and'd together, they 2392 // will get folded into a single comparison, so don't emit two blocks. 2393 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2394 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2395 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2396 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2397 return false; 2398 } 2399 2400 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2401 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2402 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2403 Cases[0].CC == Cases[1].CC && 2404 isa<Constant>(Cases[0].CmpRHS) && 2405 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2406 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2407 return false; 2408 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2409 return false; 2410 } 2411 2412 return true; 2413 } 2414 2415 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2416 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2417 2418 // Update machine-CFG edges. 2419 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2420 2421 if (I.isUnconditional()) { 2422 // Update machine-CFG edges. 2423 BrMBB->addSuccessor(Succ0MBB); 2424 2425 // If this is not a fall-through branch or optimizations are switched off, 2426 // emit the branch. 2427 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2428 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2429 MVT::Other, getControlRoot(), 2430 DAG.getBasicBlock(Succ0MBB))); 2431 2432 return; 2433 } 2434 2435 // If this condition is one of the special cases we handle, do special stuff 2436 // now. 2437 const Value *CondVal = I.getCondition(); 2438 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2439 2440 // If this is a series of conditions that are or'd or and'd together, emit 2441 // this as a sequence of branches instead of setcc's with and/or operations. 2442 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2443 // unpredictable branches, and vector extracts because those jumps are likely 2444 // expensive for any target), this should improve performance. 2445 // For example, instead of something like: 2446 // cmp A, B 2447 // C = seteq 2448 // cmp D, E 2449 // F = setle 2450 // or C, F 2451 // jnz foo 2452 // Emit: 2453 // cmp A, B 2454 // je foo 2455 // cmp D, E 2456 // jle foo 2457 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2458 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2459 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2460 Value *Vec; 2461 const Value *BOp0, *BOp1; 2462 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2463 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2464 Opcode = Instruction::And; 2465 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2466 Opcode = Instruction::Or; 2467 2468 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2469 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2470 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2471 getEdgeProbability(BrMBB, Succ0MBB), 2472 getEdgeProbability(BrMBB, Succ1MBB), 2473 /*InvertCond=*/false); 2474 // If the compares in later blocks need to use values not currently 2475 // exported from this block, export them now. This block should always 2476 // be the first entry. 2477 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2478 2479 // Allow some cases to be rejected. 2480 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2481 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2482 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2483 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2484 } 2485 2486 // Emit the branch for this block. 2487 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2488 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2489 return; 2490 } 2491 2492 // Okay, we decided not to do this, remove any inserted MBB's and clear 2493 // SwitchCases. 2494 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2495 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2496 2497 SL->SwitchCases.clear(); 2498 } 2499 } 2500 2501 // Create a CaseBlock record representing this branch. 2502 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2503 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2504 2505 // Use visitSwitchCase to actually insert the fast branch sequence for this 2506 // cond branch. 2507 visitSwitchCase(CB, BrMBB); 2508 } 2509 2510 /// visitSwitchCase - Emits the necessary code to represent a single node in 2511 /// the binary search tree resulting from lowering a switch instruction. 2512 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2513 MachineBasicBlock *SwitchBB) { 2514 SDValue Cond; 2515 SDValue CondLHS = getValue(CB.CmpLHS); 2516 SDLoc dl = CB.DL; 2517 2518 if (CB.CC == ISD::SETTRUE) { 2519 // Branch or fall through to TrueBB. 2520 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2521 SwitchBB->normalizeSuccProbs(); 2522 if (CB.TrueBB != NextBlock(SwitchBB)) { 2523 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2524 DAG.getBasicBlock(CB.TrueBB))); 2525 } 2526 return; 2527 } 2528 2529 auto &TLI = DAG.getTargetLoweringInfo(); 2530 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2531 2532 // Build the setcc now. 2533 if (!CB.CmpMHS) { 2534 // Fold "(X == true)" to X and "(X == false)" to !X to 2535 // handle common cases produced by branch lowering. 2536 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2537 CB.CC == ISD::SETEQ) 2538 Cond = CondLHS; 2539 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2540 CB.CC == ISD::SETEQ) { 2541 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2542 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2543 } else { 2544 SDValue CondRHS = getValue(CB.CmpRHS); 2545 2546 // If a pointer's DAG type is larger than its memory type then the DAG 2547 // values are zero-extended. This breaks signed comparisons so truncate 2548 // back to the underlying type before doing the compare. 2549 if (CondLHS.getValueType() != MemVT) { 2550 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2551 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2552 } 2553 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2554 } 2555 } else { 2556 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2557 2558 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2559 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2560 2561 SDValue CmpOp = getValue(CB.CmpMHS); 2562 EVT VT = CmpOp.getValueType(); 2563 2564 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2565 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2566 ISD::SETLE); 2567 } else { 2568 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2569 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2570 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2571 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2572 } 2573 } 2574 2575 // Update successor info 2576 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2577 // TrueBB and FalseBB are always different unless the incoming IR is 2578 // degenerate. This only happens when running llc on weird IR. 2579 if (CB.TrueBB != CB.FalseBB) 2580 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2581 SwitchBB->normalizeSuccProbs(); 2582 2583 // If the lhs block is the next block, invert the condition so that we can 2584 // fall through to the lhs instead of the rhs block. 2585 if (CB.TrueBB == NextBlock(SwitchBB)) { 2586 std::swap(CB.TrueBB, CB.FalseBB); 2587 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2588 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2589 } 2590 2591 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2592 MVT::Other, getControlRoot(), Cond, 2593 DAG.getBasicBlock(CB.TrueBB)); 2594 2595 setValue(CurInst, BrCond); 2596 2597 // Insert the false branch. Do this even if it's a fall through branch, 2598 // this makes it easier to do DAG optimizations which require inverting 2599 // the branch condition. 2600 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2601 DAG.getBasicBlock(CB.FalseBB)); 2602 2603 DAG.setRoot(BrCond); 2604 } 2605 2606 /// visitJumpTable - Emit JumpTable node in the current MBB 2607 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2608 // Emit the code for the jump table 2609 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2610 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2611 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2612 JT.Reg, PTy); 2613 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2614 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2615 MVT::Other, Index.getValue(1), 2616 Table, Index); 2617 DAG.setRoot(BrJumpTable); 2618 } 2619 2620 /// visitJumpTableHeader - This function emits necessary code to produce index 2621 /// in the JumpTable from switch case. 2622 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2623 JumpTableHeader &JTH, 2624 MachineBasicBlock *SwitchBB) { 2625 SDLoc dl = getCurSDLoc(); 2626 2627 // Subtract the lowest switch case value from the value being switched on. 2628 SDValue SwitchOp = getValue(JTH.SValue); 2629 EVT VT = SwitchOp.getValueType(); 2630 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2631 DAG.getConstant(JTH.First, dl, VT)); 2632 2633 // The SDNode we just created, which holds the value being switched on minus 2634 // the smallest case value, needs to be copied to a virtual register so it 2635 // can be used as an index into the jump table in a subsequent basic block. 2636 // This value may be smaller or larger than the target's pointer type, and 2637 // therefore require extension or truncating. 2638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2639 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2640 2641 unsigned JumpTableReg = 2642 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2643 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2644 JumpTableReg, SwitchOp); 2645 JT.Reg = JumpTableReg; 2646 2647 if (!JTH.FallthroughUnreachable) { 2648 // Emit the range check for the jump table, and branch to the default block 2649 // for the switch statement if the value being switched on exceeds the 2650 // largest case in the switch. 2651 SDValue CMP = DAG.getSetCC( 2652 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2653 Sub.getValueType()), 2654 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2655 2656 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2657 MVT::Other, CopyTo, CMP, 2658 DAG.getBasicBlock(JT.Default)); 2659 2660 // Avoid emitting unnecessary branches to the next block. 2661 if (JT.MBB != NextBlock(SwitchBB)) 2662 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2663 DAG.getBasicBlock(JT.MBB)); 2664 2665 DAG.setRoot(BrCond); 2666 } else { 2667 // Avoid emitting unnecessary branches to the next block. 2668 if (JT.MBB != NextBlock(SwitchBB)) 2669 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2670 DAG.getBasicBlock(JT.MBB))); 2671 else 2672 DAG.setRoot(CopyTo); 2673 } 2674 } 2675 2676 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2677 /// variable if there exists one. 2678 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2679 SDValue &Chain) { 2680 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2681 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2682 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2683 MachineFunction &MF = DAG.getMachineFunction(); 2684 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2685 MachineSDNode *Node = 2686 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2687 if (Global) { 2688 MachinePointerInfo MPInfo(Global); 2689 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2690 MachineMemOperand::MODereferenceable; 2691 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2692 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2693 DAG.setNodeMemRefs(Node, {MemRef}); 2694 } 2695 if (PtrTy != PtrMemTy) 2696 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2697 return SDValue(Node, 0); 2698 } 2699 2700 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2701 /// tail spliced into a stack protector check success bb. 2702 /// 2703 /// For a high level explanation of how this fits into the stack protector 2704 /// generation see the comment on the declaration of class 2705 /// StackProtectorDescriptor. 2706 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2707 MachineBasicBlock *ParentBB) { 2708 2709 // First create the loads to the guard/stack slot for the comparison. 2710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2711 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2712 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2713 2714 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2715 int FI = MFI.getStackProtectorIndex(); 2716 2717 SDValue Guard; 2718 SDLoc dl = getCurSDLoc(); 2719 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2720 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2721 Align Align = 2722 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2723 2724 // Generate code to load the content of the guard slot. 2725 SDValue GuardVal = DAG.getLoad( 2726 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2727 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2728 MachineMemOperand::MOVolatile); 2729 2730 if (TLI.useStackGuardXorFP()) 2731 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2732 2733 // Retrieve guard check function, nullptr if instrumentation is inlined. 2734 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2735 // The target provides a guard check function to validate the guard value. 2736 // Generate a call to that function with the content of the guard slot as 2737 // argument. 2738 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2739 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2740 2741 TargetLowering::ArgListTy Args; 2742 TargetLowering::ArgListEntry Entry; 2743 Entry.Node = GuardVal; 2744 Entry.Ty = FnTy->getParamType(0); 2745 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2746 Entry.IsInReg = true; 2747 Args.push_back(Entry); 2748 2749 TargetLowering::CallLoweringInfo CLI(DAG); 2750 CLI.setDebugLoc(getCurSDLoc()) 2751 .setChain(DAG.getEntryNode()) 2752 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2753 getValue(GuardCheckFn), std::move(Args)); 2754 2755 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2756 DAG.setRoot(Result.second); 2757 return; 2758 } 2759 2760 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2761 // Otherwise, emit a volatile load to retrieve the stack guard value. 2762 SDValue Chain = DAG.getEntryNode(); 2763 if (TLI.useLoadStackGuardNode()) { 2764 Guard = getLoadStackGuard(DAG, dl, Chain); 2765 } else { 2766 const Value *IRGuard = TLI.getSDagStackGuard(M); 2767 SDValue GuardPtr = getValue(IRGuard); 2768 2769 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2770 MachinePointerInfo(IRGuard, 0), Align, 2771 MachineMemOperand::MOVolatile); 2772 } 2773 2774 // Perform the comparison via a getsetcc. 2775 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2776 *DAG.getContext(), 2777 Guard.getValueType()), 2778 Guard, GuardVal, ISD::SETNE); 2779 2780 // If the guard/stackslot do not equal, branch to failure MBB. 2781 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2782 MVT::Other, GuardVal.getOperand(0), 2783 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2784 // Otherwise branch to success MBB. 2785 SDValue Br = DAG.getNode(ISD::BR, dl, 2786 MVT::Other, BrCond, 2787 DAG.getBasicBlock(SPD.getSuccessMBB())); 2788 2789 DAG.setRoot(Br); 2790 } 2791 2792 /// Codegen the failure basic block for a stack protector check. 2793 /// 2794 /// A failure stack protector machine basic block consists simply of a call to 2795 /// __stack_chk_fail(). 2796 /// 2797 /// For a high level explanation of how this fits into the stack protector 2798 /// generation see the comment on the declaration of class 2799 /// StackProtectorDescriptor. 2800 void 2801 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2802 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2803 TargetLowering::MakeLibCallOptions CallOptions; 2804 CallOptions.setDiscardResult(true); 2805 SDValue Chain = 2806 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2807 std::nullopt, CallOptions, getCurSDLoc()) 2808 .second; 2809 // On PS4/PS5, the "return address" must still be within the calling 2810 // function, even if it's at the very end, so emit an explicit TRAP here. 2811 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2812 if (TM.getTargetTriple().isPS()) 2813 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2814 // WebAssembly needs an unreachable instruction after a non-returning call, 2815 // because the function return type can be different from __stack_chk_fail's 2816 // return type (void). 2817 if (TM.getTargetTriple().isWasm()) 2818 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2819 2820 DAG.setRoot(Chain); 2821 } 2822 2823 /// visitBitTestHeader - This function emits necessary code to produce value 2824 /// suitable for "bit tests" 2825 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2826 MachineBasicBlock *SwitchBB) { 2827 SDLoc dl = getCurSDLoc(); 2828 2829 // Subtract the minimum value. 2830 SDValue SwitchOp = getValue(B.SValue); 2831 EVT VT = SwitchOp.getValueType(); 2832 SDValue RangeSub = 2833 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2834 2835 // Determine the type of the test operands. 2836 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2837 bool UsePtrType = false; 2838 if (!TLI.isTypeLegal(VT)) { 2839 UsePtrType = true; 2840 } else { 2841 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2842 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2843 // Switch table case range are encoded into series of masks. 2844 // Just use pointer type, it's guaranteed to fit. 2845 UsePtrType = true; 2846 break; 2847 } 2848 } 2849 SDValue Sub = RangeSub; 2850 if (UsePtrType) { 2851 VT = TLI.getPointerTy(DAG.getDataLayout()); 2852 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2853 } 2854 2855 B.RegVT = VT.getSimpleVT(); 2856 B.Reg = FuncInfo.CreateReg(B.RegVT); 2857 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2858 2859 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2860 2861 if (!B.FallthroughUnreachable) 2862 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2863 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2864 SwitchBB->normalizeSuccProbs(); 2865 2866 SDValue Root = CopyTo; 2867 if (!B.FallthroughUnreachable) { 2868 // Conditional branch to the default block. 2869 SDValue RangeCmp = DAG.getSetCC(dl, 2870 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2871 RangeSub.getValueType()), 2872 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2873 ISD::SETUGT); 2874 2875 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2876 DAG.getBasicBlock(B.Default)); 2877 } 2878 2879 // Avoid emitting unnecessary branches to the next block. 2880 if (MBB != NextBlock(SwitchBB)) 2881 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2882 2883 DAG.setRoot(Root); 2884 } 2885 2886 /// visitBitTestCase - this function produces one "bit test" 2887 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2888 MachineBasicBlock* NextMBB, 2889 BranchProbability BranchProbToNext, 2890 unsigned Reg, 2891 BitTestCase &B, 2892 MachineBasicBlock *SwitchBB) { 2893 SDLoc dl = getCurSDLoc(); 2894 MVT VT = BB.RegVT; 2895 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2896 SDValue Cmp; 2897 unsigned PopCount = llvm::popcount(B.Mask); 2898 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2899 if (PopCount == 1) { 2900 // Testing for a single bit; just compare the shift count with what it 2901 // would need to be to shift a 1 bit in that position. 2902 Cmp = DAG.getSetCC( 2903 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2904 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2905 ISD::SETEQ); 2906 } else if (PopCount == BB.Range) { 2907 // There is only one zero bit in the range, test for it directly. 2908 Cmp = DAG.getSetCC( 2909 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2910 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2911 } else { 2912 // Make desired shift 2913 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2914 DAG.getConstant(1, dl, VT), ShiftOp); 2915 2916 // Emit bit tests and jumps 2917 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2918 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2919 Cmp = DAG.getSetCC( 2920 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2921 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2922 } 2923 2924 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2925 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2926 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2927 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2928 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2929 // one as they are relative probabilities (and thus work more like weights), 2930 // and hence we need to normalize them to let the sum of them become one. 2931 SwitchBB->normalizeSuccProbs(); 2932 2933 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2934 MVT::Other, getControlRoot(), 2935 Cmp, DAG.getBasicBlock(B.TargetBB)); 2936 2937 // Avoid emitting unnecessary branches to the next block. 2938 if (NextMBB != NextBlock(SwitchBB)) 2939 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2940 DAG.getBasicBlock(NextMBB)); 2941 2942 DAG.setRoot(BrAnd); 2943 } 2944 2945 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2946 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2947 2948 // Retrieve successors. Look through artificial IR level blocks like 2949 // catchswitch for successors. 2950 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2951 const BasicBlock *EHPadBB = I.getSuccessor(1); 2952 2953 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2954 // have to do anything here to lower funclet bundles. 2955 assert(!I.hasOperandBundlesOtherThan( 2956 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 2957 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 2958 LLVMContext::OB_cfguardtarget, 2959 LLVMContext::OB_clang_arc_attachedcall}) && 2960 "Cannot lower invokes with arbitrary operand bundles yet!"); 2961 2962 const Value *Callee(I.getCalledOperand()); 2963 const Function *Fn = dyn_cast<Function>(Callee); 2964 if (isa<InlineAsm>(Callee)) 2965 visitInlineAsm(I, EHPadBB); 2966 else if (Fn && Fn->isIntrinsic()) { 2967 switch (Fn->getIntrinsicID()) { 2968 default: 2969 llvm_unreachable("Cannot invoke this intrinsic"); 2970 case Intrinsic::donothing: 2971 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2972 case Intrinsic::seh_try_begin: 2973 case Intrinsic::seh_scope_begin: 2974 case Intrinsic::seh_try_end: 2975 case Intrinsic::seh_scope_end: 2976 break; 2977 case Intrinsic::experimental_patchpoint_void: 2978 case Intrinsic::experimental_patchpoint_i64: 2979 visitPatchpoint(I, EHPadBB); 2980 break; 2981 case Intrinsic::experimental_gc_statepoint: 2982 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2983 break; 2984 case Intrinsic::wasm_rethrow: { 2985 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2986 // special because it can be invoked, so we manually lower it to a DAG 2987 // node here. 2988 SmallVector<SDValue, 8> Ops; 2989 Ops.push_back(getRoot()); // inchain 2990 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2991 Ops.push_back( 2992 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2993 TLI.getPointerTy(DAG.getDataLayout()))); 2994 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2995 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2996 break; 2997 } 2998 } 2999 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3000 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3001 // Eventually we will support lowering the @llvm.experimental.deoptimize 3002 // intrinsic, and right now there are no plans to support other intrinsics 3003 // with deopt state. 3004 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3005 } else { 3006 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3007 } 3008 3009 // If the value of the invoke is used outside of its defining block, make it 3010 // available as a virtual register. 3011 // We already took care of the exported value for the statepoint instruction 3012 // during call to the LowerStatepoint. 3013 if (!isa<GCStatepointInst>(I)) { 3014 CopyToExportRegsIfNeeded(&I); 3015 } 3016 3017 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3018 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3019 BranchProbability EHPadBBProb = 3020 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3021 : BranchProbability::getZero(); 3022 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3023 3024 // Update successor info. 3025 addSuccessorWithProb(InvokeMBB, Return); 3026 for (auto &UnwindDest : UnwindDests) { 3027 UnwindDest.first->setIsEHPad(); 3028 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3029 } 3030 InvokeMBB->normalizeSuccProbs(); 3031 3032 // Drop into normal successor. 3033 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3034 DAG.getBasicBlock(Return))); 3035 } 3036 3037 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3038 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3039 3040 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3041 // have to do anything here to lower funclet bundles. 3042 assert(!I.hasOperandBundlesOtherThan( 3043 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3044 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3045 3046 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3047 visitInlineAsm(I); 3048 CopyToExportRegsIfNeeded(&I); 3049 3050 // Retrieve successors. 3051 SmallPtrSet<BasicBlock *, 8> Dests; 3052 Dests.insert(I.getDefaultDest()); 3053 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3054 3055 // Update successor info. 3056 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3057 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3058 BasicBlock *Dest = I.getIndirectDest(i); 3059 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3060 Target->setIsInlineAsmBrIndirectTarget(); 3061 Target->setMachineBlockAddressTaken(); 3062 Target->setLabelMustBeEmitted(); 3063 // Don't add duplicate machine successors. 3064 if (Dests.insert(Dest).second) 3065 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3066 } 3067 CallBrMBB->normalizeSuccProbs(); 3068 3069 // Drop into default successor. 3070 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3071 MVT::Other, getControlRoot(), 3072 DAG.getBasicBlock(Return))); 3073 } 3074 3075 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3076 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3077 } 3078 3079 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3080 assert(FuncInfo.MBB->isEHPad() && 3081 "Call to landingpad not in landing pad!"); 3082 3083 // If there aren't registers to copy the values into (e.g., during SjLj 3084 // exceptions), then don't bother to create these DAG nodes. 3085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3086 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3087 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3088 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3089 return; 3090 3091 // If landingpad's return type is token type, we don't create DAG nodes 3092 // for its exception pointer and selector value. The extraction of exception 3093 // pointer or selector value from token type landingpads is not currently 3094 // supported. 3095 if (LP.getType()->isTokenTy()) 3096 return; 3097 3098 SmallVector<EVT, 2> ValueVTs; 3099 SDLoc dl = getCurSDLoc(); 3100 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3101 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3102 3103 // Get the two live-in registers as SDValues. The physregs have already been 3104 // copied into virtual registers. 3105 SDValue Ops[2]; 3106 if (FuncInfo.ExceptionPointerVirtReg) { 3107 Ops[0] = DAG.getZExtOrTrunc( 3108 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3109 FuncInfo.ExceptionPointerVirtReg, 3110 TLI.getPointerTy(DAG.getDataLayout())), 3111 dl, ValueVTs[0]); 3112 } else { 3113 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3114 } 3115 Ops[1] = DAG.getZExtOrTrunc( 3116 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3117 FuncInfo.ExceptionSelectorVirtReg, 3118 TLI.getPointerTy(DAG.getDataLayout())), 3119 dl, ValueVTs[1]); 3120 3121 // Merge into one. 3122 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3123 DAG.getVTList(ValueVTs), Ops); 3124 setValue(&LP, Res); 3125 } 3126 3127 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3128 MachineBasicBlock *Last) { 3129 // Update JTCases. 3130 for (JumpTableBlock &JTB : SL->JTCases) 3131 if (JTB.first.HeaderBB == First) 3132 JTB.first.HeaderBB = Last; 3133 3134 // Update BitTestCases. 3135 for (BitTestBlock &BTB : SL->BitTestCases) 3136 if (BTB.Parent == First) 3137 BTB.Parent = Last; 3138 } 3139 3140 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3141 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3142 3143 // Update machine-CFG edges with unique successors. 3144 SmallSet<BasicBlock*, 32> Done; 3145 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3146 BasicBlock *BB = I.getSuccessor(i); 3147 bool Inserted = Done.insert(BB).second; 3148 if (!Inserted) 3149 continue; 3150 3151 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3152 addSuccessorWithProb(IndirectBrMBB, Succ); 3153 } 3154 IndirectBrMBB->normalizeSuccProbs(); 3155 3156 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3157 MVT::Other, getControlRoot(), 3158 getValue(I.getAddress()))); 3159 } 3160 3161 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3162 if (!DAG.getTarget().Options.TrapUnreachable) 3163 return; 3164 3165 // We may be able to ignore unreachable behind a noreturn call. 3166 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3167 const BasicBlock &BB = *I.getParent(); 3168 if (&I != &BB.front()) { 3169 BasicBlock::const_iterator PredI = 3170 std::prev(BasicBlock::const_iterator(&I)); 3171 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3172 if (Call->doesNotReturn()) 3173 return; 3174 } 3175 } 3176 } 3177 3178 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3179 } 3180 3181 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3182 SDNodeFlags Flags; 3183 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3184 Flags.copyFMF(*FPOp); 3185 3186 SDValue Op = getValue(I.getOperand(0)); 3187 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3188 Op, Flags); 3189 setValue(&I, UnNodeValue); 3190 } 3191 3192 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3193 SDNodeFlags Flags; 3194 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3195 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3196 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3197 } 3198 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3199 Flags.setExact(ExactOp->isExact()); 3200 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3201 Flags.copyFMF(*FPOp); 3202 3203 SDValue Op1 = getValue(I.getOperand(0)); 3204 SDValue Op2 = getValue(I.getOperand(1)); 3205 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3206 Op1, Op2, Flags); 3207 setValue(&I, BinNodeValue); 3208 } 3209 3210 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3211 SDValue Op1 = getValue(I.getOperand(0)); 3212 SDValue Op2 = getValue(I.getOperand(1)); 3213 3214 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3215 Op1.getValueType(), DAG.getDataLayout()); 3216 3217 // Coerce the shift amount to the right type if we can. This exposes the 3218 // truncate or zext to optimization early. 3219 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3220 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3221 "Unexpected shift type"); 3222 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3223 } 3224 3225 bool nuw = false; 3226 bool nsw = false; 3227 bool exact = false; 3228 3229 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3230 3231 if (const OverflowingBinaryOperator *OFBinOp = 3232 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3233 nuw = OFBinOp->hasNoUnsignedWrap(); 3234 nsw = OFBinOp->hasNoSignedWrap(); 3235 } 3236 if (const PossiblyExactOperator *ExactOp = 3237 dyn_cast<const PossiblyExactOperator>(&I)) 3238 exact = ExactOp->isExact(); 3239 } 3240 SDNodeFlags Flags; 3241 Flags.setExact(exact); 3242 Flags.setNoSignedWrap(nsw); 3243 Flags.setNoUnsignedWrap(nuw); 3244 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3245 Flags); 3246 setValue(&I, Res); 3247 } 3248 3249 void SelectionDAGBuilder::visitSDiv(const User &I) { 3250 SDValue Op1 = getValue(I.getOperand(0)); 3251 SDValue Op2 = getValue(I.getOperand(1)); 3252 3253 SDNodeFlags Flags; 3254 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3255 cast<PossiblyExactOperator>(&I)->isExact()); 3256 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3257 Op2, Flags)); 3258 } 3259 3260 void SelectionDAGBuilder::visitICmp(const User &I) { 3261 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3262 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3263 predicate = IC->getPredicate(); 3264 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3265 predicate = ICmpInst::Predicate(IC->getPredicate()); 3266 SDValue Op1 = getValue(I.getOperand(0)); 3267 SDValue Op2 = getValue(I.getOperand(1)); 3268 ISD::CondCode Opcode = getICmpCondCode(predicate); 3269 3270 auto &TLI = DAG.getTargetLoweringInfo(); 3271 EVT MemVT = 3272 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3273 3274 // If a pointer's DAG type is larger than its memory type then the DAG values 3275 // are zero-extended. This breaks signed comparisons so truncate back to the 3276 // underlying type before doing the compare. 3277 if (Op1.getValueType() != MemVT) { 3278 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3279 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3280 } 3281 3282 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3283 I.getType()); 3284 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3285 } 3286 3287 void SelectionDAGBuilder::visitFCmp(const User &I) { 3288 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3289 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3290 predicate = FC->getPredicate(); 3291 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3292 predicate = FCmpInst::Predicate(FC->getPredicate()); 3293 SDValue Op1 = getValue(I.getOperand(0)); 3294 SDValue Op2 = getValue(I.getOperand(1)); 3295 3296 ISD::CondCode Condition = getFCmpCondCode(predicate); 3297 auto *FPMO = cast<FPMathOperator>(&I); 3298 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3299 Condition = getFCmpCodeWithoutNaN(Condition); 3300 3301 SDNodeFlags Flags; 3302 Flags.copyFMF(*FPMO); 3303 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3304 3305 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3306 I.getType()); 3307 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3308 } 3309 3310 // Check if the condition of the select has one use or two users that are both 3311 // selects with the same condition. 3312 static bool hasOnlySelectUsers(const Value *Cond) { 3313 return llvm::all_of(Cond->users(), [](const Value *V) { 3314 return isa<SelectInst>(V); 3315 }); 3316 } 3317 3318 void SelectionDAGBuilder::visitSelect(const User &I) { 3319 SmallVector<EVT, 4> ValueVTs; 3320 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3321 ValueVTs); 3322 unsigned NumValues = ValueVTs.size(); 3323 if (NumValues == 0) return; 3324 3325 SmallVector<SDValue, 4> Values(NumValues); 3326 SDValue Cond = getValue(I.getOperand(0)); 3327 SDValue LHSVal = getValue(I.getOperand(1)); 3328 SDValue RHSVal = getValue(I.getOperand(2)); 3329 SmallVector<SDValue, 1> BaseOps(1, Cond); 3330 ISD::NodeType OpCode = 3331 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3332 3333 bool IsUnaryAbs = false; 3334 bool Negate = false; 3335 3336 SDNodeFlags Flags; 3337 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3338 Flags.copyFMF(*FPOp); 3339 3340 // Min/max matching is only viable if all output VTs are the same. 3341 if (all_equal(ValueVTs)) { 3342 EVT VT = ValueVTs[0]; 3343 LLVMContext &Ctx = *DAG.getContext(); 3344 auto &TLI = DAG.getTargetLoweringInfo(); 3345 3346 // We care about the legality of the operation after it has been type 3347 // legalized. 3348 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3349 VT = TLI.getTypeToTransformTo(Ctx, VT); 3350 3351 // If the vselect is legal, assume we want to leave this as a vector setcc + 3352 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3353 // min/max is legal on the scalar type. 3354 bool UseScalarMinMax = VT.isVector() && 3355 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3356 3357 Value *LHS, *RHS; 3358 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3359 ISD::NodeType Opc = ISD::DELETED_NODE; 3360 switch (SPR.Flavor) { 3361 case SPF_UMAX: Opc = ISD::UMAX; break; 3362 case SPF_UMIN: Opc = ISD::UMIN; break; 3363 case SPF_SMAX: Opc = ISD::SMAX; break; 3364 case SPF_SMIN: Opc = ISD::SMIN; break; 3365 case SPF_FMINNUM: 3366 switch (SPR.NaNBehavior) { 3367 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3368 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3369 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3370 case SPNB_RETURNS_ANY: { 3371 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3372 Opc = ISD::FMINNUM; 3373 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3374 Opc = ISD::FMINIMUM; 3375 else if (UseScalarMinMax) 3376 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3377 ISD::FMINNUM : ISD::FMINIMUM; 3378 break; 3379 } 3380 } 3381 break; 3382 case SPF_FMAXNUM: 3383 switch (SPR.NaNBehavior) { 3384 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3385 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3386 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3387 case SPNB_RETURNS_ANY: 3388 3389 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3390 Opc = ISD::FMAXNUM; 3391 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3392 Opc = ISD::FMAXIMUM; 3393 else if (UseScalarMinMax) 3394 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3395 ISD::FMAXNUM : ISD::FMAXIMUM; 3396 break; 3397 } 3398 break; 3399 case SPF_NABS: 3400 Negate = true; 3401 [[fallthrough]]; 3402 case SPF_ABS: 3403 IsUnaryAbs = true; 3404 Opc = ISD::ABS; 3405 break; 3406 default: break; 3407 } 3408 3409 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3410 (TLI.isOperationLegalOrCustom(Opc, VT) || 3411 (UseScalarMinMax && 3412 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3413 // If the underlying comparison instruction is used by any other 3414 // instruction, the consumed instructions won't be destroyed, so it is 3415 // not profitable to convert to a min/max. 3416 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3417 OpCode = Opc; 3418 LHSVal = getValue(LHS); 3419 RHSVal = getValue(RHS); 3420 BaseOps.clear(); 3421 } 3422 3423 if (IsUnaryAbs) { 3424 OpCode = Opc; 3425 LHSVal = getValue(LHS); 3426 BaseOps.clear(); 3427 } 3428 } 3429 3430 if (IsUnaryAbs) { 3431 for (unsigned i = 0; i != NumValues; ++i) { 3432 SDLoc dl = getCurSDLoc(); 3433 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3434 Values[i] = 3435 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3436 if (Negate) 3437 Values[i] = DAG.getNegative(Values[i], dl, VT); 3438 } 3439 } else { 3440 for (unsigned i = 0; i != NumValues; ++i) { 3441 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3442 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3443 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3444 Values[i] = DAG.getNode( 3445 OpCode, getCurSDLoc(), 3446 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3447 } 3448 } 3449 3450 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3451 DAG.getVTList(ValueVTs), Values)); 3452 } 3453 3454 void SelectionDAGBuilder::visitTrunc(const User &I) { 3455 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3456 SDValue N = getValue(I.getOperand(0)); 3457 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3458 I.getType()); 3459 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3460 } 3461 3462 void SelectionDAGBuilder::visitZExt(const User &I) { 3463 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3464 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3465 SDValue N = getValue(I.getOperand(0)); 3466 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3467 I.getType()); 3468 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3469 } 3470 3471 void SelectionDAGBuilder::visitSExt(const User &I) { 3472 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3473 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3474 SDValue N = getValue(I.getOperand(0)); 3475 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3476 I.getType()); 3477 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3478 } 3479 3480 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3481 // FPTrunc is never a no-op cast, no need to check 3482 SDValue N = getValue(I.getOperand(0)); 3483 SDLoc dl = getCurSDLoc(); 3484 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3485 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3486 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3487 DAG.getTargetConstant( 3488 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3489 } 3490 3491 void SelectionDAGBuilder::visitFPExt(const User &I) { 3492 // FPExt is never a no-op cast, no need to check 3493 SDValue N = getValue(I.getOperand(0)); 3494 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3495 I.getType()); 3496 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3497 } 3498 3499 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3500 // FPToUI is never a no-op cast, no need to check 3501 SDValue N = getValue(I.getOperand(0)); 3502 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3503 I.getType()); 3504 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3505 } 3506 3507 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3508 // FPToSI is never a no-op cast, no need to check 3509 SDValue N = getValue(I.getOperand(0)); 3510 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3511 I.getType()); 3512 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3513 } 3514 3515 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3516 // UIToFP 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::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3521 } 3522 3523 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3524 // SIToFP 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::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3529 } 3530 3531 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3532 // What to do depends on the size of the integer and the size of the pointer. 3533 // We can either truncate, zero extend, or no-op, accordingly. 3534 SDValue N = getValue(I.getOperand(0)); 3535 auto &TLI = DAG.getTargetLoweringInfo(); 3536 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3537 I.getType()); 3538 EVT PtrMemVT = 3539 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3540 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3541 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3542 setValue(&I, N); 3543 } 3544 3545 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3546 // What to do depends on the size of the integer and the size of the pointer. 3547 // We can either truncate, zero extend, or no-op, accordingly. 3548 SDValue N = getValue(I.getOperand(0)); 3549 auto &TLI = DAG.getTargetLoweringInfo(); 3550 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3551 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3552 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3553 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3554 setValue(&I, N); 3555 } 3556 3557 void SelectionDAGBuilder::visitBitCast(const User &I) { 3558 SDValue N = getValue(I.getOperand(0)); 3559 SDLoc dl = getCurSDLoc(); 3560 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3561 I.getType()); 3562 3563 // BitCast assures us that source and destination are the same size so this is 3564 // either a BITCAST or a no-op. 3565 if (DestVT != N.getValueType()) 3566 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3567 DestVT, N)); // convert types. 3568 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3569 // might fold any kind of constant expression to an integer constant and that 3570 // is not what we are looking for. Only recognize a bitcast of a genuine 3571 // constant integer as an opaque constant. 3572 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3573 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3574 /*isOpaque*/true)); 3575 else 3576 setValue(&I, N); // noop cast. 3577 } 3578 3579 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3580 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3581 const Value *SV = I.getOperand(0); 3582 SDValue N = getValue(SV); 3583 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3584 3585 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3586 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3587 3588 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3589 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3590 3591 setValue(&I, N); 3592 } 3593 3594 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3595 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3596 SDValue InVec = getValue(I.getOperand(0)); 3597 SDValue InVal = getValue(I.getOperand(1)); 3598 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3599 TLI.getVectorIdxTy(DAG.getDataLayout())); 3600 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3601 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3602 InVec, InVal, InIdx)); 3603 } 3604 3605 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3606 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3607 SDValue InVec = getValue(I.getOperand(0)); 3608 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3609 TLI.getVectorIdxTy(DAG.getDataLayout())); 3610 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3611 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3612 InVec, InIdx)); 3613 } 3614 3615 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3616 SDValue Src1 = getValue(I.getOperand(0)); 3617 SDValue Src2 = getValue(I.getOperand(1)); 3618 ArrayRef<int> Mask; 3619 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3620 Mask = SVI->getShuffleMask(); 3621 else 3622 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3623 SDLoc DL = getCurSDLoc(); 3624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3625 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3626 EVT SrcVT = Src1.getValueType(); 3627 3628 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3629 VT.isScalableVector()) { 3630 // Canonical splat form of first element of first input vector. 3631 SDValue FirstElt = 3632 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3633 DAG.getVectorIdxConstant(0, DL)); 3634 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3635 return; 3636 } 3637 3638 // For now, we only handle splats for scalable vectors. 3639 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3640 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3641 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3642 3643 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3644 unsigned MaskNumElts = Mask.size(); 3645 3646 if (SrcNumElts == MaskNumElts) { 3647 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3648 return; 3649 } 3650 3651 // Normalize the shuffle vector since mask and vector length don't match. 3652 if (SrcNumElts < MaskNumElts) { 3653 // Mask is longer than the source vectors. We can use concatenate vector to 3654 // make the mask and vectors lengths match. 3655 3656 if (MaskNumElts % SrcNumElts == 0) { 3657 // Mask length is a multiple of the source vector length. 3658 // Check if the shuffle is some kind of concatenation of the input 3659 // vectors. 3660 unsigned NumConcat = MaskNumElts / SrcNumElts; 3661 bool IsConcat = true; 3662 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3663 for (unsigned i = 0; i != MaskNumElts; ++i) { 3664 int Idx = Mask[i]; 3665 if (Idx < 0) 3666 continue; 3667 // Ensure the indices in each SrcVT sized piece are sequential and that 3668 // the same source is used for the whole piece. 3669 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3670 (ConcatSrcs[i / SrcNumElts] >= 0 && 3671 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3672 IsConcat = false; 3673 break; 3674 } 3675 // Remember which source this index came from. 3676 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3677 } 3678 3679 // The shuffle is concatenating multiple vectors together. Just emit 3680 // a CONCAT_VECTORS operation. 3681 if (IsConcat) { 3682 SmallVector<SDValue, 8> ConcatOps; 3683 for (auto Src : ConcatSrcs) { 3684 if (Src < 0) 3685 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3686 else if (Src == 0) 3687 ConcatOps.push_back(Src1); 3688 else 3689 ConcatOps.push_back(Src2); 3690 } 3691 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3692 return; 3693 } 3694 } 3695 3696 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3697 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3698 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3699 PaddedMaskNumElts); 3700 3701 // Pad both vectors with undefs to make them the same length as the mask. 3702 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3703 3704 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3705 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3706 MOps1[0] = Src1; 3707 MOps2[0] = Src2; 3708 3709 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3710 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3711 3712 // Readjust mask for new input vector length. 3713 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3714 for (unsigned i = 0; i != MaskNumElts; ++i) { 3715 int Idx = Mask[i]; 3716 if (Idx >= (int)SrcNumElts) 3717 Idx -= SrcNumElts - PaddedMaskNumElts; 3718 MappedOps[i] = Idx; 3719 } 3720 3721 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3722 3723 // If the concatenated vector was padded, extract a subvector with the 3724 // correct number of elements. 3725 if (MaskNumElts != PaddedMaskNumElts) 3726 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3727 DAG.getVectorIdxConstant(0, DL)); 3728 3729 setValue(&I, Result); 3730 return; 3731 } 3732 3733 if (SrcNumElts > MaskNumElts) { 3734 // Analyze the access pattern of the vector to see if we can extract 3735 // two subvectors and do the shuffle. 3736 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3737 bool CanExtract = true; 3738 for (int Idx : Mask) { 3739 unsigned Input = 0; 3740 if (Idx < 0) 3741 continue; 3742 3743 if (Idx >= (int)SrcNumElts) { 3744 Input = 1; 3745 Idx -= SrcNumElts; 3746 } 3747 3748 // If all the indices come from the same MaskNumElts sized portion of 3749 // the sources we can use extract. Also make sure the extract wouldn't 3750 // extract past the end of the source. 3751 int NewStartIdx = alignDown(Idx, MaskNumElts); 3752 if (NewStartIdx + MaskNumElts > SrcNumElts || 3753 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3754 CanExtract = false; 3755 // Make sure we always update StartIdx as we use it to track if all 3756 // elements are undef. 3757 StartIdx[Input] = NewStartIdx; 3758 } 3759 3760 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3761 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3762 return; 3763 } 3764 if (CanExtract) { 3765 // Extract appropriate subvector and generate a vector shuffle 3766 for (unsigned Input = 0; Input < 2; ++Input) { 3767 SDValue &Src = Input == 0 ? Src1 : Src2; 3768 if (StartIdx[Input] < 0) 3769 Src = DAG.getUNDEF(VT); 3770 else { 3771 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3772 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3773 } 3774 } 3775 3776 // Calculate new mask. 3777 SmallVector<int, 8> MappedOps(Mask); 3778 for (int &Idx : MappedOps) { 3779 if (Idx >= (int)SrcNumElts) 3780 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3781 else if (Idx >= 0) 3782 Idx -= StartIdx[0]; 3783 } 3784 3785 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3786 return; 3787 } 3788 } 3789 3790 // We can't use either concat vectors or extract subvectors so fall back to 3791 // replacing the shuffle with extract and build vector. 3792 // to insert and build vector. 3793 EVT EltVT = VT.getVectorElementType(); 3794 SmallVector<SDValue,8> Ops; 3795 for (int Idx : Mask) { 3796 SDValue Res; 3797 3798 if (Idx < 0) { 3799 Res = DAG.getUNDEF(EltVT); 3800 } else { 3801 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3802 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3803 3804 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3805 DAG.getVectorIdxConstant(Idx, DL)); 3806 } 3807 3808 Ops.push_back(Res); 3809 } 3810 3811 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3812 } 3813 3814 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3815 ArrayRef<unsigned> Indices = I.getIndices(); 3816 const Value *Op0 = I.getOperand(0); 3817 const Value *Op1 = I.getOperand(1); 3818 Type *AggTy = I.getType(); 3819 Type *ValTy = Op1->getType(); 3820 bool IntoUndef = isa<UndefValue>(Op0); 3821 bool FromUndef = isa<UndefValue>(Op1); 3822 3823 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3824 3825 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3826 SmallVector<EVT, 4> AggValueVTs; 3827 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3828 SmallVector<EVT, 4> ValValueVTs; 3829 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3830 3831 unsigned NumAggValues = AggValueVTs.size(); 3832 unsigned NumValValues = ValValueVTs.size(); 3833 SmallVector<SDValue, 4> Values(NumAggValues); 3834 3835 // Ignore an insertvalue that produces an empty object 3836 if (!NumAggValues) { 3837 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3838 return; 3839 } 3840 3841 SDValue Agg = getValue(Op0); 3842 unsigned i = 0; 3843 // Copy the beginning value(s) from the original aggregate. 3844 for (; i != LinearIndex; ++i) 3845 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3846 SDValue(Agg.getNode(), Agg.getResNo() + i); 3847 // Copy values from the inserted value(s). 3848 if (NumValValues) { 3849 SDValue Val = getValue(Op1); 3850 for (; i != LinearIndex + NumValValues; ++i) 3851 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3852 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3853 } 3854 // Copy remaining value(s) from the original aggregate. 3855 for (; i != NumAggValues; ++i) 3856 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3857 SDValue(Agg.getNode(), Agg.getResNo() + i); 3858 3859 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3860 DAG.getVTList(AggValueVTs), Values)); 3861 } 3862 3863 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3864 ArrayRef<unsigned> Indices = I.getIndices(); 3865 const Value *Op0 = I.getOperand(0); 3866 Type *AggTy = Op0->getType(); 3867 Type *ValTy = I.getType(); 3868 bool OutOfUndef = isa<UndefValue>(Op0); 3869 3870 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3871 3872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3873 SmallVector<EVT, 4> ValValueVTs; 3874 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3875 3876 unsigned NumValValues = ValValueVTs.size(); 3877 3878 // Ignore a extractvalue that produces an empty object 3879 if (!NumValValues) { 3880 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3881 return; 3882 } 3883 3884 SmallVector<SDValue, 4> Values(NumValValues); 3885 3886 SDValue Agg = getValue(Op0); 3887 // Copy out the selected value(s). 3888 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3889 Values[i - LinearIndex] = 3890 OutOfUndef ? 3891 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3892 SDValue(Agg.getNode(), Agg.getResNo() + i); 3893 3894 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3895 DAG.getVTList(ValValueVTs), Values)); 3896 } 3897 3898 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3899 Value *Op0 = I.getOperand(0); 3900 // Note that the pointer operand may be a vector of pointers. Take the scalar 3901 // element which holds a pointer. 3902 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3903 SDValue N = getValue(Op0); 3904 SDLoc dl = getCurSDLoc(); 3905 auto &TLI = DAG.getTargetLoweringInfo(); 3906 3907 // Normalize Vector GEP - all scalar operands should be converted to the 3908 // splat vector. 3909 bool IsVectorGEP = I.getType()->isVectorTy(); 3910 ElementCount VectorElementCount = 3911 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3912 : ElementCount::getFixed(0); 3913 3914 if (IsVectorGEP && !N.getValueType().isVector()) { 3915 LLVMContext &Context = *DAG.getContext(); 3916 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3917 N = DAG.getSplat(VT, dl, N); 3918 } 3919 3920 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3921 GTI != E; ++GTI) { 3922 const Value *Idx = GTI.getOperand(); 3923 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3924 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3925 if (Field) { 3926 // N = N + Offset 3927 uint64_t Offset = 3928 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3929 3930 // In an inbounds GEP with an offset that is nonnegative even when 3931 // interpreted as signed, assume there is no unsigned overflow. 3932 SDNodeFlags Flags; 3933 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3934 Flags.setNoUnsignedWrap(true); 3935 3936 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3937 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3938 } 3939 } else { 3940 // IdxSize is the width of the arithmetic according to IR semantics. 3941 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3942 // (and fix up the result later). 3943 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3944 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3945 TypeSize ElementSize = 3946 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 3947 // We intentionally mask away the high bits here; ElementSize may not 3948 // fit in IdxTy. 3949 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 3950 bool ElementScalable = ElementSize.isScalable(); 3951 3952 // If this is a scalar constant or a splat vector of constants, 3953 // handle it quickly. 3954 const auto *C = dyn_cast<Constant>(Idx); 3955 if (C && isa<VectorType>(C->getType())) 3956 C = C->getSplatValue(); 3957 3958 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3959 if (CI && CI->isZero()) 3960 continue; 3961 if (CI && !ElementScalable) { 3962 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3963 LLVMContext &Context = *DAG.getContext(); 3964 SDValue OffsVal; 3965 if (IsVectorGEP) 3966 OffsVal = DAG.getConstant( 3967 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3968 else 3969 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3970 3971 // In an inbounds GEP with an offset that is nonnegative even when 3972 // interpreted as signed, assume there is no unsigned overflow. 3973 SDNodeFlags Flags; 3974 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3975 Flags.setNoUnsignedWrap(true); 3976 3977 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3978 3979 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3980 continue; 3981 } 3982 3983 // N = N + Idx * ElementMul; 3984 SDValue IdxN = getValue(Idx); 3985 3986 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3987 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3988 VectorElementCount); 3989 IdxN = DAG.getSplat(VT, dl, IdxN); 3990 } 3991 3992 // If the index is smaller or larger than intptr_t, truncate or extend 3993 // it. 3994 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3995 3996 if (ElementScalable) { 3997 EVT VScaleTy = N.getValueType().getScalarType(); 3998 SDValue VScale = DAG.getNode( 3999 ISD::VSCALE, dl, VScaleTy, 4000 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4001 if (IsVectorGEP) 4002 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4003 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4004 } else { 4005 // If this is a multiply by a power of two, turn it into a shl 4006 // immediately. This is a very common case. 4007 if (ElementMul != 1) { 4008 if (ElementMul.isPowerOf2()) { 4009 unsigned Amt = ElementMul.logBase2(); 4010 IdxN = DAG.getNode(ISD::SHL, dl, 4011 N.getValueType(), IdxN, 4012 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4013 } else { 4014 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4015 IdxN.getValueType()); 4016 IdxN = DAG.getNode(ISD::MUL, dl, 4017 N.getValueType(), IdxN, Scale); 4018 } 4019 } 4020 } 4021 4022 N = DAG.getNode(ISD::ADD, dl, 4023 N.getValueType(), N, IdxN); 4024 } 4025 } 4026 4027 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4028 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4029 if (IsVectorGEP) { 4030 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4031 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4032 } 4033 4034 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4035 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4036 4037 setValue(&I, N); 4038 } 4039 4040 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4041 // If this is a fixed sized alloca in the entry block of the function, 4042 // allocate it statically on the stack. 4043 if (FuncInfo.StaticAllocaMap.count(&I)) 4044 return; // getValue will auto-populate this. 4045 4046 SDLoc dl = getCurSDLoc(); 4047 Type *Ty = I.getAllocatedType(); 4048 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4049 auto &DL = DAG.getDataLayout(); 4050 TypeSize TySize = DL.getTypeAllocSize(Ty); 4051 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4052 4053 SDValue AllocSize = getValue(I.getArraySize()); 4054 4055 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4056 if (AllocSize.getValueType() != IntPtr) 4057 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4058 4059 if (TySize.isScalable()) 4060 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4061 DAG.getVScale(dl, IntPtr, 4062 APInt(IntPtr.getScalarSizeInBits(), 4063 TySize.getKnownMinValue()))); 4064 else 4065 AllocSize = 4066 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4067 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4068 4069 // Handle alignment. If the requested alignment is less than or equal to 4070 // the stack alignment, ignore it. If the size is greater than or equal to 4071 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4072 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4073 if (*Alignment <= StackAlign) 4074 Alignment = std::nullopt; 4075 4076 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4077 // Round the size of the allocation up to the stack alignment size 4078 // by add SA-1 to the size. This doesn't overflow because we're computing 4079 // an address inside an alloca. 4080 SDNodeFlags Flags; 4081 Flags.setNoUnsignedWrap(true); 4082 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4083 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4084 4085 // Mask out the low bits for alignment purposes. 4086 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4087 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4088 4089 SDValue Ops[] = { 4090 getRoot(), AllocSize, 4091 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4092 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4093 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4094 setValue(&I, DSA); 4095 DAG.setRoot(DSA.getValue(1)); 4096 4097 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4098 } 4099 4100 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4101 if (I.isAtomic()) 4102 return visitAtomicLoad(I); 4103 4104 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4105 const Value *SV = I.getOperand(0); 4106 if (TLI.supportSwiftError()) { 4107 // Swifterror values can come from either a function parameter with 4108 // swifterror attribute or an alloca with swifterror attribute. 4109 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4110 if (Arg->hasSwiftErrorAttr()) 4111 return visitLoadFromSwiftError(I); 4112 } 4113 4114 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4115 if (Alloca->isSwiftError()) 4116 return visitLoadFromSwiftError(I); 4117 } 4118 } 4119 4120 SDValue Ptr = getValue(SV); 4121 4122 Type *Ty = I.getType(); 4123 SmallVector<EVT, 4> ValueVTs, MemVTs; 4124 SmallVector<uint64_t, 4> Offsets; 4125 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4126 unsigned NumValues = ValueVTs.size(); 4127 if (NumValues == 0) 4128 return; 4129 4130 Align Alignment = I.getAlign(); 4131 AAMDNodes AAInfo = I.getAAMetadata(); 4132 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4133 bool isVolatile = I.isVolatile(); 4134 MachineMemOperand::Flags MMOFlags = 4135 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4136 4137 SDValue Root; 4138 bool ConstantMemory = false; 4139 if (isVolatile) 4140 // Serialize volatile loads with other side effects. 4141 Root = getRoot(); 4142 else if (NumValues > MaxParallelChains) 4143 Root = getMemoryRoot(); 4144 else if (AA && 4145 AA->pointsToConstantMemory(MemoryLocation( 4146 SV, 4147 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4148 AAInfo))) { 4149 // Do not serialize (non-volatile) loads of constant memory with anything. 4150 Root = DAG.getEntryNode(); 4151 ConstantMemory = true; 4152 MMOFlags |= MachineMemOperand::MOInvariant; 4153 } else { 4154 // Do not serialize non-volatile loads against each other. 4155 Root = DAG.getRoot(); 4156 } 4157 4158 SDLoc dl = getCurSDLoc(); 4159 4160 if (isVolatile) 4161 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4162 4163 // An aggregate load cannot wrap around the address space, so offsets to its 4164 // parts don't wrap either. 4165 SDNodeFlags Flags; 4166 Flags.setNoUnsignedWrap(true); 4167 4168 SmallVector<SDValue, 4> Values(NumValues); 4169 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4170 EVT PtrVT = Ptr.getValueType(); 4171 4172 unsigned ChainI = 0; 4173 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4174 // Serializing loads here may result in excessive register pressure, and 4175 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4176 // could recover a bit by hoisting nodes upward in the chain by recognizing 4177 // they are side-effect free or do not alias. The optimizer should really 4178 // avoid this case by converting large object/array copies to llvm.memcpy 4179 // (MaxParallelChains should always remain as failsafe). 4180 if (ChainI == MaxParallelChains) { 4181 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4182 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4183 ArrayRef(Chains.data(), ChainI)); 4184 Root = Chain; 4185 ChainI = 0; 4186 } 4187 SDValue A = DAG.getNode(ISD::ADD, dl, 4188 PtrVT, Ptr, 4189 DAG.getConstant(Offsets[i], dl, PtrVT), 4190 Flags); 4191 4192 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4193 MachinePointerInfo(SV, Offsets[i]), Alignment, 4194 MMOFlags, AAInfo, Ranges); 4195 Chains[ChainI] = L.getValue(1); 4196 4197 if (MemVTs[i] != ValueVTs[i]) 4198 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4199 4200 Values[i] = L; 4201 } 4202 4203 if (!ConstantMemory) { 4204 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4205 ArrayRef(Chains.data(), ChainI)); 4206 if (isVolatile) 4207 DAG.setRoot(Chain); 4208 else 4209 PendingLoads.push_back(Chain); 4210 } 4211 4212 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4213 DAG.getVTList(ValueVTs), Values)); 4214 } 4215 4216 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4217 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4218 "call visitStoreToSwiftError when backend supports swifterror"); 4219 4220 SmallVector<EVT, 4> ValueVTs; 4221 SmallVector<uint64_t, 4> Offsets; 4222 const Value *SrcV = I.getOperand(0); 4223 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4224 SrcV->getType(), ValueVTs, &Offsets); 4225 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4226 "expect a single EVT for swifterror"); 4227 4228 SDValue Src = getValue(SrcV); 4229 // Create a virtual register, then update the virtual register. 4230 Register VReg = 4231 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4232 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4233 // Chain can be getRoot or getControlRoot. 4234 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4235 SDValue(Src.getNode(), Src.getResNo())); 4236 DAG.setRoot(CopyNode); 4237 } 4238 4239 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4240 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4241 "call visitLoadFromSwiftError when backend supports swifterror"); 4242 4243 assert(!I.isVolatile() && 4244 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4245 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4246 "Support volatile, non temporal, invariant for load_from_swift_error"); 4247 4248 const Value *SV = I.getOperand(0); 4249 Type *Ty = I.getType(); 4250 assert( 4251 (!AA || 4252 !AA->pointsToConstantMemory(MemoryLocation( 4253 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4254 I.getAAMetadata()))) && 4255 "load_from_swift_error should not be constant memory"); 4256 4257 SmallVector<EVT, 4> ValueVTs; 4258 SmallVector<uint64_t, 4> Offsets; 4259 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4260 ValueVTs, &Offsets); 4261 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4262 "expect a single EVT for swifterror"); 4263 4264 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4265 SDValue L = DAG.getCopyFromReg( 4266 getRoot(), getCurSDLoc(), 4267 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4268 4269 setValue(&I, L); 4270 } 4271 4272 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4273 if (I.isAtomic()) 4274 return visitAtomicStore(I); 4275 4276 const Value *SrcV = I.getOperand(0); 4277 const Value *PtrV = I.getOperand(1); 4278 4279 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4280 if (TLI.supportSwiftError()) { 4281 // Swifterror values can come from either a function parameter with 4282 // swifterror attribute or an alloca with swifterror attribute. 4283 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4284 if (Arg->hasSwiftErrorAttr()) 4285 return visitStoreToSwiftError(I); 4286 } 4287 4288 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4289 if (Alloca->isSwiftError()) 4290 return visitStoreToSwiftError(I); 4291 } 4292 } 4293 4294 SmallVector<EVT, 4> ValueVTs, MemVTs; 4295 SmallVector<uint64_t, 4> Offsets; 4296 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4297 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4298 unsigned NumValues = ValueVTs.size(); 4299 if (NumValues == 0) 4300 return; 4301 4302 // Get the lowered operands. Note that we do this after 4303 // checking if NumResults is zero, because with zero results 4304 // the operands won't have values in the map. 4305 SDValue Src = getValue(SrcV); 4306 SDValue Ptr = getValue(PtrV); 4307 4308 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4309 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4310 SDLoc dl = getCurSDLoc(); 4311 Align Alignment = I.getAlign(); 4312 AAMDNodes AAInfo = I.getAAMetadata(); 4313 4314 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4315 4316 // An aggregate load cannot wrap around the address space, so offsets to its 4317 // parts don't wrap either. 4318 SDNodeFlags Flags; 4319 Flags.setNoUnsignedWrap(true); 4320 4321 unsigned ChainI = 0; 4322 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4323 // See visitLoad comments. 4324 if (ChainI == MaxParallelChains) { 4325 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4326 ArrayRef(Chains.data(), ChainI)); 4327 Root = Chain; 4328 ChainI = 0; 4329 } 4330 SDValue Add = 4331 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4332 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4333 if (MemVTs[i] != ValueVTs[i]) 4334 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4335 SDValue St = 4336 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4337 Alignment, MMOFlags, AAInfo); 4338 Chains[ChainI] = St; 4339 } 4340 4341 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4342 ArrayRef(Chains.data(), ChainI)); 4343 setValue(&I, StoreNode); 4344 DAG.setRoot(StoreNode); 4345 } 4346 4347 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4348 bool IsCompressing) { 4349 SDLoc sdl = getCurSDLoc(); 4350 4351 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4352 MaybeAlign &Alignment) { 4353 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4354 Src0 = I.getArgOperand(0); 4355 Ptr = I.getArgOperand(1); 4356 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4357 Mask = I.getArgOperand(3); 4358 }; 4359 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4360 MaybeAlign &Alignment) { 4361 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4362 Src0 = I.getArgOperand(0); 4363 Ptr = I.getArgOperand(1); 4364 Mask = I.getArgOperand(2); 4365 Alignment = std::nullopt; 4366 }; 4367 4368 Value *PtrOperand, *MaskOperand, *Src0Operand; 4369 MaybeAlign Alignment; 4370 if (IsCompressing) 4371 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4372 else 4373 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4374 4375 SDValue Ptr = getValue(PtrOperand); 4376 SDValue Src0 = getValue(Src0Operand); 4377 SDValue Mask = getValue(MaskOperand); 4378 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4379 4380 EVT VT = Src0.getValueType(); 4381 if (!Alignment) 4382 Alignment = DAG.getEVTAlign(VT); 4383 4384 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4385 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4386 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4387 SDValue StoreNode = 4388 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4389 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4390 DAG.setRoot(StoreNode); 4391 setValue(&I, StoreNode); 4392 } 4393 4394 // Get a uniform base for the Gather/Scatter intrinsic. 4395 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4396 // We try to represent it as a base pointer + vector of indices. 4397 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4398 // The first operand of the GEP may be a single pointer or a vector of pointers 4399 // Example: 4400 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4401 // or 4402 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4403 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4404 // 4405 // When the first GEP operand is a single pointer - it is the uniform base we 4406 // are looking for. If first operand of the GEP is a splat vector - we 4407 // extract the splat value and use it as a uniform base. 4408 // In all other cases the function returns 'false'. 4409 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4410 ISD::MemIndexType &IndexType, SDValue &Scale, 4411 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4412 uint64_t ElemSize) { 4413 SelectionDAG& DAG = SDB->DAG; 4414 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4415 const DataLayout &DL = DAG.getDataLayout(); 4416 4417 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4418 4419 // Handle splat constant pointer. 4420 if (auto *C = dyn_cast<Constant>(Ptr)) { 4421 C = C->getSplatValue(); 4422 if (!C) 4423 return false; 4424 4425 Base = SDB->getValue(C); 4426 4427 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4428 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4429 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4430 IndexType = ISD::SIGNED_SCALED; 4431 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4432 return true; 4433 } 4434 4435 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4436 if (!GEP || GEP->getParent() != CurBB) 4437 return false; 4438 4439 if (GEP->getNumOperands() != 2) 4440 return false; 4441 4442 const Value *BasePtr = GEP->getPointerOperand(); 4443 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4444 4445 // Make sure the base is scalar and the index is a vector. 4446 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4447 return false; 4448 4449 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4450 4451 // Target may not support the required addressing mode. 4452 if (ScaleVal != 1 && 4453 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4454 return false; 4455 4456 Base = SDB->getValue(BasePtr); 4457 Index = SDB->getValue(IndexVal); 4458 IndexType = ISD::SIGNED_SCALED; 4459 4460 Scale = 4461 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4462 return true; 4463 } 4464 4465 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4466 SDLoc sdl = getCurSDLoc(); 4467 4468 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4469 const Value *Ptr = I.getArgOperand(1); 4470 SDValue Src0 = getValue(I.getArgOperand(0)); 4471 SDValue Mask = getValue(I.getArgOperand(3)); 4472 EVT VT = Src0.getValueType(); 4473 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4474 ->getMaybeAlignValue() 4475 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4477 4478 SDValue Base; 4479 SDValue Index; 4480 ISD::MemIndexType IndexType; 4481 SDValue Scale; 4482 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4483 I.getParent(), VT.getScalarStoreSize()); 4484 4485 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4486 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4487 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4488 // TODO: Make MachineMemOperands aware of scalable 4489 // vectors. 4490 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4491 if (!UniformBase) { 4492 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4493 Index = getValue(Ptr); 4494 IndexType = ISD::SIGNED_SCALED; 4495 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4496 } 4497 4498 EVT IdxVT = Index.getValueType(); 4499 EVT EltTy = IdxVT.getVectorElementType(); 4500 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4501 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4502 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4503 } 4504 4505 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4506 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4507 Ops, MMO, IndexType, false); 4508 DAG.setRoot(Scatter); 4509 setValue(&I, Scatter); 4510 } 4511 4512 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4513 SDLoc sdl = getCurSDLoc(); 4514 4515 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4516 MaybeAlign &Alignment) { 4517 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4518 Ptr = I.getArgOperand(0); 4519 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4520 Mask = I.getArgOperand(2); 4521 Src0 = I.getArgOperand(3); 4522 }; 4523 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4524 MaybeAlign &Alignment) { 4525 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4526 Ptr = I.getArgOperand(0); 4527 Alignment = std::nullopt; 4528 Mask = I.getArgOperand(1); 4529 Src0 = I.getArgOperand(2); 4530 }; 4531 4532 Value *PtrOperand, *MaskOperand, *Src0Operand; 4533 MaybeAlign Alignment; 4534 if (IsExpanding) 4535 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4536 else 4537 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4538 4539 SDValue Ptr = getValue(PtrOperand); 4540 SDValue Src0 = getValue(Src0Operand); 4541 SDValue Mask = getValue(MaskOperand); 4542 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4543 4544 EVT VT = Src0.getValueType(); 4545 if (!Alignment) 4546 Alignment = DAG.getEVTAlign(VT); 4547 4548 AAMDNodes AAInfo = I.getAAMetadata(); 4549 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4550 4551 // Do not serialize masked loads of constant memory with anything. 4552 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4553 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4554 4555 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4556 4557 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4558 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4559 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4560 4561 SDValue Load = 4562 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4563 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4564 if (AddToChain) 4565 PendingLoads.push_back(Load.getValue(1)); 4566 setValue(&I, Load); 4567 } 4568 4569 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4570 SDLoc sdl = getCurSDLoc(); 4571 4572 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4573 const Value *Ptr = I.getArgOperand(0); 4574 SDValue Src0 = getValue(I.getArgOperand(3)); 4575 SDValue Mask = getValue(I.getArgOperand(2)); 4576 4577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4578 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4579 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4580 ->getMaybeAlignValue() 4581 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4582 4583 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4584 4585 SDValue Root = DAG.getRoot(); 4586 SDValue Base; 4587 SDValue Index; 4588 ISD::MemIndexType IndexType; 4589 SDValue Scale; 4590 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4591 I.getParent(), VT.getScalarStoreSize()); 4592 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4593 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4594 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4595 // TODO: Make MachineMemOperands aware of scalable 4596 // vectors. 4597 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4598 4599 if (!UniformBase) { 4600 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4601 Index = getValue(Ptr); 4602 IndexType = ISD::SIGNED_SCALED; 4603 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4604 } 4605 4606 EVT IdxVT = Index.getValueType(); 4607 EVT EltTy = IdxVT.getVectorElementType(); 4608 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4609 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4610 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4611 } 4612 4613 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4614 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4615 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4616 4617 PendingLoads.push_back(Gather.getValue(1)); 4618 setValue(&I, Gather); 4619 } 4620 4621 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4622 SDLoc dl = getCurSDLoc(); 4623 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4624 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4625 SyncScope::ID SSID = I.getSyncScopeID(); 4626 4627 SDValue InChain = getRoot(); 4628 4629 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4630 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4631 4632 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4633 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4634 4635 MachineFunction &MF = DAG.getMachineFunction(); 4636 MachineMemOperand *MMO = MF.getMachineMemOperand( 4637 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4638 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4639 FailureOrdering); 4640 4641 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4642 dl, MemVT, VTs, InChain, 4643 getValue(I.getPointerOperand()), 4644 getValue(I.getCompareOperand()), 4645 getValue(I.getNewValOperand()), MMO); 4646 4647 SDValue OutChain = L.getValue(2); 4648 4649 setValue(&I, L); 4650 DAG.setRoot(OutChain); 4651 } 4652 4653 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4654 SDLoc dl = getCurSDLoc(); 4655 ISD::NodeType NT; 4656 switch (I.getOperation()) { 4657 default: llvm_unreachable("Unknown atomicrmw operation"); 4658 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4659 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4660 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4661 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4662 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4663 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4664 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4665 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4666 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4667 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4668 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4669 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4670 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4671 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4672 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4673 case AtomicRMWInst::UIncWrap: 4674 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4675 break; 4676 case AtomicRMWInst::UDecWrap: 4677 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4678 break; 4679 } 4680 AtomicOrdering Ordering = I.getOrdering(); 4681 SyncScope::ID SSID = I.getSyncScopeID(); 4682 4683 SDValue InChain = getRoot(); 4684 4685 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4686 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4687 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4688 4689 MachineFunction &MF = DAG.getMachineFunction(); 4690 MachineMemOperand *MMO = MF.getMachineMemOperand( 4691 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4692 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4693 4694 SDValue L = 4695 DAG.getAtomic(NT, dl, MemVT, InChain, 4696 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4697 MMO); 4698 4699 SDValue OutChain = L.getValue(1); 4700 4701 setValue(&I, L); 4702 DAG.setRoot(OutChain); 4703 } 4704 4705 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4706 SDLoc dl = getCurSDLoc(); 4707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4708 SDValue Ops[3]; 4709 Ops[0] = getRoot(); 4710 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4711 TLI.getFenceOperandTy(DAG.getDataLayout())); 4712 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4713 TLI.getFenceOperandTy(DAG.getDataLayout())); 4714 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4715 setValue(&I, N); 4716 DAG.setRoot(N); 4717 } 4718 4719 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4720 SDLoc dl = getCurSDLoc(); 4721 AtomicOrdering Order = I.getOrdering(); 4722 SyncScope::ID SSID = I.getSyncScopeID(); 4723 4724 SDValue InChain = getRoot(); 4725 4726 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4727 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4728 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4729 4730 if (!TLI.supportsUnalignedAtomics() && 4731 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4732 report_fatal_error("Cannot generate unaligned atomic load"); 4733 4734 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4735 4736 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4737 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4738 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4739 4740 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4741 4742 SDValue Ptr = getValue(I.getPointerOperand()); 4743 4744 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4745 // TODO: Once this is better exercised by tests, it should be merged with 4746 // the normal path for loads to prevent future divergence. 4747 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4748 if (MemVT != VT) 4749 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4750 4751 setValue(&I, L); 4752 SDValue OutChain = L.getValue(1); 4753 if (!I.isUnordered()) 4754 DAG.setRoot(OutChain); 4755 else 4756 PendingLoads.push_back(OutChain); 4757 return; 4758 } 4759 4760 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4761 Ptr, MMO); 4762 4763 SDValue OutChain = L.getValue(1); 4764 if (MemVT != VT) 4765 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4766 4767 setValue(&I, L); 4768 DAG.setRoot(OutChain); 4769 } 4770 4771 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4772 SDLoc dl = getCurSDLoc(); 4773 4774 AtomicOrdering Ordering = I.getOrdering(); 4775 SyncScope::ID SSID = I.getSyncScopeID(); 4776 4777 SDValue InChain = getRoot(); 4778 4779 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4780 EVT MemVT = 4781 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4782 4783 if (!TLI.supportsUnalignedAtomics() && 4784 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4785 report_fatal_error("Cannot generate unaligned atomic store"); 4786 4787 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4788 4789 MachineFunction &MF = DAG.getMachineFunction(); 4790 MachineMemOperand *MMO = MF.getMachineMemOperand( 4791 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4792 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4793 4794 SDValue Val = getValue(I.getValueOperand()); 4795 if (Val.getValueType() != MemVT) 4796 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4797 SDValue Ptr = getValue(I.getPointerOperand()); 4798 4799 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4800 // TODO: Once this is better exercised by tests, it should be merged with 4801 // the normal path for stores to prevent future divergence. 4802 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4803 setValue(&I, S); 4804 DAG.setRoot(S); 4805 return; 4806 } 4807 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4808 Ptr, Val, MMO); 4809 4810 setValue(&I, OutChain); 4811 DAG.setRoot(OutChain); 4812 } 4813 4814 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4815 /// node. 4816 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4817 unsigned Intrinsic) { 4818 // Ignore the callsite's attributes. A specific call site may be marked with 4819 // readnone, but the lowering code will expect the chain based on the 4820 // definition. 4821 const Function *F = I.getCalledFunction(); 4822 bool HasChain = !F->doesNotAccessMemory(); 4823 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4824 4825 // Build the operand list. 4826 SmallVector<SDValue, 8> Ops; 4827 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4828 if (OnlyLoad) { 4829 // We don't need to serialize loads against other loads. 4830 Ops.push_back(DAG.getRoot()); 4831 } else { 4832 Ops.push_back(getRoot()); 4833 } 4834 } 4835 4836 // Info is set by getTgtMemIntrinsic 4837 TargetLowering::IntrinsicInfo Info; 4838 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4839 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4840 DAG.getMachineFunction(), 4841 Intrinsic); 4842 4843 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4844 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4845 Info.opc == ISD::INTRINSIC_W_CHAIN) 4846 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4847 TLI.getPointerTy(DAG.getDataLayout()))); 4848 4849 // Add all operands of the call to the operand list. 4850 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4851 const Value *Arg = I.getArgOperand(i); 4852 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4853 Ops.push_back(getValue(Arg)); 4854 continue; 4855 } 4856 4857 // Use TargetConstant instead of a regular constant for immarg. 4858 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4859 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4860 assert(CI->getBitWidth() <= 64 && 4861 "large intrinsic immediates not handled"); 4862 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4863 } else { 4864 Ops.push_back( 4865 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4866 } 4867 } 4868 4869 SmallVector<EVT, 4> ValueVTs; 4870 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4871 4872 if (HasChain) 4873 ValueVTs.push_back(MVT::Other); 4874 4875 SDVTList VTs = DAG.getVTList(ValueVTs); 4876 4877 // Propagate fast-math-flags from IR to node(s). 4878 SDNodeFlags Flags; 4879 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4880 Flags.copyFMF(*FPMO); 4881 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4882 4883 // Create the node. 4884 SDValue Result; 4885 // In some cases, custom collection of operands from CallInst I may be needed. 4886 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4887 if (IsTgtIntrinsic) { 4888 // This is target intrinsic that touches memory 4889 // 4890 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4891 // didn't yield anything useful. 4892 MachinePointerInfo MPI; 4893 if (Info.ptrVal) 4894 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4895 else if (Info.fallbackAddressSpace) 4896 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4897 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4898 Info.memVT, MPI, Info.align, Info.flags, 4899 Info.size, I.getAAMetadata()); 4900 } else if (!HasChain) { 4901 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4902 } else if (!I.getType()->isVoidTy()) { 4903 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4904 } else { 4905 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4906 } 4907 4908 if (HasChain) { 4909 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4910 if (OnlyLoad) 4911 PendingLoads.push_back(Chain); 4912 else 4913 DAG.setRoot(Chain); 4914 } 4915 4916 if (!I.getType()->isVoidTy()) { 4917 if (!isa<VectorType>(I.getType())) 4918 Result = lowerRangeToAssertZExt(DAG, I, Result); 4919 4920 MaybeAlign Alignment = I.getRetAlign(); 4921 4922 // Insert `assertalign` node if there's an alignment. 4923 if (InsertAssertAlign && Alignment) { 4924 Result = 4925 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4926 } 4927 4928 setValue(&I, Result); 4929 } 4930 } 4931 4932 /// GetSignificand - Get the significand and build it into a floating-point 4933 /// number with exponent of 1: 4934 /// 4935 /// Op = (Op & 0x007fffff) | 0x3f800000; 4936 /// 4937 /// where Op is the hexadecimal representation of floating point value. 4938 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4939 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4940 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4941 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4942 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4943 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4944 } 4945 4946 /// GetExponent - Get the exponent: 4947 /// 4948 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4949 /// 4950 /// where Op is the hexadecimal representation of floating point value. 4951 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4952 const TargetLowering &TLI, const SDLoc &dl) { 4953 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4954 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4955 SDValue t1 = DAG.getNode( 4956 ISD::SRL, dl, MVT::i32, t0, 4957 DAG.getConstant(23, dl, 4958 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 4959 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4960 DAG.getConstant(127, dl, MVT::i32)); 4961 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4962 } 4963 4964 /// getF32Constant - Get 32-bit floating point constant. 4965 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4966 const SDLoc &dl) { 4967 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4968 MVT::f32); 4969 } 4970 4971 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4972 SelectionDAG &DAG) { 4973 // TODO: What fast-math-flags should be set on the floating-point nodes? 4974 4975 // IntegerPartOfX = ((int32_t)(t0); 4976 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4977 4978 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4979 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4980 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4981 4982 // IntegerPartOfX <<= 23; 4983 IntegerPartOfX = 4984 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4985 DAG.getConstant(23, dl, 4986 DAG.getTargetLoweringInfo().getShiftAmountTy( 4987 MVT::i32, DAG.getDataLayout()))); 4988 4989 SDValue TwoToFractionalPartOfX; 4990 if (LimitFloatPrecision <= 6) { 4991 // For floating-point precision of 6: 4992 // 4993 // TwoToFractionalPartOfX = 4994 // 0.997535578f + 4995 // (0.735607626f + 0.252464424f * x) * x; 4996 // 4997 // error 0.0144103317, which is 6 bits 4998 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4999 getF32Constant(DAG, 0x3e814304, dl)); 5000 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5001 getF32Constant(DAG, 0x3f3c50c8, dl)); 5002 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5003 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5004 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5005 } else if (LimitFloatPrecision <= 12) { 5006 // For floating-point precision of 12: 5007 // 5008 // TwoToFractionalPartOfX = 5009 // 0.999892986f + 5010 // (0.696457318f + 5011 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5012 // 5013 // error 0.000107046256, which is 13 to 14 bits 5014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5015 getF32Constant(DAG, 0x3da235e3, dl)); 5016 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5017 getF32Constant(DAG, 0x3e65b8f3, dl)); 5018 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5019 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5020 getF32Constant(DAG, 0x3f324b07, dl)); 5021 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5022 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5023 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5024 } else { // LimitFloatPrecision <= 18 5025 // For floating-point precision of 18: 5026 // 5027 // TwoToFractionalPartOfX = 5028 // 0.999999982f + 5029 // (0.693148872f + 5030 // (0.240227044f + 5031 // (0.554906021e-1f + 5032 // (0.961591928e-2f + 5033 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5034 // error 2.47208000*10^(-7), which is better than 18 bits 5035 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5036 getF32Constant(DAG, 0x3924b03e, dl)); 5037 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5038 getF32Constant(DAG, 0x3ab24b87, dl)); 5039 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5040 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5041 getF32Constant(DAG, 0x3c1d8c17, dl)); 5042 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5043 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5044 getF32Constant(DAG, 0x3d634a1d, dl)); 5045 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5046 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5047 getF32Constant(DAG, 0x3e75fe14, dl)); 5048 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5049 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5050 getF32Constant(DAG, 0x3f317234, dl)); 5051 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5052 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5053 getF32Constant(DAG, 0x3f800000, dl)); 5054 } 5055 5056 // Add the exponent into the result in integer domain. 5057 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5058 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5059 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5060 } 5061 5062 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5063 /// limited-precision mode. 5064 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5065 const TargetLowering &TLI, SDNodeFlags Flags) { 5066 if (Op.getValueType() == MVT::f32 && 5067 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5068 5069 // Put the exponent in the right bit position for later addition to the 5070 // final result: 5071 // 5072 // t0 = Op * log2(e) 5073 5074 // TODO: What fast-math-flags should be set here? 5075 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5076 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5077 return getLimitedPrecisionExp2(t0, dl, DAG); 5078 } 5079 5080 // No special expansion. 5081 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5082 } 5083 5084 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5085 /// limited-precision mode. 5086 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5087 const TargetLowering &TLI, SDNodeFlags Flags) { 5088 // TODO: What fast-math-flags should be set on the floating-point nodes? 5089 5090 if (Op.getValueType() == MVT::f32 && 5091 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5092 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5093 5094 // Scale the exponent by log(2). 5095 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5096 SDValue LogOfExponent = 5097 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5098 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5099 5100 // Get the significand and build it into a floating-point number with 5101 // exponent of 1. 5102 SDValue X = GetSignificand(DAG, Op1, dl); 5103 5104 SDValue LogOfMantissa; 5105 if (LimitFloatPrecision <= 6) { 5106 // For floating-point precision of 6: 5107 // 5108 // LogofMantissa = 5109 // -1.1609546f + 5110 // (1.4034025f - 0.23903021f * x) * x; 5111 // 5112 // error 0.0034276066, which is better than 8 bits 5113 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5114 getF32Constant(DAG, 0xbe74c456, dl)); 5115 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5116 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5117 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5118 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5119 getF32Constant(DAG, 0x3f949a29, dl)); 5120 } else if (LimitFloatPrecision <= 12) { 5121 // For floating-point precision of 12: 5122 // 5123 // LogOfMantissa = 5124 // -1.7417939f + 5125 // (2.8212026f + 5126 // (-1.4699568f + 5127 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5128 // 5129 // error 0.000061011436, which is 14 bits 5130 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5131 getF32Constant(DAG, 0xbd67b6d6, dl)); 5132 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5133 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5135 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5136 getF32Constant(DAG, 0x3fbc278b, dl)); 5137 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5138 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5139 getF32Constant(DAG, 0x40348e95, dl)); 5140 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5141 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5142 getF32Constant(DAG, 0x3fdef31a, dl)); 5143 } else { // LimitFloatPrecision <= 18 5144 // For floating-point precision of 18: 5145 // 5146 // LogOfMantissa = 5147 // -2.1072184f + 5148 // (4.2372794f + 5149 // (-3.7029485f + 5150 // (2.2781945f + 5151 // (-0.87823314f + 5152 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5153 // 5154 // error 0.0000023660568, which is better than 18 bits 5155 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5156 getF32Constant(DAG, 0xbc91e5ac, dl)); 5157 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5158 getF32Constant(DAG, 0x3e4350aa, dl)); 5159 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5160 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5161 getF32Constant(DAG, 0x3f60d3e3, dl)); 5162 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5163 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5164 getF32Constant(DAG, 0x4011cdf0, dl)); 5165 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5166 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5167 getF32Constant(DAG, 0x406cfd1c, dl)); 5168 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5169 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5170 getF32Constant(DAG, 0x408797cb, dl)); 5171 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5172 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5173 getF32Constant(DAG, 0x4006dcab, dl)); 5174 } 5175 5176 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5177 } 5178 5179 // No special expansion. 5180 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5181 } 5182 5183 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5184 /// limited-precision mode. 5185 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5186 const TargetLowering &TLI, SDNodeFlags Flags) { 5187 // TODO: What fast-math-flags should be set on the floating-point nodes? 5188 5189 if (Op.getValueType() == MVT::f32 && 5190 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5191 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5192 5193 // Get the exponent. 5194 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5195 5196 // Get the significand and build it into a floating-point number with 5197 // exponent of 1. 5198 SDValue X = GetSignificand(DAG, Op1, dl); 5199 5200 // Different possible minimax approximations of significand in 5201 // floating-point for various degrees of accuracy over [1,2]. 5202 SDValue Log2ofMantissa; 5203 if (LimitFloatPrecision <= 6) { 5204 // For floating-point precision of 6: 5205 // 5206 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5207 // 5208 // error 0.0049451742, which is more than 7 bits 5209 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5210 getF32Constant(DAG, 0xbeb08fe0, dl)); 5211 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5212 getF32Constant(DAG, 0x40019463, dl)); 5213 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5214 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5215 getF32Constant(DAG, 0x3fd6633d, dl)); 5216 } else if (LimitFloatPrecision <= 12) { 5217 // For floating-point precision of 12: 5218 // 5219 // Log2ofMantissa = 5220 // -2.51285454f + 5221 // (4.07009056f + 5222 // (-2.12067489f + 5223 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5224 // 5225 // error 0.0000876136000, which is better than 13 bits 5226 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5227 getF32Constant(DAG, 0xbda7262e, dl)); 5228 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5229 getF32Constant(DAG, 0x3f25280b, dl)); 5230 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5231 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5232 getF32Constant(DAG, 0x4007b923, dl)); 5233 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5234 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5235 getF32Constant(DAG, 0x40823e2f, dl)); 5236 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5237 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5238 getF32Constant(DAG, 0x4020d29c, dl)); 5239 } else { // LimitFloatPrecision <= 18 5240 // For floating-point precision of 18: 5241 // 5242 // Log2ofMantissa = 5243 // -3.0400495f + 5244 // (6.1129976f + 5245 // (-5.3420409f + 5246 // (3.2865683f + 5247 // (-1.2669343f + 5248 // (0.27515199f - 5249 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5250 // 5251 // error 0.0000018516, which is better than 18 bits 5252 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5253 getF32Constant(DAG, 0xbcd2769e, dl)); 5254 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5255 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5256 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5257 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5258 getF32Constant(DAG, 0x3fa22ae7, dl)); 5259 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5260 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5261 getF32Constant(DAG, 0x40525723, dl)); 5262 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5263 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5264 getF32Constant(DAG, 0x40aaf200, dl)); 5265 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5266 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5267 getF32Constant(DAG, 0x40c39dad, dl)); 5268 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5269 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5270 getF32Constant(DAG, 0x4042902c, dl)); 5271 } 5272 5273 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5274 } 5275 5276 // No special expansion. 5277 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5278 } 5279 5280 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5281 /// limited-precision mode. 5282 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5283 const TargetLowering &TLI, SDNodeFlags Flags) { 5284 // TODO: What fast-math-flags should be set on the floating-point nodes? 5285 5286 if (Op.getValueType() == MVT::f32 && 5287 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5288 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5289 5290 // Scale the exponent by log10(2) [0.30102999f]. 5291 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5292 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5293 getF32Constant(DAG, 0x3e9a209a, dl)); 5294 5295 // Get the significand and build it into a floating-point number with 5296 // exponent of 1. 5297 SDValue X = GetSignificand(DAG, Op1, dl); 5298 5299 SDValue Log10ofMantissa; 5300 if (LimitFloatPrecision <= 6) { 5301 // For floating-point precision of 6: 5302 // 5303 // Log10ofMantissa = 5304 // -0.50419619f + 5305 // (0.60948995f - 0.10380950f * x) * x; 5306 // 5307 // error 0.0014886165, which is 6 bits 5308 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5309 getF32Constant(DAG, 0xbdd49a13, dl)); 5310 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5311 getF32Constant(DAG, 0x3f1c0789, dl)); 5312 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5313 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5314 getF32Constant(DAG, 0x3f011300, dl)); 5315 } else if (LimitFloatPrecision <= 12) { 5316 // For floating-point precision of 12: 5317 // 5318 // Log10ofMantissa = 5319 // -0.64831180f + 5320 // (0.91751397f + 5321 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5322 // 5323 // error 0.00019228036, which is better than 12 bits 5324 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5325 getF32Constant(DAG, 0x3d431f31, dl)); 5326 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5327 getF32Constant(DAG, 0x3ea21fb2, dl)); 5328 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5329 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5330 getF32Constant(DAG, 0x3f6ae232, dl)); 5331 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5332 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5333 getF32Constant(DAG, 0x3f25f7c3, dl)); 5334 } else { // LimitFloatPrecision <= 18 5335 // For floating-point precision of 18: 5336 // 5337 // Log10ofMantissa = 5338 // -0.84299375f + 5339 // (1.5327582f + 5340 // (-1.0688956f + 5341 // (0.49102474f + 5342 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5343 // 5344 // error 0.0000037995730, which is better than 18 bits 5345 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5346 getF32Constant(DAG, 0x3c5d51ce, dl)); 5347 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5348 getF32Constant(DAG, 0x3e00685a, dl)); 5349 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5350 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5351 getF32Constant(DAG, 0x3efb6798, dl)); 5352 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5353 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5354 getF32Constant(DAG, 0x3f88d192, dl)); 5355 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5356 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5357 getF32Constant(DAG, 0x3fc4316c, dl)); 5358 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5359 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5360 getF32Constant(DAG, 0x3f57ce70, dl)); 5361 } 5362 5363 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5364 } 5365 5366 // No special expansion. 5367 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5368 } 5369 5370 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5371 /// limited-precision mode. 5372 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5373 const TargetLowering &TLI, SDNodeFlags Flags) { 5374 if (Op.getValueType() == MVT::f32 && 5375 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5376 return getLimitedPrecisionExp2(Op, dl, DAG); 5377 5378 // No special expansion. 5379 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5380 } 5381 5382 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5383 /// limited-precision mode with x == 10.0f. 5384 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5385 SelectionDAG &DAG, const TargetLowering &TLI, 5386 SDNodeFlags Flags) { 5387 bool IsExp10 = false; 5388 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5389 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5390 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5391 APFloat Ten(10.0f); 5392 IsExp10 = LHSC->isExactlyValue(Ten); 5393 } 5394 } 5395 5396 // TODO: What fast-math-flags should be set on the FMUL node? 5397 if (IsExp10) { 5398 // Put the exponent in the right bit position for later addition to the 5399 // final result: 5400 // 5401 // #define LOG2OF10 3.3219281f 5402 // t0 = Op * LOG2OF10; 5403 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5404 getF32Constant(DAG, 0x40549a78, dl)); 5405 return getLimitedPrecisionExp2(t0, dl, DAG); 5406 } 5407 5408 // No special expansion. 5409 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5410 } 5411 5412 /// ExpandPowI - Expand a llvm.powi intrinsic. 5413 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5414 SelectionDAG &DAG) { 5415 // If RHS is a constant, we can expand this out to a multiplication tree if 5416 // it's beneficial on the target, otherwise we end up lowering to a call to 5417 // __powidf2 (for example). 5418 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5419 unsigned Val = RHSC->getSExtValue(); 5420 5421 // powi(x, 0) -> 1.0 5422 if (Val == 0) 5423 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5424 5425 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5426 Val, DAG.shouldOptForSize())) { 5427 // Get the exponent as a positive value. 5428 if ((int)Val < 0) 5429 Val = -Val; 5430 // We use the simple binary decomposition method to generate the multiply 5431 // sequence. There are more optimal ways to do this (for example, 5432 // powi(x,15) generates one more multiply than it should), but this has 5433 // the benefit of being both really simple and much better than a libcall. 5434 SDValue Res; // Logically starts equal to 1.0 5435 SDValue CurSquare = LHS; 5436 // TODO: Intrinsics should have fast-math-flags that propagate to these 5437 // nodes. 5438 while (Val) { 5439 if (Val & 1) { 5440 if (Res.getNode()) 5441 Res = 5442 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5443 else 5444 Res = CurSquare; // 1.0*CurSquare. 5445 } 5446 5447 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5448 CurSquare, CurSquare); 5449 Val >>= 1; 5450 } 5451 5452 // If the original was negative, invert the result, producing 1/(x*x*x). 5453 if (RHSC->getSExtValue() < 0) 5454 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5455 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5456 return Res; 5457 } 5458 } 5459 5460 // Otherwise, expand to a libcall. 5461 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5462 } 5463 5464 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5465 SDValue LHS, SDValue RHS, SDValue Scale, 5466 SelectionDAG &DAG, const TargetLowering &TLI) { 5467 EVT VT = LHS.getValueType(); 5468 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5469 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5470 LLVMContext &Ctx = *DAG.getContext(); 5471 5472 // If the type is legal but the operation isn't, this node might survive all 5473 // the way to operation legalization. If we end up there and we do not have 5474 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5475 // node. 5476 5477 // Coax the legalizer into expanding the node during type legalization instead 5478 // by bumping the size by one bit. This will force it to Promote, enabling the 5479 // early expansion and avoiding the need to expand later. 5480 5481 // We don't have to do this if Scale is 0; that can always be expanded, unless 5482 // it's a saturating signed operation. Those can experience true integer 5483 // division overflow, a case which we must avoid. 5484 5485 // FIXME: We wouldn't have to do this (or any of the early 5486 // expansion/promotion) if it was possible to expand a libcall of an 5487 // illegal type during operation legalization. But it's not, so things 5488 // get a bit hacky. 5489 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5490 if ((ScaleInt > 0 || (Saturating && Signed)) && 5491 (TLI.isTypeLegal(VT) || 5492 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5493 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5494 Opcode, VT, ScaleInt); 5495 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5496 EVT PromVT; 5497 if (VT.isScalarInteger()) 5498 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5499 else if (VT.isVector()) { 5500 PromVT = VT.getVectorElementType(); 5501 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5502 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5503 } else 5504 llvm_unreachable("Wrong VT for DIVFIX?"); 5505 if (Signed) { 5506 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5507 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5508 } else { 5509 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5510 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5511 } 5512 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5513 // For saturating operations, we need to shift up the LHS to get the 5514 // proper saturation width, and then shift down again afterwards. 5515 if (Saturating) 5516 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5517 DAG.getConstant(1, DL, ShiftTy)); 5518 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5519 if (Saturating) 5520 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5521 DAG.getConstant(1, DL, ShiftTy)); 5522 return DAG.getZExtOrTrunc(Res, DL, VT); 5523 } 5524 } 5525 5526 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5527 } 5528 5529 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5530 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5531 static void 5532 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5533 const SDValue &N) { 5534 switch (N.getOpcode()) { 5535 case ISD::CopyFromReg: { 5536 SDValue Op = N.getOperand(1); 5537 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5538 Op.getValueType().getSizeInBits()); 5539 return; 5540 } 5541 case ISD::BITCAST: 5542 case ISD::AssertZext: 5543 case ISD::AssertSext: 5544 case ISD::TRUNCATE: 5545 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5546 return; 5547 case ISD::BUILD_PAIR: 5548 case ISD::BUILD_VECTOR: 5549 case ISD::CONCAT_VECTORS: 5550 for (SDValue Op : N->op_values()) 5551 getUnderlyingArgRegs(Regs, Op); 5552 return; 5553 default: 5554 return; 5555 } 5556 } 5557 5558 /// If the DbgValueInst is a dbg_value of a function argument, create the 5559 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5560 /// instruction selection, they will be inserted to the entry BB. 5561 /// We don't currently support this for variadic dbg_values, as they shouldn't 5562 /// appear for function arguments or in the prologue. 5563 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5564 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5565 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5566 const Argument *Arg = dyn_cast<Argument>(V); 5567 if (!Arg) 5568 return false; 5569 5570 MachineFunction &MF = DAG.getMachineFunction(); 5571 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5572 5573 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5574 // we've been asked to pursue. 5575 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5576 bool Indirect) { 5577 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5578 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5579 // pointing at the VReg, which will be patched up later. 5580 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5581 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5582 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5583 /* isKill */ false, /* isDead */ false, 5584 /* isUndef */ false, /* isEarlyClobber */ false, 5585 /* SubReg */ 0, /* isDebug */ true)}); 5586 5587 auto *NewDIExpr = FragExpr; 5588 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5589 // the DIExpression. 5590 if (Indirect) 5591 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5592 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5593 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5594 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5595 } else { 5596 // Create a completely standard DBG_VALUE. 5597 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5598 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5599 } 5600 }; 5601 5602 if (Kind == FuncArgumentDbgValueKind::Value) { 5603 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5604 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5605 // the entry block. 5606 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5607 if (!IsInEntryBlock) 5608 return false; 5609 5610 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5611 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5612 // variable that also is a param. 5613 // 5614 // Although, if we are at the top of the entry block already, we can still 5615 // emit using ArgDbgValue. This might catch some situations when the 5616 // dbg.value refers to an argument that isn't used in the entry block, so 5617 // any CopyToReg node would be optimized out and the only way to express 5618 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5619 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5620 // we should only emit as ArgDbgValue if the Variable is an argument to the 5621 // current function, and the dbg.value intrinsic is found in the entry 5622 // block. 5623 bool VariableIsFunctionInputArg = Variable->isParameter() && 5624 !DL->getInlinedAt(); 5625 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5626 if (!IsInPrologue && !VariableIsFunctionInputArg) 5627 return false; 5628 5629 // Here we assume that a function argument on IR level only can be used to 5630 // describe one input parameter on source level. If we for example have 5631 // source code like this 5632 // 5633 // struct A { long x, y; }; 5634 // void foo(struct A a, long b) { 5635 // ... 5636 // b = a.x; 5637 // ... 5638 // } 5639 // 5640 // and IR like this 5641 // 5642 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5643 // entry: 5644 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5645 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5646 // call void @llvm.dbg.value(metadata i32 %b, "b", 5647 // ... 5648 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5649 // ... 5650 // 5651 // then the last dbg.value is describing a parameter "b" using a value that 5652 // is an argument. But since we already has used %a1 to describe a parameter 5653 // we should not handle that last dbg.value here (that would result in an 5654 // incorrect hoisting of the DBG_VALUE to the function entry). 5655 // Notice that we allow one dbg.value per IR level argument, to accommodate 5656 // for the situation with fragments above. 5657 if (VariableIsFunctionInputArg) { 5658 unsigned ArgNo = Arg->getArgNo(); 5659 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5660 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5661 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5662 return false; 5663 FuncInfo.DescribedArgs.set(ArgNo); 5664 } 5665 } 5666 5667 bool IsIndirect = false; 5668 std::optional<MachineOperand> Op; 5669 // Some arguments' frame index is recorded during argument lowering. 5670 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5671 if (FI != std::numeric_limits<int>::max()) 5672 Op = MachineOperand::CreateFI(FI); 5673 5674 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5675 if (!Op && N.getNode()) { 5676 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5677 Register Reg; 5678 if (ArgRegsAndSizes.size() == 1) 5679 Reg = ArgRegsAndSizes.front().first; 5680 5681 if (Reg && Reg.isVirtual()) { 5682 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5683 Register PR = RegInfo.getLiveInPhysReg(Reg); 5684 if (PR) 5685 Reg = PR; 5686 } 5687 if (Reg) { 5688 Op = MachineOperand::CreateReg(Reg, false); 5689 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5690 } 5691 } 5692 5693 if (!Op && N.getNode()) { 5694 // Check if frame index is available. 5695 SDValue LCandidate = peekThroughBitcasts(N); 5696 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5697 if (FrameIndexSDNode *FINode = 5698 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5699 Op = MachineOperand::CreateFI(FINode->getIndex()); 5700 } 5701 5702 if (!Op) { 5703 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5704 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5705 SplitRegs) { 5706 unsigned Offset = 0; 5707 for (const auto &RegAndSize : SplitRegs) { 5708 // If the expression is already a fragment, the current register 5709 // offset+size might extend beyond the fragment. In this case, only 5710 // the register bits that are inside the fragment are relevant. 5711 int RegFragmentSizeInBits = RegAndSize.second; 5712 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5713 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5714 // The register is entirely outside the expression fragment, 5715 // so is irrelevant for debug info. 5716 if (Offset >= ExprFragmentSizeInBits) 5717 break; 5718 // The register is partially outside the expression fragment, only 5719 // the low bits within the fragment are relevant for debug info. 5720 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5721 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5722 } 5723 } 5724 5725 auto FragmentExpr = DIExpression::createFragmentExpression( 5726 Expr, Offset, RegFragmentSizeInBits); 5727 Offset += RegAndSize.second; 5728 // If a valid fragment expression cannot be created, the variable's 5729 // correct value cannot be determined and so it is set as Undef. 5730 if (!FragmentExpr) { 5731 SDDbgValue *SDV = DAG.getConstantDbgValue( 5732 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5733 DAG.AddDbgValue(SDV, false); 5734 continue; 5735 } 5736 MachineInstr *NewMI = 5737 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5738 Kind != FuncArgumentDbgValueKind::Value); 5739 FuncInfo.ArgDbgValues.push_back(NewMI); 5740 } 5741 }; 5742 5743 // Check if ValueMap has reg number. 5744 DenseMap<const Value *, Register>::const_iterator 5745 VMI = FuncInfo.ValueMap.find(V); 5746 if (VMI != FuncInfo.ValueMap.end()) { 5747 const auto &TLI = DAG.getTargetLoweringInfo(); 5748 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5749 V->getType(), std::nullopt); 5750 if (RFV.occupiesMultipleRegs()) { 5751 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5752 return true; 5753 } 5754 5755 Op = MachineOperand::CreateReg(VMI->second, false); 5756 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5757 } else if (ArgRegsAndSizes.size() > 1) { 5758 // This was split due to the calling convention, and no virtual register 5759 // mapping exists for the value. 5760 splitMultiRegDbgValue(ArgRegsAndSizes); 5761 return true; 5762 } 5763 } 5764 5765 if (!Op) 5766 return false; 5767 5768 assert(Variable->isValidLocationForIntrinsic(DL) && 5769 "Expected inlined-at fields to agree"); 5770 MachineInstr *NewMI = nullptr; 5771 5772 if (Op->isReg()) 5773 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5774 else 5775 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5776 Variable, Expr); 5777 5778 // Otherwise, use ArgDbgValues. 5779 FuncInfo.ArgDbgValues.push_back(NewMI); 5780 return true; 5781 } 5782 5783 /// Return the appropriate SDDbgValue based on N. 5784 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5785 DILocalVariable *Variable, 5786 DIExpression *Expr, 5787 const DebugLoc &dl, 5788 unsigned DbgSDNodeOrder) { 5789 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5790 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5791 // stack slot locations. 5792 // 5793 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5794 // debug values here after optimization: 5795 // 5796 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5797 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5798 // 5799 // Both describe the direct values of their associated variables. 5800 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5801 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5802 } 5803 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5804 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5805 } 5806 5807 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5808 switch (Intrinsic) { 5809 case Intrinsic::smul_fix: 5810 return ISD::SMULFIX; 5811 case Intrinsic::umul_fix: 5812 return ISD::UMULFIX; 5813 case Intrinsic::smul_fix_sat: 5814 return ISD::SMULFIXSAT; 5815 case Intrinsic::umul_fix_sat: 5816 return ISD::UMULFIXSAT; 5817 case Intrinsic::sdiv_fix: 5818 return ISD::SDIVFIX; 5819 case Intrinsic::udiv_fix: 5820 return ISD::UDIVFIX; 5821 case Intrinsic::sdiv_fix_sat: 5822 return ISD::SDIVFIXSAT; 5823 case Intrinsic::udiv_fix_sat: 5824 return ISD::UDIVFIXSAT; 5825 default: 5826 llvm_unreachable("Unhandled fixed point intrinsic"); 5827 } 5828 } 5829 5830 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5831 const char *FunctionName) { 5832 assert(FunctionName && "FunctionName must not be nullptr"); 5833 SDValue Callee = DAG.getExternalSymbol( 5834 FunctionName, 5835 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5836 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5837 } 5838 5839 /// Given a @llvm.call.preallocated.setup, return the corresponding 5840 /// preallocated call. 5841 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5842 assert(cast<CallBase>(PreallocatedSetup) 5843 ->getCalledFunction() 5844 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5845 "expected call_preallocated_setup Value"); 5846 for (const auto *U : PreallocatedSetup->users()) { 5847 auto *UseCall = cast<CallBase>(U); 5848 const Function *Fn = UseCall->getCalledFunction(); 5849 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5850 return UseCall; 5851 } 5852 } 5853 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5854 } 5855 5856 /// Lower the call to the specified intrinsic function. 5857 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5858 unsigned Intrinsic) { 5859 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5860 SDLoc sdl = getCurSDLoc(); 5861 DebugLoc dl = getCurDebugLoc(); 5862 SDValue Res; 5863 5864 SDNodeFlags Flags; 5865 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5866 Flags.copyFMF(*FPOp); 5867 5868 switch (Intrinsic) { 5869 default: 5870 // By default, turn this into a target intrinsic node. 5871 visitTargetIntrinsic(I, Intrinsic); 5872 return; 5873 case Intrinsic::vscale: { 5874 match(&I, m_VScale(DAG.getDataLayout())); 5875 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5876 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5877 return; 5878 } 5879 case Intrinsic::vastart: visitVAStart(I); return; 5880 case Intrinsic::vaend: visitVAEnd(I); return; 5881 case Intrinsic::vacopy: visitVACopy(I); return; 5882 case Intrinsic::returnaddress: 5883 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5884 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5885 getValue(I.getArgOperand(0)))); 5886 return; 5887 case Intrinsic::addressofreturnaddress: 5888 setValue(&I, 5889 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5890 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5891 return; 5892 case Intrinsic::sponentry: 5893 setValue(&I, 5894 DAG.getNode(ISD::SPONENTRY, sdl, 5895 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5896 return; 5897 case Intrinsic::frameaddress: 5898 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5899 TLI.getFrameIndexTy(DAG.getDataLayout()), 5900 getValue(I.getArgOperand(0)))); 5901 return; 5902 case Intrinsic::read_volatile_register: 5903 case Intrinsic::read_register: { 5904 Value *Reg = I.getArgOperand(0); 5905 SDValue Chain = getRoot(); 5906 SDValue RegName = 5907 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5908 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5909 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5910 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5911 setValue(&I, Res); 5912 DAG.setRoot(Res.getValue(1)); 5913 return; 5914 } 5915 case Intrinsic::write_register: { 5916 Value *Reg = I.getArgOperand(0); 5917 Value *RegValue = I.getArgOperand(1); 5918 SDValue Chain = getRoot(); 5919 SDValue RegName = 5920 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5921 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5922 RegName, getValue(RegValue))); 5923 return; 5924 } 5925 case Intrinsic::memcpy: { 5926 const auto &MCI = cast<MemCpyInst>(I); 5927 SDValue Op1 = getValue(I.getArgOperand(0)); 5928 SDValue Op2 = getValue(I.getArgOperand(1)); 5929 SDValue Op3 = getValue(I.getArgOperand(2)); 5930 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5931 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5932 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5933 Align Alignment = std::min(DstAlign, SrcAlign); 5934 bool isVol = MCI.isVolatile(); 5935 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5936 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5937 // node. 5938 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5939 SDValue MC = DAG.getMemcpy( 5940 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5941 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 5942 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5943 updateDAGForMaybeTailCall(MC); 5944 setValue(&I, MC); 5945 return; 5946 } 5947 case Intrinsic::memcpy_inline: { 5948 const auto &MCI = cast<MemCpyInlineInst>(I); 5949 SDValue Dst = getValue(I.getArgOperand(0)); 5950 SDValue Src = getValue(I.getArgOperand(1)); 5951 SDValue Size = getValue(I.getArgOperand(2)); 5952 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5953 // @llvm.memcpy.inline 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 MC = DAG.getMemcpy( 5962 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5963 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 5964 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 5965 updateDAGForMaybeTailCall(MC); 5966 setValue(&I, MC); 5967 return; 5968 } 5969 case Intrinsic::memset: { 5970 const auto &MSI = cast<MemSetInst>(I); 5971 SDValue Op1 = getValue(I.getArgOperand(0)); 5972 SDValue Op2 = getValue(I.getArgOperand(1)); 5973 SDValue Op3 = getValue(I.getArgOperand(2)); 5974 // @llvm.memset defines 0 and 1 to both mean no alignment. 5975 Align Alignment = MSI.getDestAlign().valueOrOne(); 5976 bool isVol = MSI.isVolatile(); 5977 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5978 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5979 SDValue MS = DAG.getMemset( 5980 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 5981 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 5982 updateDAGForMaybeTailCall(MS); 5983 setValue(&I, MS); 5984 return; 5985 } 5986 case Intrinsic::memset_inline: { 5987 const auto &MSII = cast<MemSetInlineInst>(I); 5988 SDValue Dst = getValue(I.getArgOperand(0)); 5989 SDValue Value = getValue(I.getArgOperand(1)); 5990 SDValue Size = getValue(I.getArgOperand(2)); 5991 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 5992 // @llvm.memset defines 0 and 1 to both mean no alignment. 5993 Align DstAlign = MSII.getDestAlign().valueOrOne(); 5994 bool isVol = MSII.isVolatile(); 5995 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5996 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5997 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 5998 /* AlwaysInline */ true, isTC, 5999 MachinePointerInfo(I.getArgOperand(0)), 6000 I.getAAMetadata()); 6001 updateDAGForMaybeTailCall(MC); 6002 setValue(&I, MC); 6003 return; 6004 } 6005 case Intrinsic::memmove: { 6006 const auto &MMI = cast<MemMoveInst>(I); 6007 SDValue Op1 = getValue(I.getArgOperand(0)); 6008 SDValue Op2 = getValue(I.getArgOperand(1)); 6009 SDValue Op3 = getValue(I.getArgOperand(2)); 6010 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6011 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6012 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6013 Align Alignment = std::min(DstAlign, SrcAlign); 6014 bool isVol = MMI.isVolatile(); 6015 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6016 // FIXME: Support passing different dest/src alignments to the memmove DAG 6017 // node. 6018 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6019 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6020 isTC, MachinePointerInfo(I.getArgOperand(0)), 6021 MachinePointerInfo(I.getArgOperand(1)), 6022 I.getAAMetadata(), AA); 6023 updateDAGForMaybeTailCall(MM); 6024 setValue(&I, MM); 6025 return; 6026 } 6027 case Intrinsic::memcpy_element_unordered_atomic: { 6028 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6029 SDValue Dst = getValue(MI.getRawDest()); 6030 SDValue Src = getValue(MI.getRawSource()); 6031 SDValue Length = getValue(MI.getLength()); 6032 6033 Type *LengthTy = MI.getLength()->getType(); 6034 unsigned ElemSz = MI.getElementSizeInBytes(); 6035 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6036 SDValue MC = 6037 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6038 isTC, MachinePointerInfo(MI.getRawDest()), 6039 MachinePointerInfo(MI.getRawSource())); 6040 updateDAGForMaybeTailCall(MC); 6041 setValue(&I, MC); 6042 return; 6043 } 6044 case Intrinsic::memmove_element_unordered_atomic: { 6045 auto &MI = cast<AtomicMemMoveInst>(I); 6046 SDValue Dst = getValue(MI.getRawDest()); 6047 SDValue Src = getValue(MI.getRawSource()); 6048 SDValue Length = getValue(MI.getLength()); 6049 6050 Type *LengthTy = MI.getLength()->getType(); 6051 unsigned ElemSz = MI.getElementSizeInBytes(); 6052 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6053 SDValue MC = 6054 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6055 isTC, MachinePointerInfo(MI.getRawDest()), 6056 MachinePointerInfo(MI.getRawSource())); 6057 updateDAGForMaybeTailCall(MC); 6058 setValue(&I, MC); 6059 return; 6060 } 6061 case Intrinsic::memset_element_unordered_atomic: { 6062 auto &MI = cast<AtomicMemSetInst>(I); 6063 SDValue Dst = getValue(MI.getRawDest()); 6064 SDValue Val = getValue(MI.getValue()); 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.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6072 isTC, MachinePointerInfo(MI.getRawDest())); 6073 updateDAGForMaybeTailCall(MC); 6074 setValue(&I, MC); 6075 return; 6076 } 6077 case Intrinsic::call_preallocated_setup: { 6078 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6079 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6080 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6081 getRoot(), SrcValue); 6082 setValue(&I, Res); 6083 DAG.setRoot(Res); 6084 return; 6085 } 6086 case Intrinsic::call_preallocated_arg: { 6087 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6088 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6089 SDValue Ops[3]; 6090 Ops[0] = getRoot(); 6091 Ops[1] = SrcValue; 6092 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6093 MVT::i32); // arg index 6094 SDValue Res = DAG.getNode( 6095 ISD::PREALLOCATED_ARG, sdl, 6096 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6097 setValue(&I, Res); 6098 DAG.setRoot(Res.getValue(1)); 6099 return; 6100 } 6101 case Intrinsic::dbg_addr: 6102 case Intrinsic::dbg_declare: { 6103 // Debug intrinsics are handled seperately in assignment tracking mode. 6104 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent())) 6105 return; 6106 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e. 6107 // they are non-variadic. 6108 const auto &DI = cast<DbgVariableIntrinsic>(I); 6109 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6110 DILocalVariable *Variable = DI.getVariable(); 6111 DIExpression *Expression = DI.getExpression(); 6112 dropDanglingDebugInfo(Variable, Expression); 6113 assert(Variable && "Missing variable"); 6114 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6115 << "\n"); 6116 // Check if address has undef value. 6117 const Value *Address = DI.getVariableLocationOp(0); 6118 if (!Address || isa<UndefValue>(Address) || 6119 (Address->use_empty() && !isa<Argument>(Address))) { 6120 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6121 << " (bad/undef/unused-arg address)\n"); 6122 return; 6123 } 6124 6125 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6126 6127 // Check if this variable can be described by a frame index, typically 6128 // either as a static alloca or a byval parameter. 6129 int FI = std::numeric_limits<int>::max(); 6130 if (const auto *AI = 6131 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 6132 if (AI->isStaticAlloca()) { 6133 auto I = FuncInfo.StaticAllocaMap.find(AI); 6134 if (I != FuncInfo.StaticAllocaMap.end()) 6135 FI = I->second; 6136 } 6137 } else if (const auto *Arg = dyn_cast<Argument>( 6138 Address->stripInBoundsConstantOffsets())) { 6139 FI = FuncInfo.getArgumentFrameIndex(Arg); 6140 } 6141 6142 // llvm.dbg.addr is control dependent and always generates indirect 6143 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 6144 // the MachineFunction variable table. 6145 if (FI != std::numeric_limits<int>::max()) { 6146 if (Intrinsic == Intrinsic::dbg_addr) { 6147 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 6148 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true, 6149 dl, SDNodeOrder); 6150 DAG.AddDbgValue(SDV, isParameter); 6151 } else { 6152 LLVM_DEBUG(dbgs() << "Skipping " << DI 6153 << " (variable info stashed in MF side table)\n"); 6154 } 6155 return; 6156 } 6157 6158 SDValue &N = NodeMap[Address]; 6159 if (!N.getNode() && isa<Argument>(Address)) 6160 // Check unused arguments map. 6161 N = UnusedArgNodeMap[Address]; 6162 SDDbgValue *SDV; 6163 if (N.getNode()) { 6164 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6165 Address = BCI->getOperand(0); 6166 // Parameters are handled specially. 6167 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6168 if (isParameter && FINode) { 6169 // Byval parameter. We have a frame index at this point. 6170 SDV = 6171 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6172 /*IsIndirect*/ true, dl, SDNodeOrder); 6173 } else if (isa<Argument>(Address)) { 6174 // Address is an argument, so try to emit its dbg value using 6175 // virtual register info from the FuncInfo.ValueMap. 6176 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6177 FuncArgumentDbgValueKind::Declare, N); 6178 return; 6179 } else { 6180 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6181 true, dl, SDNodeOrder); 6182 } 6183 DAG.AddDbgValue(SDV, isParameter); 6184 } else { 6185 // If Address is an argument then try to emit its dbg value using 6186 // virtual register info from the FuncInfo.ValueMap. 6187 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6188 FuncArgumentDbgValueKind::Declare, N)) { 6189 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6190 << " (could not emit func-arg dbg_value)\n"); 6191 } 6192 } 6193 return; 6194 } 6195 case Intrinsic::dbg_label: { 6196 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6197 DILabel *Label = DI.getLabel(); 6198 assert(Label && "Missing label"); 6199 6200 SDDbgLabel *SDV; 6201 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6202 DAG.AddDbgLabel(SDV); 6203 return; 6204 } 6205 case Intrinsic::dbg_assign: { 6206 // Debug intrinsics are handled seperately in assignment tracking mode. 6207 assert(isAssignmentTrackingEnabled(*I.getFunction()->getParent()) && 6208 "expected assignment tracking to be enabled"); 6209 return; 6210 } 6211 case Intrinsic::dbg_value: { 6212 // Debug intrinsics are handled seperately in assignment tracking mode. 6213 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent())) 6214 return; 6215 const DbgValueInst &DI = cast<DbgValueInst>(I); 6216 assert(DI.getVariable() && "Missing variable"); 6217 6218 DILocalVariable *Variable = DI.getVariable(); 6219 DIExpression *Expression = DI.getExpression(); 6220 dropDanglingDebugInfo(Variable, Expression); 6221 SmallVector<Value *, 4> Values(DI.getValues()); 6222 if (Values.empty()) 6223 return; 6224 6225 if (llvm::is_contained(Values, nullptr)) 6226 return; 6227 6228 bool IsVariadic = DI.hasArgList(); 6229 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6230 SDNodeOrder, IsVariadic)) 6231 addDanglingDebugInfo(&DI, SDNodeOrder); 6232 return; 6233 } 6234 6235 case Intrinsic::eh_typeid_for: { 6236 // Find the type id for the given typeinfo. 6237 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6238 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6239 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6240 setValue(&I, Res); 6241 return; 6242 } 6243 6244 case Intrinsic::eh_return_i32: 6245 case Intrinsic::eh_return_i64: 6246 DAG.getMachineFunction().setCallsEHReturn(true); 6247 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6248 MVT::Other, 6249 getControlRoot(), 6250 getValue(I.getArgOperand(0)), 6251 getValue(I.getArgOperand(1)))); 6252 return; 6253 case Intrinsic::eh_unwind_init: 6254 DAG.getMachineFunction().setCallsUnwindInit(true); 6255 return; 6256 case Intrinsic::eh_dwarf_cfa: 6257 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6258 TLI.getPointerTy(DAG.getDataLayout()), 6259 getValue(I.getArgOperand(0)))); 6260 return; 6261 case Intrinsic::eh_sjlj_callsite: { 6262 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6263 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6264 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6265 6266 MMI.setCurrentCallSite(CI->getZExtValue()); 6267 return; 6268 } 6269 case Intrinsic::eh_sjlj_functioncontext: { 6270 // Get and store the index of the function context. 6271 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6272 AllocaInst *FnCtx = 6273 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6274 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6275 MFI.setFunctionContextIndex(FI); 6276 return; 6277 } 6278 case Intrinsic::eh_sjlj_setjmp: { 6279 SDValue Ops[2]; 6280 Ops[0] = getRoot(); 6281 Ops[1] = getValue(I.getArgOperand(0)); 6282 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6283 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6284 setValue(&I, Op.getValue(0)); 6285 DAG.setRoot(Op.getValue(1)); 6286 return; 6287 } 6288 case Intrinsic::eh_sjlj_longjmp: 6289 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6290 getRoot(), getValue(I.getArgOperand(0)))); 6291 return; 6292 case Intrinsic::eh_sjlj_setup_dispatch: 6293 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6294 getRoot())); 6295 return; 6296 case Intrinsic::masked_gather: 6297 visitMaskedGather(I); 6298 return; 6299 case Intrinsic::masked_load: 6300 visitMaskedLoad(I); 6301 return; 6302 case Intrinsic::masked_scatter: 6303 visitMaskedScatter(I); 6304 return; 6305 case Intrinsic::masked_store: 6306 visitMaskedStore(I); 6307 return; 6308 case Intrinsic::masked_expandload: 6309 visitMaskedLoad(I, true /* IsExpanding */); 6310 return; 6311 case Intrinsic::masked_compressstore: 6312 visitMaskedStore(I, true /* IsCompressing */); 6313 return; 6314 case Intrinsic::powi: 6315 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6316 getValue(I.getArgOperand(1)), DAG)); 6317 return; 6318 case Intrinsic::log: 6319 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6320 return; 6321 case Intrinsic::log2: 6322 setValue(&I, 6323 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6324 return; 6325 case Intrinsic::log10: 6326 setValue(&I, 6327 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6328 return; 6329 case Intrinsic::exp: 6330 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6331 return; 6332 case Intrinsic::exp2: 6333 setValue(&I, 6334 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6335 return; 6336 case Intrinsic::pow: 6337 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6338 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6339 return; 6340 case Intrinsic::sqrt: 6341 case Intrinsic::fabs: 6342 case Intrinsic::sin: 6343 case Intrinsic::cos: 6344 case Intrinsic::floor: 6345 case Intrinsic::ceil: 6346 case Intrinsic::trunc: 6347 case Intrinsic::rint: 6348 case Intrinsic::nearbyint: 6349 case Intrinsic::round: 6350 case Intrinsic::roundeven: 6351 case Intrinsic::canonicalize: { 6352 unsigned Opcode; 6353 switch (Intrinsic) { 6354 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6355 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6356 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6357 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6358 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6359 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6360 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6361 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6362 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6363 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6364 case Intrinsic::round: Opcode = ISD::FROUND; break; 6365 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6366 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6367 } 6368 6369 setValue(&I, DAG.getNode(Opcode, sdl, 6370 getValue(I.getArgOperand(0)).getValueType(), 6371 getValue(I.getArgOperand(0)), Flags)); 6372 return; 6373 } 6374 case Intrinsic::lround: 6375 case Intrinsic::llround: 6376 case Intrinsic::lrint: 6377 case Intrinsic::llrint: { 6378 unsigned Opcode; 6379 switch (Intrinsic) { 6380 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6381 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6382 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6383 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6384 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6385 } 6386 6387 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6388 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6389 getValue(I.getArgOperand(0)))); 6390 return; 6391 } 6392 case Intrinsic::minnum: 6393 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6394 getValue(I.getArgOperand(0)).getValueType(), 6395 getValue(I.getArgOperand(0)), 6396 getValue(I.getArgOperand(1)), Flags)); 6397 return; 6398 case Intrinsic::maxnum: 6399 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6400 getValue(I.getArgOperand(0)).getValueType(), 6401 getValue(I.getArgOperand(0)), 6402 getValue(I.getArgOperand(1)), Flags)); 6403 return; 6404 case Intrinsic::minimum: 6405 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6406 getValue(I.getArgOperand(0)).getValueType(), 6407 getValue(I.getArgOperand(0)), 6408 getValue(I.getArgOperand(1)), Flags)); 6409 return; 6410 case Intrinsic::maximum: 6411 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6412 getValue(I.getArgOperand(0)).getValueType(), 6413 getValue(I.getArgOperand(0)), 6414 getValue(I.getArgOperand(1)), Flags)); 6415 return; 6416 case Intrinsic::copysign: 6417 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6418 getValue(I.getArgOperand(0)).getValueType(), 6419 getValue(I.getArgOperand(0)), 6420 getValue(I.getArgOperand(1)), Flags)); 6421 return; 6422 case Intrinsic::arithmetic_fence: { 6423 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6424 getValue(I.getArgOperand(0)).getValueType(), 6425 getValue(I.getArgOperand(0)), Flags)); 6426 return; 6427 } 6428 case Intrinsic::fma: 6429 setValue(&I, DAG.getNode( 6430 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6431 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6432 getValue(I.getArgOperand(2)), Flags)); 6433 return; 6434 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6435 case Intrinsic::INTRINSIC: 6436 #include "llvm/IR/ConstrainedOps.def" 6437 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6438 return; 6439 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6440 #include "llvm/IR/VPIntrinsics.def" 6441 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6442 return; 6443 case Intrinsic::fptrunc_round: { 6444 // Get the last argument, the metadata and convert it to an integer in the 6445 // call 6446 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6447 std::optional<RoundingMode> RoundMode = 6448 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6449 6450 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6451 6452 // Propagate fast-math-flags from IR to node(s). 6453 SDNodeFlags Flags; 6454 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6455 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6456 6457 SDValue Result; 6458 Result = DAG.getNode( 6459 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6460 DAG.getTargetConstant((int)*RoundMode, sdl, 6461 TLI.getPointerTy(DAG.getDataLayout()))); 6462 setValue(&I, Result); 6463 6464 return; 6465 } 6466 case Intrinsic::fmuladd: { 6467 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6468 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6469 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6470 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6471 getValue(I.getArgOperand(0)).getValueType(), 6472 getValue(I.getArgOperand(0)), 6473 getValue(I.getArgOperand(1)), 6474 getValue(I.getArgOperand(2)), Flags)); 6475 } else { 6476 // TODO: Intrinsic calls should have fast-math-flags. 6477 SDValue Mul = DAG.getNode( 6478 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6479 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6480 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6481 getValue(I.getArgOperand(0)).getValueType(), 6482 Mul, getValue(I.getArgOperand(2)), Flags); 6483 setValue(&I, Add); 6484 } 6485 return; 6486 } 6487 case Intrinsic::convert_to_fp16: 6488 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6489 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6490 getValue(I.getArgOperand(0)), 6491 DAG.getTargetConstant(0, sdl, 6492 MVT::i32)))); 6493 return; 6494 case Intrinsic::convert_from_fp16: 6495 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6496 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6497 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6498 getValue(I.getArgOperand(0))))); 6499 return; 6500 case Intrinsic::fptosi_sat: { 6501 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6502 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6503 getValue(I.getArgOperand(0)), 6504 DAG.getValueType(VT.getScalarType()))); 6505 return; 6506 } 6507 case Intrinsic::fptoui_sat: { 6508 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6509 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6510 getValue(I.getArgOperand(0)), 6511 DAG.getValueType(VT.getScalarType()))); 6512 return; 6513 } 6514 case Intrinsic::set_rounding: 6515 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6516 {getRoot(), getValue(I.getArgOperand(0))}); 6517 setValue(&I, Res); 6518 DAG.setRoot(Res.getValue(0)); 6519 return; 6520 case Intrinsic::is_fpclass: { 6521 const DataLayout DLayout = DAG.getDataLayout(); 6522 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6523 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6524 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6525 MachineFunction &MF = DAG.getMachineFunction(); 6526 const Function &F = MF.getFunction(); 6527 SDValue Op = getValue(I.getArgOperand(0)); 6528 SDNodeFlags Flags; 6529 Flags.setNoFPExcept( 6530 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6531 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6532 // expansion can use illegal types. Making expansion early allows 6533 // legalizing these types prior to selection. 6534 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6535 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6536 setValue(&I, Result); 6537 return; 6538 } 6539 6540 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6541 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6542 setValue(&I, V); 6543 return; 6544 } 6545 case Intrinsic::pcmarker: { 6546 SDValue Tmp = getValue(I.getArgOperand(0)); 6547 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6548 return; 6549 } 6550 case Intrinsic::readcyclecounter: { 6551 SDValue Op = getRoot(); 6552 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6553 DAG.getVTList(MVT::i64, MVT::Other), Op); 6554 setValue(&I, Res); 6555 DAG.setRoot(Res.getValue(1)); 6556 return; 6557 } 6558 case Intrinsic::bitreverse: 6559 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6560 getValue(I.getArgOperand(0)).getValueType(), 6561 getValue(I.getArgOperand(0)))); 6562 return; 6563 case Intrinsic::bswap: 6564 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6565 getValue(I.getArgOperand(0)).getValueType(), 6566 getValue(I.getArgOperand(0)))); 6567 return; 6568 case Intrinsic::cttz: { 6569 SDValue Arg = getValue(I.getArgOperand(0)); 6570 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6571 EVT Ty = Arg.getValueType(); 6572 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6573 sdl, Ty, Arg)); 6574 return; 6575 } 6576 case Intrinsic::ctlz: { 6577 SDValue Arg = getValue(I.getArgOperand(0)); 6578 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6579 EVT Ty = Arg.getValueType(); 6580 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6581 sdl, Ty, Arg)); 6582 return; 6583 } 6584 case Intrinsic::ctpop: { 6585 SDValue Arg = getValue(I.getArgOperand(0)); 6586 EVT Ty = Arg.getValueType(); 6587 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6588 return; 6589 } 6590 case Intrinsic::fshl: 6591 case Intrinsic::fshr: { 6592 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6593 SDValue X = getValue(I.getArgOperand(0)); 6594 SDValue Y = getValue(I.getArgOperand(1)); 6595 SDValue Z = getValue(I.getArgOperand(2)); 6596 EVT VT = X.getValueType(); 6597 6598 if (X == Y) { 6599 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6600 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6601 } else { 6602 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6603 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6604 } 6605 return; 6606 } 6607 case Intrinsic::sadd_sat: { 6608 SDValue Op1 = getValue(I.getArgOperand(0)); 6609 SDValue Op2 = getValue(I.getArgOperand(1)); 6610 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6611 return; 6612 } 6613 case Intrinsic::uadd_sat: { 6614 SDValue Op1 = getValue(I.getArgOperand(0)); 6615 SDValue Op2 = getValue(I.getArgOperand(1)); 6616 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6617 return; 6618 } 6619 case Intrinsic::ssub_sat: { 6620 SDValue Op1 = getValue(I.getArgOperand(0)); 6621 SDValue Op2 = getValue(I.getArgOperand(1)); 6622 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6623 return; 6624 } 6625 case Intrinsic::usub_sat: { 6626 SDValue Op1 = getValue(I.getArgOperand(0)); 6627 SDValue Op2 = getValue(I.getArgOperand(1)); 6628 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6629 return; 6630 } 6631 case Intrinsic::sshl_sat: { 6632 SDValue Op1 = getValue(I.getArgOperand(0)); 6633 SDValue Op2 = getValue(I.getArgOperand(1)); 6634 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6635 return; 6636 } 6637 case Intrinsic::ushl_sat: { 6638 SDValue Op1 = getValue(I.getArgOperand(0)); 6639 SDValue Op2 = getValue(I.getArgOperand(1)); 6640 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6641 return; 6642 } 6643 case Intrinsic::smul_fix: 6644 case Intrinsic::umul_fix: 6645 case Intrinsic::smul_fix_sat: 6646 case Intrinsic::umul_fix_sat: { 6647 SDValue Op1 = getValue(I.getArgOperand(0)); 6648 SDValue Op2 = getValue(I.getArgOperand(1)); 6649 SDValue Op3 = getValue(I.getArgOperand(2)); 6650 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6651 Op1.getValueType(), Op1, Op2, Op3)); 6652 return; 6653 } 6654 case Intrinsic::sdiv_fix: 6655 case Intrinsic::udiv_fix: 6656 case Intrinsic::sdiv_fix_sat: 6657 case Intrinsic::udiv_fix_sat: { 6658 SDValue Op1 = getValue(I.getArgOperand(0)); 6659 SDValue Op2 = getValue(I.getArgOperand(1)); 6660 SDValue Op3 = getValue(I.getArgOperand(2)); 6661 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6662 Op1, Op2, Op3, DAG, TLI)); 6663 return; 6664 } 6665 case Intrinsic::smax: { 6666 SDValue Op1 = getValue(I.getArgOperand(0)); 6667 SDValue Op2 = getValue(I.getArgOperand(1)); 6668 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6669 return; 6670 } 6671 case Intrinsic::smin: { 6672 SDValue Op1 = getValue(I.getArgOperand(0)); 6673 SDValue Op2 = getValue(I.getArgOperand(1)); 6674 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6675 return; 6676 } 6677 case Intrinsic::umax: { 6678 SDValue Op1 = getValue(I.getArgOperand(0)); 6679 SDValue Op2 = getValue(I.getArgOperand(1)); 6680 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6681 return; 6682 } 6683 case Intrinsic::umin: { 6684 SDValue Op1 = getValue(I.getArgOperand(0)); 6685 SDValue Op2 = getValue(I.getArgOperand(1)); 6686 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6687 return; 6688 } 6689 case Intrinsic::abs: { 6690 // TODO: Preserve "int min is poison" arg in SDAG? 6691 SDValue Op1 = getValue(I.getArgOperand(0)); 6692 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6693 return; 6694 } 6695 case Intrinsic::stacksave: { 6696 SDValue Op = getRoot(); 6697 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6698 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6699 setValue(&I, Res); 6700 DAG.setRoot(Res.getValue(1)); 6701 return; 6702 } 6703 case Intrinsic::stackrestore: 6704 Res = getValue(I.getArgOperand(0)); 6705 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6706 return; 6707 case Intrinsic::get_dynamic_area_offset: { 6708 SDValue Op = getRoot(); 6709 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6710 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6711 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6712 // target. 6713 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6714 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6715 " intrinsic!"); 6716 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6717 Op); 6718 DAG.setRoot(Op); 6719 setValue(&I, Res); 6720 return; 6721 } 6722 case Intrinsic::stackguard: { 6723 MachineFunction &MF = DAG.getMachineFunction(); 6724 const Module &M = *MF.getFunction().getParent(); 6725 SDValue Chain = getRoot(); 6726 if (TLI.useLoadStackGuardNode()) { 6727 Res = getLoadStackGuard(DAG, sdl, Chain); 6728 } else { 6729 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6730 const Value *Global = TLI.getSDagStackGuard(M); 6731 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6732 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6733 MachinePointerInfo(Global, 0), Align, 6734 MachineMemOperand::MOVolatile); 6735 } 6736 if (TLI.useStackGuardXorFP()) 6737 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6738 DAG.setRoot(Chain); 6739 setValue(&I, Res); 6740 return; 6741 } 6742 case Intrinsic::stackprotector: { 6743 // Emit code into the DAG to store the stack guard onto the stack. 6744 MachineFunction &MF = DAG.getMachineFunction(); 6745 MachineFrameInfo &MFI = MF.getFrameInfo(); 6746 SDValue Src, Chain = getRoot(); 6747 6748 if (TLI.useLoadStackGuardNode()) 6749 Src = getLoadStackGuard(DAG, sdl, Chain); 6750 else 6751 Src = getValue(I.getArgOperand(0)); // The guard's value. 6752 6753 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6754 6755 int FI = FuncInfo.StaticAllocaMap[Slot]; 6756 MFI.setStackProtectorIndex(FI); 6757 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6758 6759 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6760 6761 // Store the stack protector onto the stack. 6762 Res = DAG.getStore( 6763 Chain, sdl, Src, FIN, 6764 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6765 MaybeAlign(), MachineMemOperand::MOVolatile); 6766 setValue(&I, Res); 6767 DAG.setRoot(Res); 6768 return; 6769 } 6770 case Intrinsic::objectsize: 6771 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6772 6773 case Intrinsic::is_constant: 6774 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6775 6776 case Intrinsic::annotation: 6777 case Intrinsic::ptr_annotation: 6778 case Intrinsic::launder_invariant_group: 6779 case Intrinsic::strip_invariant_group: 6780 // Drop the intrinsic, but forward the value 6781 setValue(&I, getValue(I.getOperand(0))); 6782 return; 6783 6784 case Intrinsic::assume: 6785 case Intrinsic::experimental_noalias_scope_decl: 6786 case Intrinsic::var_annotation: 6787 case Intrinsic::sideeffect: 6788 // Discard annotate attributes, noalias scope declarations, assumptions, and 6789 // artificial side-effects. 6790 return; 6791 6792 case Intrinsic::codeview_annotation: { 6793 // Emit a label associated with this metadata. 6794 MachineFunction &MF = DAG.getMachineFunction(); 6795 MCSymbol *Label = 6796 MF.getMMI().getContext().createTempSymbol("annotation", true); 6797 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6798 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6799 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6800 DAG.setRoot(Res); 6801 return; 6802 } 6803 6804 case Intrinsic::init_trampoline: { 6805 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6806 6807 SDValue Ops[6]; 6808 Ops[0] = getRoot(); 6809 Ops[1] = getValue(I.getArgOperand(0)); 6810 Ops[2] = getValue(I.getArgOperand(1)); 6811 Ops[3] = getValue(I.getArgOperand(2)); 6812 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6813 Ops[5] = DAG.getSrcValue(F); 6814 6815 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6816 6817 DAG.setRoot(Res); 6818 return; 6819 } 6820 case Intrinsic::adjust_trampoline: 6821 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6822 TLI.getPointerTy(DAG.getDataLayout()), 6823 getValue(I.getArgOperand(0)))); 6824 return; 6825 case Intrinsic::gcroot: { 6826 assert(DAG.getMachineFunction().getFunction().hasGC() && 6827 "only valid in functions with gc specified, enforced by Verifier"); 6828 assert(GFI && "implied by previous"); 6829 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6830 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6831 6832 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6833 GFI->addStackRoot(FI->getIndex(), TypeMap); 6834 return; 6835 } 6836 case Intrinsic::gcread: 6837 case Intrinsic::gcwrite: 6838 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6839 case Intrinsic::get_rounding: 6840 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6841 setValue(&I, Res); 6842 DAG.setRoot(Res.getValue(1)); 6843 return; 6844 6845 case Intrinsic::expect: 6846 // Just replace __builtin_expect(exp, c) with EXP. 6847 setValue(&I, getValue(I.getArgOperand(0))); 6848 return; 6849 6850 case Intrinsic::ubsantrap: 6851 case Intrinsic::debugtrap: 6852 case Intrinsic::trap: { 6853 StringRef TrapFuncName = 6854 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6855 if (TrapFuncName.empty()) { 6856 switch (Intrinsic) { 6857 case Intrinsic::trap: 6858 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6859 break; 6860 case Intrinsic::debugtrap: 6861 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6862 break; 6863 case Intrinsic::ubsantrap: 6864 DAG.setRoot(DAG.getNode( 6865 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6866 DAG.getTargetConstant( 6867 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6868 MVT::i32))); 6869 break; 6870 default: llvm_unreachable("unknown trap intrinsic"); 6871 } 6872 return; 6873 } 6874 TargetLowering::ArgListTy Args; 6875 if (Intrinsic == Intrinsic::ubsantrap) { 6876 Args.push_back(TargetLoweringBase::ArgListEntry()); 6877 Args[0].Val = I.getArgOperand(0); 6878 Args[0].Node = getValue(Args[0].Val); 6879 Args[0].Ty = Args[0].Val->getType(); 6880 } 6881 6882 TargetLowering::CallLoweringInfo CLI(DAG); 6883 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6884 CallingConv::C, I.getType(), 6885 DAG.getExternalSymbol(TrapFuncName.data(), 6886 TLI.getPointerTy(DAG.getDataLayout())), 6887 std::move(Args)); 6888 6889 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6890 DAG.setRoot(Result.second); 6891 return; 6892 } 6893 6894 case Intrinsic::uadd_with_overflow: 6895 case Intrinsic::sadd_with_overflow: 6896 case Intrinsic::usub_with_overflow: 6897 case Intrinsic::ssub_with_overflow: 6898 case Intrinsic::umul_with_overflow: 6899 case Intrinsic::smul_with_overflow: { 6900 ISD::NodeType Op; 6901 switch (Intrinsic) { 6902 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6903 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6904 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6905 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6906 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6907 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6908 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6909 } 6910 SDValue Op1 = getValue(I.getArgOperand(0)); 6911 SDValue Op2 = getValue(I.getArgOperand(1)); 6912 6913 EVT ResultVT = Op1.getValueType(); 6914 EVT OverflowVT = MVT::i1; 6915 if (ResultVT.isVector()) 6916 OverflowVT = EVT::getVectorVT( 6917 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6918 6919 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6920 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6921 return; 6922 } 6923 case Intrinsic::prefetch: { 6924 SDValue Ops[5]; 6925 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6926 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6927 Ops[0] = DAG.getRoot(); 6928 Ops[1] = getValue(I.getArgOperand(0)); 6929 Ops[2] = getValue(I.getArgOperand(1)); 6930 Ops[3] = getValue(I.getArgOperand(2)); 6931 Ops[4] = getValue(I.getArgOperand(3)); 6932 SDValue Result = DAG.getMemIntrinsicNode( 6933 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6934 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6935 /* align */ std::nullopt, Flags); 6936 6937 // Chain the prefetch in parallell with any pending loads, to stay out of 6938 // the way of later optimizations. 6939 PendingLoads.push_back(Result); 6940 Result = getRoot(); 6941 DAG.setRoot(Result); 6942 return; 6943 } 6944 case Intrinsic::lifetime_start: 6945 case Intrinsic::lifetime_end: { 6946 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6947 // Stack coloring is not enabled in O0, discard region information. 6948 if (TM.getOptLevel() == CodeGenOpt::None) 6949 return; 6950 6951 const int64_t ObjectSize = 6952 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6953 Value *const ObjectPtr = I.getArgOperand(1); 6954 SmallVector<const Value *, 4> Allocas; 6955 getUnderlyingObjects(ObjectPtr, Allocas); 6956 6957 for (const Value *Alloca : Allocas) { 6958 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6959 6960 // Could not find an Alloca. 6961 if (!LifetimeObject) 6962 continue; 6963 6964 // First check that the Alloca is static, otherwise it won't have a 6965 // valid frame index. 6966 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6967 if (SI == FuncInfo.StaticAllocaMap.end()) 6968 return; 6969 6970 const int FrameIndex = SI->second; 6971 int64_t Offset; 6972 if (GetPointerBaseWithConstantOffset( 6973 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6974 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6975 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6976 Offset); 6977 DAG.setRoot(Res); 6978 } 6979 return; 6980 } 6981 case Intrinsic::pseudoprobe: { 6982 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6983 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6984 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6985 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6986 DAG.setRoot(Res); 6987 return; 6988 } 6989 case Intrinsic::invariant_start: 6990 // Discard region information. 6991 setValue(&I, 6992 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 6993 return; 6994 case Intrinsic::invariant_end: 6995 // Discard region information. 6996 return; 6997 case Intrinsic::clear_cache: 6998 /// FunctionName may be null. 6999 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7000 lowerCallToExternalSymbol(I, FunctionName); 7001 return; 7002 case Intrinsic::donothing: 7003 case Intrinsic::seh_try_begin: 7004 case Intrinsic::seh_scope_begin: 7005 case Intrinsic::seh_try_end: 7006 case Intrinsic::seh_scope_end: 7007 // ignore 7008 return; 7009 case Intrinsic::experimental_stackmap: 7010 visitStackmap(I); 7011 return; 7012 case Intrinsic::experimental_patchpoint_void: 7013 case Intrinsic::experimental_patchpoint_i64: 7014 visitPatchpoint(I); 7015 return; 7016 case Intrinsic::experimental_gc_statepoint: 7017 LowerStatepoint(cast<GCStatepointInst>(I)); 7018 return; 7019 case Intrinsic::experimental_gc_result: 7020 visitGCResult(cast<GCResultInst>(I)); 7021 return; 7022 case Intrinsic::experimental_gc_relocate: 7023 visitGCRelocate(cast<GCRelocateInst>(I)); 7024 return; 7025 case Intrinsic::instrprof_cover: 7026 llvm_unreachable("instrprof failed to lower a cover"); 7027 case Intrinsic::instrprof_increment: 7028 llvm_unreachable("instrprof failed to lower an increment"); 7029 case Intrinsic::instrprof_value_profile: 7030 llvm_unreachable("instrprof failed to lower a value profiling call"); 7031 case Intrinsic::localescape: { 7032 MachineFunction &MF = DAG.getMachineFunction(); 7033 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7034 7035 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7036 // is the same on all targets. 7037 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7038 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7039 if (isa<ConstantPointerNull>(Arg)) 7040 continue; // Skip null pointers. They represent a hole in index space. 7041 AllocaInst *Slot = cast<AllocaInst>(Arg); 7042 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7043 "can only escape static allocas"); 7044 int FI = FuncInfo.StaticAllocaMap[Slot]; 7045 MCSymbol *FrameAllocSym = 7046 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7047 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7049 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7050 .addSym(FrameAllocSym) 7051 .addFrameIndex(FI); 7052 } 7053 7054 return; 7055 } 7056 7057 case Intrinsic::localrecover: { 7058 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7059 MachineFunction &MF = DAG.getMachineFunction(); 7060 7061 // Get the symbol that defines the frame offset. 7062 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7063 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7064 unsigned IdxVal = 7065 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7066 MCSymbol *FrameAllocSym = 7067 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7068 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7069 7070 Value *FP = I.getArgOperand(1); 7071 SDValue FPVal = getValue(FP); 7072 EVT PtrVT = FPVal.getValueType(); 7073 7074 // Create a MCSymbol for the label to avoid any target lowering 7075 // that would make this PC relative. 7076 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7077 SDValue OffsetVal = 7078 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7079 7080 // Add the offset to the FP. 7081 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7082 setValue(&I, Add); 7083 7084 return; 7085 } 7086 7087 case Intrinsic::eh_exceptionpointer: 7088 case Intrinsic::eh_exceptioncode: { 7089 // Get the exception pointer vreg, copy from it, and resize it to fit. 7090 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7091 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7092 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7093 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7094 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7095 if (Intrinsic == Intrinsic::eh_exceptioncode) 7096 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7097 setValue(&I, N); 7098 return; 7099 } 7100 case Intrinsic::xray_customevent: { 7101 // Here we want to make sure that the intrinsic behaves as if it has a 7102 // specific calling convention, and only for x86_64. 7103 // FIXME: Support other platforms later. 7104 const auto &Triple = DAG.getTarget().getTargetTriple(); 7105 if (Triple.getArch() != Triple::x86_64) 7106 return; 7107 7108 SmallVector<SDValue, 8> Ops; 7109 7110 // We want to say that we always want the arguments in registers. 7111 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7112 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7113 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7114 SDValue Chain = getRoot(); 7115 Ops.push_back(LogEntryVal); 7116 Ops.push_back(StrSizeVal); 7117 Ops.push_back(Chain); 7118 7119 // We need to enforce the calling convention for the callsite, so that 7120 // argument ordering is enforced correctly, and that register allocation can 7121 // see that some registers may be assumed clobbered and have to preserve 7122 // them across calls to the intrinsic. 7123 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7124 sdl, NodeTys, Ops); 7125 SDValue patchableNode = SDValue(MN, 0); 7126 DAG.setRoot(patchableNode); 7127 setValue(&I, patchableNode); 7128 return; 7129 } 7130 case Intrinsic::xray_typedevent: { 7131 // Here we want to make sure that the intrinsic behaves as if it has a 7132 // specific calling convention, and only for x86_64. 7133 // FIXME: Support other platforms later. 7134 const auto &Triple = DAG.getTarget().getTargetTriple(); 7135 if (Triple.getArch() != Triple::x86_64) 7136 return; 7137 7138 SmallVector<SDValue, 8> Ops; 7139 7140 // We want to say that we always want the arguments in registers. 7141 // It's unclear to me how manipulating the selection DAG here forces callers 7142 // to provide arguments in registers instead of on the stack. 7143 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7144 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7145 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7146 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7147 SDValue Chain = getRoot(); 7148 Ops.push_back(LogTypeId); 7149 Ops.push_back(LogEntryVal); 7150 Ops.push_back(StrSizeVal); 7151 Ops.push_back(Chain); 7152 7153 // We need to enforce the calling convention for the callsite, so that 7154 // argument ordering is enforced correctly, and that register allocation can 7155 // see that some registers may be assumed clobbered and have to preserve 7156 // them across calls to the intrinsic. 7157 MachineSDNode *MN = DAG.getMachineNode( 7158 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7159 SDValue patchableNode = SDValue(MN, 0); 7160 DAG.setRoot(patchableNode); 7161 setValue(&I, patchableNode); 7162 return; 7163 } 7164 case Intrinsic::experimental_deoptimize: 7165 LowerDeoptimizeCall(&I); 7166 return; 7167 case Intrinsic::experimental_stepvector: 7168 visitStepVector(I); 7169 return; 7170 case Intrinsic::vector_reduce_fadd: 7171 case Intrinsic::vector_reduce_fmul: 7172 case Intrinsic::vector_reduce_add: 7173 case Intrinsic::vector_reduce_mul: 7174 case Intrinsic::vector_reduce_and: 7175 case Intrinsic::vector_reduce_or: 7176 case Intrinsic::vector_reduce_xor: 7177 case Intrinsic::vector_reduce_smax: 7178 case Intrinsic::vector_reduce_smin: 7179 case Intrinsic::vector_reduce_umax: 7180 case Intrinsic::vector_reduce_umin: 7181 case Intrinsic::vector_reduce_fmax: 7182 case Intrinsic::vector_reduce_fmin: 7183 visitVectorReduce(I, Intrinsic); 7184 return; 7185 7186 case Intrinsic::icall_branch_funnel: { 7187 SmallVector<SDValue, 16> Ops; 7188 Ops.push_back(getValue(I.getArgOperand(0))); 7189 7190 int64_t Offset; 7191 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7192 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7193 if (!Base) 7194 report_fatal_error( 7195 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7196 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7197 7198 struct BranchFunnelTarget { 7199 int64_t Offset; 7200 SDValue Target; 7201 }; 7202 SmallVector<BranchFunnelTarget, 8> Targets; 7203 7204 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7205 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7206 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7207 if (ElemBase != Base) 7208 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7209 "to the same GlobalValue"); 7210 7211 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7212 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7213 if (!GA) 7214 report_fatal_error( 7215 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7216 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7217 GA->getGlobal(), sdl, Val.getValueType(), 7218 GA->getOffset())}); 7219 } 7220 llvm::sort(Targets, 7221 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7222 return T1.Offset < T2.Offset; 7223 }); 7224 7225 for (auto &T : Targets) { 7226 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7227 Ops.push_back(T.Target); 7228 } 7229 7230 Ops.push_back(DAG.getRoot()); // Chain 7231 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7232 MVT::Other, Ops), 7233 0); 7234 DAG.setRoot(N); 7235 setValue(&I, N); 7236 HasTailCall = true; 7237 return; 7238 } 7239 7240 case Intrinsic::wasm_landingpad_index: 7241 // Information this intrinsic contained has been transferred to 7242 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7243 // delete it now. 7244 return; 7245 7246 case Intrinsic::aarch64_settag: 7247 case Intrinsic::aarch64_settag_zero: { 7248 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7249 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7250 SDValue Val = TSI.EmitTargetCodeForSetTag( 7251 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7252 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7253 ZeroMemory); 7254 DAG.setRoot(Val); 7255 setValue(&I, Val); 7256 return; 7257 } 7258 case Intrinsic::ptrmask: { 7259 SDValue Ptr = getValue(I.getOperand(0)); 7260 SDValue Const = getValue(I.getOperand(1)); 7261 7262 EVT PtrVT = Ptr.getValueType(); 7263 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7264 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7265 return; 7266 } 7267 case Intrinsic::threadlocal_address: { 7268 setValue(&I, getValue(I.getOperand(0))); 7269 return; 7270 } 7271 case Intrinsic::get_active_lane_mask: { 7272 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7273 SDValue Index = getValue(I.getOperand(0)); 7274 EVT ElementVT = Index.getValueType(); 7275 7276 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7277 visitTargetIntrinsic(I, Intrinsic); 7278 return; 7279 } 7280 7281 SDValue TripCount = getValue(I.getOperand(1)); 7282 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7283 7284 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7285 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7286 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7287 SDValue VectorInduction = DAG.getNode( 7288 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7289 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7290 VectorTripCount, ISD::CondCode::SETULT); 7291 setValue(&I, SetCC); 7292 return; 7293 } 7294 case Intrinsic::vector_insert: { 7295 SDValue Vec = getValue(I.getOperand(0)); 7296 SDValue SubVec = getValue(I.getOperand(1)); 7297 SDValue Index = getValue(I.getOperand(2)); 7298 7299 // The intrinsic's index type is i64, but the SDNode requires an index type 7300 // suitable for the target. Convert the index as required. 7301 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7302 if (Index.getValueType() != VectorIdxTy) 7303 Index = DAG.getVectorIdxConstant( 7304 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7305 7306 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7307 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7308 Index)); 7309 return; 7310 } 7311 case Intrinsic::vector_extract: { 7312 SDValue Vec = getValue(I.getOperand(0)); 7313 SDValue Index = getValue(I.getOperand(1)); 7314 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7315 7316 // The intrinsic's index type is i64, but the SDNode requires an index type 7317 // suitable for the target. Convert the index as required. 7318 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7319 if (Index.getValueType() != VectorIdxTy) 7320 Index = DAG.getVectorIdxConstant( 7321 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7322 7323 setValue(&I, 7324 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7325 return; 7326 } 7327 case Intrinsic::experimental_vector_reverse: 7328 visitVectorReverse(I); 7329 return; 7330 case Intrinsic::experimental_vector_splice: 7331 visitVectorSplice(I); 7332 return; 7333 } 7334 } 7335 7336 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7337 const ConstrainedFPIntrinsic &FPI) { 7338 SDLoc sdl = getCurSDLoc(); 7339 7340 // We do not need to serialize constrained FP intrinsics against 7341 // each other or against (nonvolatile) loads, so they can be 7342 // chained like loads. 7343 SDValue Chain = DAG.getRoot(); 7344 SmallVector<SDValue, 4> Opers; 7345 Opers.push_back(Chain); 7346 if (FPI.isUnaryOp()) { 7347 Opers.push_back(getValue(FPI.getArgOperand(0))); 7348 } else if (FPI.isTernaryOp()) { 7349 Opers.push_back(getValue(FPI.getArgOperand(0))); 7350 Opers.push_back(getValue(FPI.getArgOperand(1))); 7351 Opers.push_back(getValue(FPI.getArgOperand(2))); 7352 } else { 7353 Opers.push_back(getValue(FPI.getArgOperand(0))); 7354 Opers.push_back(getValue(FPI.getArgOperand(1))); 7355 } 7356 7357 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7358 assert(Result.getNode()->getNumValues() == 2); 7359 7360 // Push node to the appropriate list so that future instructions can be 7361 // chained up correctly. 7362 SDValue OutChain = Result.getValue(1); 7363 switch (EB) { 7364 case fp::ExceptionBehavior::ebIgnore: 7365 // The only reason why ebIgnore nodes still need to be chained is that 7366 // they might depend on the current rounding mode, and therefore must 7367 // not be moved across instruction that may change that mode. 7368 [[fallthrough]]; 7369 case fp::ExceptionBehavior::ebMayTrap: 7370 // These must not be moved across calls or instructions that may change 7371 // floating-point exception masks. 7372 PendingConstrainedFP.push_back(OutChain); 7373 break; 7374 case fp::ExceptionBehavior::ebStrict: 7375 // These must not be moved across calls or instructions that may change 7376 // floating-point exception masks or read floating-point exception flags. 7377 // In addition, they cannot be optimized out even if unused. 7378 PendingConstrainedFPStrict.push_back(OutChain); 7379 break; 7380 } 7381 }; 7382 7383 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7384 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7385 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7386 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7387 7388 SDNodeFlags Flags; 7389 if (EB == fp::ExceptionBehavior::ebIgnore) 7390 Flags.setNoFPExcept(true); 7391 7392 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7393 Flags.copyFMF(*FPOp); 7394 7395 unsigned Opcode; 7396 switch (FPI.getIntrinsicID()) { 7397 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7398 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7399 case Intrinsic::INTRINSIC: \ 7400 Opcode = ISD::STRICT_##DAGN; \ 7401 break; 7402 #include "llvm/IR/ConstrainedOps.def" 7403 case Intrinsic::experimental_constrained_fmuladd: { 7404 Opcode = ISD::STRICT_FMA; 7405 // Break fmuladd into fmul and fadd. 7406 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7407 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7408 Opers.pop_back(); 7409 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7410 pushOutChain(Mul, EB); 7411 Opcode = ISD::STRICT_FADD; 7412 Opers.clear(); 7413 Opers.push_back(Mul.getValue(1)); 7414 Opers.push_back(Mul.getValue(0)); 7415 Opers.push_back(getValue(FPI.getArgOperand(2))); 7416 } 7417 break; 7418 } 7419 } 7420 7421 // A few strict DAG nodes carry additional operands that are not 7422 // set up by the default code above. 7423 switch (Opcode) { 7424 default: break; 7425 case ISD::STRICT_FP_ROUND: 7426 Opers.push_back( 7427 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7428 break; 7429 case ISD::STRICT_FSETCC: 7430 case ISD::STRICT_FSETCCS: { 7431 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7432 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7433 if (TM.Options.NoNaNsFPMath) 7434 Condition = getFCmpCodeWithoutNaN(Condition); 7435 Opers.push_back(DAG.getCondCode(Condition)); 7436 break; 7437 } 7438 } 7439 7440 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7441 pushOutChain(Result, EB); 7442 7443 SDValue FPResult = Result.getValue(0); 7444 setValue(&FPI, FPResult); 7445 } 7446 7447 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7448 std::optional<unsigned> ResOPC; 7449 switch (VPIntrin.getIntrinsicID()) { 7450 case Intrinsic::vp_ctlz: { 7451 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne(); 7452 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7453 break; 7454 } 7455 case Intrinsic::vp_cttz: { 7456 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne(); 7457 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7458 break; 7459 } 7460 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7461 case Intrinsic::VPID: \ 7462 ResOPC = ISD::VPSD; \ 7463 break; 7464 #include "llvm/IR/VPIntrinsics.def" 7465 } 7466 7467 if (!ResOPC) 7468 llvm_unreachable( 7469 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7470 7471 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7472 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7473 if (VPIntrin.getFastMathFlags().allowReassoc()) 7474 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7475 : ISD::VP_REDUCE_FMUL; 7476 } 7477 7478 return *ResOPC; 7479 } 7480 7481 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT, 7482 SmallVector<SDValue, 7> &OpValues) { 7483 SDLoc DL = getCurSDLoc(); 7484 Value *PtrOperand = VPIntrin.getArgOperand(0); 7485 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7486 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7487 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7488 SDValue LD; 7489 bool AddToChain = true; 7490 // Do not serialize variable-length loads of constant memory with 7491 // anything. 7492 if (!Alignment) 7493 Alignment = DAG.getEVTAlign(VT); 7494 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7495 AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7496 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7497 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7498 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7499 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7500 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7501 MMO, false /*IsExpanding */); 7502 if (AddToChain) 7503 PendingLoads.push_back(LD.getValue(1)); 7504 setValue(&VPIntrin, LD); 7505 } 7506 7507 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT, 7508 SmallVector<SDValue, 7> &OpValues) { 7509 SDLoc DL = getCurSDLoc(); 7510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7511 Value *PtrOperand = VPIntrin.getArgOperand(0); 7512 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7513 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7514 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7515 SDValue LD; 7516 if (!Alignment) 7517 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7518 unsigned AS = 7519 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7520 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7521 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7522 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7523 SDValue Base, Index, Scale; 7524 ISD::MemIndexType IndexType; 7525 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7526 this, VPIntrin.getParent(), 7527 VT.getScalarStoreSize()); 7528 if (!UniformBase) { 7529 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7530 Index = getValue(PtrOperand); 7531 IndexType = ISD::SIGNED_SCALED; 7532 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7533 } 7534 EVT IdxVT = Index.getValueType(); 7535 EVT EltTy = IdxVT.getVectorElementType(); 7536 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7537 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7538 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7539 } 7540 LD = DAG.getGatherVP( 7541 DAG.getVTList(VT, MVT::Other), VT, DL, 7542 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7543 IndexType); 7544 PendingLoads.push_back(LD.getValue(1)); 7545 setValue(&VPIntrin, LD); 7546 } 7547 7548 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin, 7549 SmallVector<SDValue, 7> &OpValues) { 7550 SDLoc DL = getCurSDLoc(); 7551 Value *PtrOperand = VPIntrin.getArgOperand(1); 7552 EVT VT = OpValues[0].getValueType(); 7553 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7554 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7555 SDValue ST; 7556 if (!Alignment) 7557 Alignment = DAG.getEVTAlign(VT); 7558 SDValue Ptr = OpValues[1]; 7559 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7560 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7561 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7562 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7563 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7564 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7565 /* IsTruncating */ false, /*IsCompressing*/ false); 7566 DAG.setRoot(ST); 7567 setValue(&VPIntrin, ST); 7568 } 7569 7570 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin, 7571 SmallVector<SDValue, 7> &OpValues) { 7572 SDLoc DL = getCurSDLoc(); 7573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7574 Value *PtrOperand = VPIntrin.getArgOperand(1); 7575 EVT VT = OpValues[0].getValueType(); 7576 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7577 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7578 SDValue ST; 7579 if (!Alignment) 7580 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7581 unsigned AS = 7582 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7583 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7584 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7585 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7586 SDValue Base, Index, Scale; 7587 ISD::MemIndexType IndexType; 7588 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7589 this, VPIntrin.getParent(), 7590 VT.getScalarStoreSize()); 7591 if (!UniformBase) { 7592 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7593 Index = getValue(PtrOperand); 7594 IndexType = ISD::SIGNED_SCALED; 7595 Scale = 7596 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7597 } 7598 EVT IdxVT = Index.getValueType(); 7599 EVT EltTy = IdxVT.getVectorElementType(); 7600 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7601 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7602 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7603 } 7604 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7605 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7606 OpValues[2], OpValues[3]}, 7607 MMO, IndexType); 7608 DAG.setRoot(ST); 7609 setValue(&VPIntrin, ST); 7610 } 7611 7612 void SelectionDAGBuilder::visitVPStridedLoad( 7613 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) { 7614 SDLoc DL = getCurSDLoc(); 7615 Value *PtrOperand = VPIntrin.getArgOperand(0); 7616 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7617 if (!Alignment) 7618 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7619 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7620 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7621 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7622 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7623 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7624 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7625 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7626 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7627 7628 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7629 OpValues[2], OpValues[3], MMO, 7630 false /*IsExpanding*/); 7631 7632 if (AddToChain) 7633 PendingLoads.push_back(LD.getValue(1)); 7634 setValue(&VPIntrin, LD); 7635 } 7636 7637 void SelectionDAGBuilder::visitVPStridedStore( 7638 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) { 7639 SDLoc DL = getCurSDLoc(); 7640 Value *PtrOperand = VPIntrin.getArgOperand(1); 7641 EVT VT = OpValues[0].getValueType(); 7642 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7643 if (!Alignment) 7644 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7645 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7646 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7647 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7648 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7649 7650 SDValue ST = DAG.getStridedStoreVP( 7651 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7652 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7653 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7654 /*IsCompressing*/ false); 7655 7656 DAG.setRoot(ST); 7657 setValue(&VPIntrin, ST); 7658 } 7659 7660 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7661 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7662 SDLoc DL = getCurSDLoc(); 7663 7664 ISD::CondCode Condition; 7665 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7666 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7667 if (IsFP) { 7668 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7669 // flags, but calls that don't return floating-point types can't be 7670 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7671 Condition = getFCmpCondCode(CondCode); 7672 if (TM.Options.NoNaNsFPMath) 7673 Condition = getFCmpCodeWithoutNaN(Condition); 7674 } else { 7675 Condition = getICmpCondCode(CondCode); 7676 } 7677 7678 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7679 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7680 // #2 is the condition code 7681 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7682 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7683 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7684 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7685 "Unexpected target EVL type"); 7686 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7687 7688 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7689 VPIntrin.getType()); 7690 setValue(&VPIntrin, 7691 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7692 } 7693 7694 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7695 const VPIntrinsic &VPIntrin) { 7696 SDLoc DL = getCurSDLoc(); 7697 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7698 7699 auto IID = VPIntrin.getIntrinsicID(); 7700 7701 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7702 return visitVPCmp(*CmpI); 7703 7704 SmallVector<EVT, 4> ValueVTs; 7705 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7706 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7707 SDVTList VTs = DAG.getVTList(ValueVTs); 7708 7709 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7710 7711 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7712 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7713 "Unexpected target EVL type"); 7714 7715 // Request operands. 7716 SmallVector<SDValue, 7> OpValues; 7717 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7718 auto Op = getValue(VPIntrin.getArgOperand(I)); 7719 if (I == EVLParamPos) 7720 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7721 OpValues.push_back(Op); 7722 } 7723 7724 switch (Opcode) { 7725 default: { 7726 SDNodeFlags SDFlags; 7727 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7728 SDFlags.copyFMF(*FPMO); 7729 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7730 setValue(&VPIntrin, Result); 7731 break; 7732 } 7733 case ISD::VP_LOAD: 7734 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7735 break; 7736 case ISD::VP_GATHER: 7737 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7738 break; 7739 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7740 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7741 break; 7742 case ISD::VP_STORE: 7743 visitVPStore(VPIntrin, OpValues); 7744 break; 7745 case ISD::VP_SCATTER: 7746 visitVPScatter(VPIntrin, OpValues); 7747 break; 7748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7749 visitVPStridedStore(VPIntrin, OpValues); 7750 break; 7751 case ISD::VP_FMULADD: { 7752 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7753 SDNodeFlags SDFlags; 7754 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7755 SDFlags.copyFMF(*FPMO); 7756 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7757 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7758 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7759 } else { 7760 SDValue Mul = DAG.getNode( 7761 ISD::VP_FMUL, DL, VTs, 7762 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7763 SDValue Add = 7764 DAG.getNode(ISD::VP_FADD, DL, VTs, 7765 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7766 setValue(&VPIntrin, Add); 7767 } 7768 break; 7769 } 7770 case ISD::VP_INTTOPTR: { 7771 SDValue N = OpValues[0]; 7772 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7773 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7774 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7775 OpValues[2]); 7776 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7777 OpValues[2]); 7778 setValue(&VPIntrin, N); 7779 break; 7780 } 7781 case ISD::VP_PTRTOINT: { 7782 SDValue N = OpValues[0]; 7783 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7784 VPIntrin.getType()); 7785 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7786 VPIntrin.getOperand(0)->getType()); 7787 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7788 OpValues[2]); 7789 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7790 OpValues[2]); 7791 setValue(&VPIntrin, N); 7792 break; 7793 } 7794 case ISD::VP_ABS: 7795 case ISD::VP_CTLZ: 7796 case ISD::VP_CTLZ_ZERO_UNDEF: 7797 case ISD::VP_CTTZ: 7798 case ISD::VP_CTTZ_ZERO_UNDEF: { 7799 // Pop is_zero_poison operand for cp.ctlz/cttz or 7800 // is_int_min_poison operand for vp.abs. 7801 OpValues.pop_back(); 7802 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7803 setValue(&VPIntrin, Result); 7804 break; 7805 } 7806 } 7807 } 7808 7809 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7810 const BasicBlock *EHPadBB, 7811 MCSymbol *&BeginLabel) { 7812 MachineFunction &MF = DAG.getMachineFunction(); 7813 MachineModuleInfo &MMI = MF.getMMI(); 7814 7815 // Insert a label before the invoke call to mark the try range. This can be 7816 // used to detect deletion of the invoke via the MachineModuleInfo. 7817 BeginLabel = MMI.getContext().createTempSymbol(); 7818 7819 // For SjLj, keep track of which landing pads go with which invokes 7820 // so as to maintain the ordering of pads in the LSDA. 7821 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7822 if (CallSiteIndex) { 7823 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7824 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7825 7826 // Now that the call site is handled, stop tracking it. 7827 MMI.setCurrentCallSite(0); 7828 } 7829 7830 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7831 } 7832 7833 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7834 const BasicBlock *EHPadBB, 7835 MCSymbol *BeginLabel) { 7836 assert(BeginLabel && "BeginLabel should've been set"); 7837 7838 MachineFunction &MF = DAG.getMachineFunction(); 7839 MachineModuleInfo &MMI = MF.getMMI(); 7840 7841 // Insert a label at the end of the invoke call to mark the try range. This 7842 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7843 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7844 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7845 7846 // Inform MachineModuleInfo of range. 7847 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7848 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7849 // actually use outlined funclets and their LSDA info style. 7850 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7851 assert(II && "II should've been set"); 7852 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 7853 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 7854 } else if (!isScopedEHPersonality(Pers)) { 7855 assert(EHPadBB); 7856 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7857 } 7858 7859 return Chain; 7860 } 7861 7862 std::pair<SDValue, SDValue> 7863 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7864 const BasicBlock *EHPadBB) { 7865 MCSymbol *BeginLabel = nullptr; 7866 7867 if (EHPadBB) { 7868 // Both PendingLoads and PendingExports must be flushed here; 7869 // this call might not return. 7870 (void)getRoot(); 7871 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 7872 CLI.setChain(getRoot()); 7873 } 7874 7875 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7876 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7877 7878 assert((CLI.IsTailCall || Result.second.getNode()) && 7879 "Non-null chain expected with non-tail call!"); 7880 assert((Result.second.getNode() || !Result.first.getNode()) && 7881 "Null value expected with tail call!"); 7882 7883 if (!Result.second.getNode()) { 7884 // As a special case, a null chain means that a tail call has been emitted 7885 // and the DAG root is already updated. 7886 HasTailCall = true; 7887 7888 // Since there's no actual continuation from this block, nothing can be 7889 // relying on us setting vregs for them. 7890 PendingExports.clear(); 7891 } else { 7892 DAG.setRoot(Result.second); 7893 } 7894 7895 if (EHPadBB) { 7896 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 7897 BeginLabel)); 7898 } 7899 7900 return Result; 7901 } 7902 7903 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7904 bool isTailCall, 7905 bool isMustTailCall, 7906 const BasicBlock *EHPadBB) { 7907 auto &DL = DAG.getDataLayout(); 7908 FunctionType *FTy = CB.getFunctionType(); 7909 Type *RetTy = CB.getType(); 7910 7911 TargetLowering::ArgListTy Args; 7912 Args.reserve(CB.arg_size()); 7913 7914 const Value *SwiftErrorVal = nullptr; 7915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7916 7917 if (isTailCall) { 7918 // Avoid emitting tail calls in functions with the disable-tail-calls 7919 // attribute. 7920 auto *Caller = CB.getParent()->getParent(); 7921 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7922 "true" && !isMustTailCall) 7923 isTailCall = false; 7924 7925 // We can't tail call inside a function with a swifterror argument. Lowering 7926 // does not support this yet. It would have to move into the swifterror 7927 // register before the call. 7928 if (TLI.supportSwiftError() && 7929 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7930 isTailCall = false; 7931 } 7932 7933 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7934 TargetLowering::ArgListEntry Entry; 7935 const Value *V = *I; 7936 7937 // Skip empty types 7938 if (V->getType()->isEmptyTy()) 7939 continue; 7940 7941 SDValue ArgNode = getValue(V); 7942 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7943 7944 Entry.setAttributes(&CB, I - CB.arg_begin()); 7945 7946 // Use swifterror virtual register as input to the call. 7947 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7948 SwiftErrorVal = V; 7949 // We find the virtual register for the actual swifterror argument. 7950 // Instead of using the Value, we use the virtual register instead. 7951 Entry.Node = 7952 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7953 EVT(TLI.getPointerTy(DL))); 7954 } 7955 7956 Args.push_back(Entry); 7957 7958 // If we have an explicit sret argument that is an Instruction, (i.e., it 7959 // might point to function-local memory), we can't meaningfully tail-call. 7960 if (Entry.IsSRet && isa<Instruction>(V)) 7961 isTailCall = false; 7962 } 7963 7964 // If call site has a cfguardtarget operand bundle, create and add an 7965 // additional ArgListEntry. 7966 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7967 TargetLowering::ArgListEntry Entry; 7968 Value *V = Bundle->Inputs[0]; 7969 SDValue ArgNode = getValue(V); 7970 Entry.Node = ArgNode; 7971 Entry.Ty = V->getType(); 7972 Entry.IsCFGuardTarget = true; 7973 Args.push_back(Entry); 7974 } 7975 7976 // Check if target-independent constraints permit a tail call here. 7977 // Target-dependent constraints are checked within TLI->LowerCallTo. 7978 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7979 isTailCall = false; 7980 7981 // Disable tail calls if there is an swifterror argument. Targets have not 7982 // been updated to support tail calls. 7983 if (TLI.supportSwiftError() && SwiftErrorVal) 7984 isTailCall = false; 7985 7986 ConstantInt *CFIType = nullptr; 7987 if (CB.isIndirectCall()) { 7988 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 7989 if (!TLI.supportKCFIBundles()) 7990 report_fatal_error( 7991 "Target doesn't support calls with kcfi operand bundles."); 7992 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 7993 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 7994 } 7995 } 7996 7997 TargetLowering::CallLoweringInfo CLI(DAG); 7998 CLI.setDebugLoc(getCurSDLoc()) 7999 .setChain(getRoot()) 8000 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8001 .setTailCall(isTailCall) 8002 .setConvergent(CB.isConvergent()) 8003 .setIsPreallocated( 8004 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8005 .setCFIType(CFIType); 8006 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8007 8008 if (Result.first.getNode()) { 8009 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8010 setValue(&CB, Result.first); 8011 } 8012 8013 // The last element of CLI.InVals has the SDValue for swifterror return. 8014 // Here we copy it to a virtual register and update SwiftErrorMap for 8015 // book-keeping. 8016 if (SwiftErrorVal && TLI.supportSwiftError()) { 8017 // Get the last element of InVals. 8018 SDValue Src = CLI.InVals.back(); 8019 Register VReg = 8020 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8021 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8022 DAG.setRoot(CopyNode); 8023 } 8024 } 8025 8026 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8027 SelectionDAGBuilder &Builder) { 8028 // Check to see if this load can be trivially constant folded, e.g. if the 8029 // input is from a string literal. 8030 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8031 // Cast pointer to the type we really want to load. 8032 Type *LoadTy = 8033 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8034 if (LoadVT.isVector()) 8035 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8036 8037 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8038 PointerType::getUnqual(LoadTy)); 8039 8040 if (const Constant *LoadCst = 8041 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8042 LoadTy, Builder.DAG.getDataLayout())) 8043 return Builder.getValue(LoadCst); 8044 } 8045 8046 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8047 // still constant memory, the input chain can be the entry node. 8048 SDValue Root; 8049 bool ConstantMemory = false; 8050 8051 // Do not serialize (non-volatile) loads of constant memory with anything. 8052 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8053 Root = Builder.DAG.getEntryNode(); 8054 ConstantMemory = true; 8055 } else { 8056 // Do not serialize non-volatile loads against each other. 8057 Root = Builder.DAG.getRoot(); 8058 } 8059 8060 SDValue Ptr = Builder.getValue(PtrVal); 8061 SDValue LoadVal = 8062 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8063 MachinePointerInfo(PtrVal), Align(1)); 8064 8065 if (!ConstantMemory) 8066 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8067 return LoadVal; 8068 } 8069 8070 /// Record the value for an instruction that produces an integer result, 8071 /// converting the type where necessary. 8072 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8073 SDValue Value, 8074 bool IsSigned) { 8075 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8076 I.getType(), true); 8077 if (IsSigned) 8078 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 8079 else 8080 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 8081 setValue(&I, Value); 8082 } 8083 8084 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8085 /// true and lower it. Otherwise return false, and it will be lowered like a 8086 /// normal call. 8087 /// The caller already checked that \p I calls the appropriate LibFunc with a 8088 /// correct prototype. 8089 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8090 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8091 const Value *Size = I.getArgOperand(2); 8092 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8093 if (CSize && CSize->getZExtValue() == 0) { 8094 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8095 I.getType(), true); 8096 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8097 return true; 8098 } 8099 8100 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8101 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8102 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8103 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8104 if (Res.first.getNode()) { 8105 processIntegerCallValue(I, Res.first, true); 8106 PendingLoads.push_back(Res.second); 8107 return true; 8108 } 8109 8110 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8111 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8112 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8113 return false; 8114 8115 // If the target has a fast compare for the given size, it will return a 8116 // preferred load type for that size. Require that the load VT is legal and 8117 // that the target supports unaligned loads of that type. Otherwise, return 8118 // INVALID. 8119 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8121 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8122 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8123 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8124 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8125 // TODO: Check alignment of src and dest ptrs. 8126 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8127 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8128 if (!TLI.isTypeLegal(LVT) || 8129 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8130 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8131 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8132 } 8133 8134 return LVT; 8135 }; 8136 8137 // This turns into unaligned loads. We only do this if the target natively 8138 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8139 // we'll only produce a small number of byte loads. 8140 MVT LoadVT; 8141 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8142 switch (NumBitsToCompare) { 8143 default: 8144 return false; 8145 case 16: 8146 LoadVT = MVT::i16; 8147 break; 8148 case 32: 8149 LoadVT = MVT::i32; 8150 break; 8151 case 64: 8152 case 128: 8153 case 256: 8154 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8155 break; 8156 } 8157 8158 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8159 return false; 8160 8161 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8162 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8163 8164 // Bitcast to a wide integer type if the loads are vectors. 8165 if (LoadVT.isVector()) { 8166 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8167 LoadL = DAG.getBitcast(CmpVT, LoadL); 8168 LoadR = DAG.getBitcast(CmpVT, LoadR); 8169 } 8170 8171 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8172 processIntegerCallValue(I, Cmp, false); 8173 return true; 8174 } 8175 8176 /// See if we can lower a memchr call into an optimized form. If so, return 8177 /// true and lower it. Otherwise return false, and it will be lowered like a 8178 /// normal call. 8179 /// The caller already checked that \p I calls the appropriate LibFunc with a 8180 /// correct prototype. 8181 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8182 const Value *Src = I.getArgOperand(0); 8183 const Value *Char = I.getArgOperand(1); 8184 const Value *Length = I.getArgOperand(2); 8185 8186 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8187 std::pair<SDValue, SDValue> Res = 8188 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8189 getValue(Src), getValue(Char), getValue(Length), 8190 MachinePointerInfo(Src)); 8191 if (Res.first.getNode()) { 8192 setValue(&I, Res.first); 8193 PendingLoads.push_back(Res.second); 8194 return true; 8195 } 8196 8197 return false; 8198 } 8199 8200 /// See if we can lower a mempcpy call into an optimized form. If so, return 8201 /// true and lower it. Otherwise return false, and it will be lowered like a 8202 /// normal call. 8203 /// The caller already checked that \p I calls the appropriate LibFunc with a 8204 /// correct prototype. 8205 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8206 SDValue Dst = getValue(I.getArgOperand(0)); 8207 SDValue Src = getValue(I.getArgOperand(1)); 8208 SDValue Size = getValue(I.getArgOperand(2)); 8209 8210 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8211 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8212 // DAG::getMemcpy needs Alignment to be defined. 8213 Align Alignment = std::min(DstAlign, SrcAlign); 8214 8215 bool isVol = false; 8216 SDLoc sdl = getCurSDLoc(); 8217 8218 // In the mempcpy context we need to pass in a false value for isTailCall 8219 // because the return pointer needs to be adjusted by the size of 8220 // the copied memory. 8221 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 8222 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 8223 /*isTailCall=*/false, 8224 MachinePointerInfo(I.getArgOperand(0)), 8225 MachinePointerInfo(I.getArgOperand(1)), 8226 I.getAAMetadata()); 8227 assert(MC.getNode() != nullptr && 8228 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8229 DAG.setRoot(MC); 8230 8231 // Check if Size needs to be truncated or extended. 8232 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8233 8234 // Adjust return pointer to point just past the last dst byte. 8235 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8236 Dst, Size); 8237 setValue(&I, DstPlusSize); 8238 return true; 8239 } 8240 8241 /// See if we can lower a strcpy call into an optimized form. If so, return 8242 /// true and lower it, otherwise return false and it will be lowered like a 8243 /// normal call. 8244 /// The caller already checked that \p I calls the appropriate LibFunc with a 8245 /// correct prototype. 8246 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8247 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8248 8249 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8250 std::pair<SDValue, SDValue> Res = 8251 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8252 getValue(Arg0), getValue(Arg1), 8253 MachinePointerInfo(Arg0), 8254 MachinePointerInfo(Arg1), isStpcpy); 8255 if (Res.first.getNode()) { 8256 setValue(&I, Res.first); 8257 DAG.setRoot(Res.second); 8258 return true; 8259 } 8260 8261 return false; 8262 } 8263 8264 /// See if we can lower a strcmp call into an optimized form. If so, return 8265 /// true and lower it, otherwise return false and it will be lowered like a 8266 /// normal call. 8267 /// The caller already checked that \p I calls the appropriate LibFunc with a 8268 /// correct prototype. 8269 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8270 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8271 8272 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8273 std::pair<SDValue, SDValue> Res = 8274 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8275 getValue(Arg0), getValue(Arg1), 8276 MachinePointerInfo(Arg0), 8277 MachinePointerInfo(Arg1)); 8278 if (Res.first.getNode()) { 8279 processIntegerCallValue(I, Res.first, true); 8280 PendingLoads.push_back(Res.second); 8281 return true; 8282 } 8283 8284 return false; 8285 } 8286 8287 /// See if we can lower a strlen call into an optimized form. If so, return 8288 /// true and lower it, otherwise return false and it will be lowered like a 8289 /// normal call. 8290 /// The caller already checked that \p I calls the appropriate LibFunc with a 8291 /// correct prototype. 8292 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8293 const Value *Arg0 = I.getArgOperand(0); 8294 8295 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8296 std::pair<SDValue, SDValue> Res = 8297 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8298 getValue(Arg0), MachinePointerInfo(Arg0)); 8299 if (Res.first.getNode()) { 8300 processIntegerCallValue(I, Res.first, false); 8301 PendingLoads.push_back(Res.second); 8302 return true; 8303 } 8304 8305 return false; 8306 } 8307 8308 /// See if we can lower a strnlen call into an optimized form. If so, return 8309 /// true and lower it, otherwise return false and it will be lowered like a 8310 /// normal call. 8311 /// The caller already checked that \p I calls the appropriate LibFunc with a 8312 /// correct prototype. 8313 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8314 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8315 8316 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8317 std::pair<SDValue, SDValue> Res = 8318 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8319 getValue(Arg0), getValue(Arg1), 8320 MachinePointerInfo(Arg0)); 8321 if (Res.first.getNode()) { 8322 processIntegerCallValue(I, Res.first, false); 8323 PendingLoads.push_back(Res.second); 8324 return true; 8325 } 8326 8327 return false; 8328 } 8329 8330 /// See if we can lower a unary floating-point operation into an SDNode with 8331 /// the specified Opcode. If so, return true and lower it, otherwise return 8332 /// false and it will be lowered like a normal call. 8333 /// The caller already checked that \p I calls the appropriate LibFunc with a 8334 /// correct prototype. 8335 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8336 unsigned Opcode) { 8337 // We already checked this call's prototype; verify it doesn't modify errno. 8338 if (!I.onlyReadsMemory()) 8339 return false; 8340 8341 SDNodeFlags Flags; 8342 Flags.copyFMF(cast<FPMathOperator>(I)); 8343 8344 SDValue Tmp = getValue(I.getArgOperand(0)); 8345 setValue(&I, 8346 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8347 return true; 8348 } 8349 8350 /// See if we can lower a binary floating-point operation into an SDNode with 8351 /// the specified Opcode. If so, return true and lower it. Otherwise return 8352 /// false, and it will be lowered like a normal call. 8353 /// The caller already checked that \p I calls the appropriate LibFunc with a 8354 /// correct prototype. 8355 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8356 unsigned Opcode) { 8357 // We already checked this call's prototype; verify it doesn't modify errno. 8358 if (!I.onlyReadsMemory()) 8359 return false; 8360 8361 SDNodeFlags Flags; 8362 Flags.copyFMF(cast<FPMathOperator>(I)); 8363 8364 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8365 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8366 EVT VT = Tmp0.getValueType(); 8367 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8368 return true; 8369 } 8370 8371 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8372 // Handle inline assembly differently. 8373 if (I.isInlineAsm()) { 8374 visitInlineAsm(I); 8375 return; 8376 } 8377 8378 diagnoseDontCall(I); 8379 8380 if (Function *F = I.getCalledFunction()) { 8381 if (F->isDeclaration()) { 8382 // Is this an LLVM intrinsic or a target-specific intrinsic? 8383 unsigned IID = F->getIntrinsicID(); 8384 if (!IID) 8385 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8386 IID = II->getIntrinsicID(F); 8387 8388 if (IID) { 8389 visitIntrinsicCall(I, IID); 8390 return; 8391 } 8392 } 8393 8394 // Check for well-known libc/libm calls. If the function is internal, it 8395 // can't be a library call. Don't do the check if marked as nobuiltin for 8396 // some reason or the call site requires strict floating point semantics. 8397 LibFunc Func; 8398 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8399 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8400 LibInfo->hasOptimizedCodeGen(Func)) { 8401 switch (Func) { 8402 default: break; 8403 case LibFunc_bcmp: 8404 if (visitMemCmpBCmpCall(I)) 8405 return; 8406 break; 8407 case LibFunc_copysign: 8408 case LibFunc_copysignf: 8409 case LibFunc_copysignl: 8410 // We already checked this call's prototype; verify it doesn't modify 8411 // errno. 8412 if (I.onlyReadsMemory()) { 8413 SDValue LHS = getValue(I.getArgOperand(0)); 8414 SDValue RHS = getValue(I.getArgOperand(1)); 8415 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8416 LHS.getValueType(), LHS, RHS)); 8417 return; 8418 } 8419 break; 8420 case LibFunc_fabs: 8421 case LibFunc_fabsf: 8422 case LibFunc_fabsl: 8423 if (visitUnaryFloatCall(I, ISD::FABS)) 8424 return; 8425 break; 8426 case LibFunc_fmin: 8427 case LibFunc_fminf: 8428 case LibFunc_fminl: 8429 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8430 return; 8431 break; 8432 case LibFunc_fmax: 8433 case LibFunc_fmaxf: 8434 case LibFunc_fmaxl: 8435 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8436 return; 8437 break; 8438 case LibFunc_sin: 8439 case LibFunc_sinf: 8440 case LibFunc_sinl: 8441 if (visitUnaryFloatCall(I, ISD::FSIN)) 8442 return; 8443 break; 8444 case LibFunc_cos: 8445 case LibFunc_cosf: 8446 case LibFunc_cosl: 8447 if (visitUnaryFloatCall(I, ISD::FCOS)) 8448 return; 8449 break; 8450 case LibFunc_sqrt: 8451 case LibFunc_sqrtf: 8452 case LibFunc_sqrtl: 8453 case LibFunc_sqrt_finite: 8454 case LibFunc_sqrtf_finite: 8455 case LibFunc_sqrtl_finite: 8456 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8457 return; 8458 break; 8459 case LibFunc_floor: 8460 case LibFunc_floorf: 8461 case LibFunc_floorl: 8462 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8463 return; 8464 break; 8465 case LibFunc_nearbyint: 8466 case LibFunc_nearbyintf: 8467 case LibFunc_nearbyintl: 8468 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8469 return; 8470 break; 8471 case LibFunc_ceil: 8472 case LibFunc_ceilf: 8473 case LibFunc_ceill: 8474 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8475 return; 8476 break; 8477 case LibFunc_rint: 8478 case LibFunc_rintf: 8479 case LibFunc_rintl: 8480 if (visitUnaryFloatCall(I, ISD::FRINT)) 8481 return; 8482 break; 8483 case LibFunc_round: 8484 case LibFunc_roundf: 8485 case LibFunc_roundl: 8486 if (visitUnaryFloatCall(I, ISD::FROUND)) 8487 return; 8488 break; 8489 case LibFunc_trunc: 8490 case LibFunc_truncf: 8491 case LibFunc_truncl: 8492 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8493 return; 8494 break; 8495 case LibFunc_log2: 8496 case LibFunc_log2f: 8497 case LibFunc_log2l: 8498 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8499 return; 8500 break; 8501 case LibFunc_exp2: 8502 case LibFunc_exp2f: 8503 case LibFunc_exp2l: 8504 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8505 return; 8506 break; 8507 case LibFunc_memcmp: 8508 if (visitMemCmpBCmpCall(I)) 8509 return; 8510 break; 8511 case LibFunc_mempcpy: 8512 if (visitMemPCpyCall(I)) 8513 return; 8514 break; 8515 case LibFunc_memchr: 8516 if (visitMemChrCall(I)) 8517 return; 8518 break; 8519 case LibFunc_strcpy: 8520 if (visitStrCpyCall(I, false)) 8521 return; 8522 break; 8523 case LibFunc_stpcpy: 8524 if (visitStrCpyCall(I, true)) 8525 return; 8526 break; 8527 case LibFunc_strcmp: 8528 if (visitStrCmpCall(I)) 8529 return; 8530 break; 8531 case LibFunc_strlen: 8532 if (visitStrLenCall(I)) 8533 return; 8534 break; 8535 case LibFunc_strnlen: 8536 if (visitStrNLenCall(I)) 8537 return; 8538 break; 8539 } 8540 } 8541 } 8542 8543 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8544 // have to do anything here to lower funclet bundles. 8545 // CFGuardTarget bundles are lowered in LowerCallTo. 8546 assert(!I.hasOperandBundlesOtherThan( 8547 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8548 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8549 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8550 "Cannot lower calls with arbitrary operand bundles!"); 8551 8552 SDValue Callee = getValue(I.getCalledOperand()); 8553 8554 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8555 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8556 else 8557 // Check if we can potentially perform a tail call. More detailed checking 8558 // is be done within LowerCallTo, after more information about the call is 8559 // known. 8560 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8561 } 8562 8563 namespace { 8564 8565 /// AsmOperandInfo - This contains information for each constraint that we are 8566 /// lowering. 8567 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8568 public: 8569 /// CallOperand - If this is the result output operand or a clobber 8570 /// this is null, otherwise it is the incoming operand to the CallInst. 8571 /// This gets modified as the asm is processed. 8572 SDValue CallOperand; 8573 8574 /// AssignedRegs - If this is a register or register class operand, this 8575 /// contains the set of register corresponding to the operand. 8576 RegsForValue AssignedRegs; 8577 8578 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8579 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8580 } 8581 8582 /// Whether or not this operand accesses memory 8583 bool hasMemory(const TargetLowering &TLI) const { 8584 // Indirect operand accesses access memory. 8585 if (isIndirect) 8586 return true; 8587 8588 for (const auto &Code : Codes) 8589 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8590 return true; 8591 8592 return false; 8593 } 8594 }; 8595 8596 8597 } // end anonymous namespace 8598 8599 /// Make sure that the output operand \p OpInfo and its corresponding input 8600 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8601 /// out). 8602 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8603 SDISelAsmOperandInfo &MatchingOpInfo, 8604 SelectionDAG &DAG) { 8605 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8606 return; 8607 8608 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8609 const auto &TLI = DAG.getTargetLoweringInfo(); 8610 8611 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8612 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8613 OpInfo.ConstraintVT); 8614 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8615 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8616 MatchingOpInfo.ConstraintVT); 8617 if ((OpInfo.ConstraintVT.isInteger() != 8618 MatchingOpInfo.ConstraintVT.isInteger()) || 8619 (MatchRC.second != InputRC.second)) { 8620 // FIXME: error out in a more elegant fashion 8621 report_fatal_error("Unsupported asm: input constraint" 8622 " with a matching output constraint of" 8623 " incompatible type!"); 8624 } 8625 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8626 } 8627 8628 /// Get a direct memory input to behave well as an indirect operand. 8629 /// This may introduce stores, hence the need for a \p Chain. 8630 /// \return The (possibly updated) chain. 8631 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8632 SDISelAsmOperandInfo &OpInfo, 8633 SelectionDAG &DAG) { 8634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8635 8636 // If we don't have an indirect input, put it in the constpool if we can, 8637 // otherwise spill it to a stack slot. 8638 // TODO: This isn't quite right. We need to handle these according to 8639 // the addressing mode that the constraint wants. Also, this may take 8640 // an additional register for the computation and we don't want that 8641 // either. 8642 8643 // If the operand is a float, integer, or vector constant, spill to a 8644 // constant pool entry to get its address. 8645 const Value *OpVal = OpInfo.CallOperandVal; 8646 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8647 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8648 OpInfo.CallOperand = DAG.getConstantPool( 8649 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8650 return Chain; 8651 } 8652 8653 // Otherwise, create a stack slot and emit a store to it before the asm. 8654 Type *Ty = OpVal->getType(); 8655 auto &DL = DAG.getDataLayout(); 8656 uint64_t TySize = DL.getTypeAllocSize(Ty); 8657 MachineFunction &MF = DAG.getMachineFunction(); 8658 int SSFI = MF.getFrameInfo().CreateStackObject( 8659 TySize, DL.getPrefTypeAlign(Ty), false); 8660 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8661 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8662 MachinePointerInfo::getFixedStack(MF, SSFI), 8663 TLI.getMemValueType(DL, Ty)); 8664 OpInfo.CallOperand = StackSlot; 8665 8666 return Chain; 8667 } 8668 8669 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8670 /// specified operand. We prefer to assign virtual registers, to allow the 8671 /// register allocator to handle the assignment process. However, if the asm 8672 /// uses features that we can't model on machineinstrs, we have SDISel do the 8673 /// allocation. This produces generally horrible, but correct, code. 8674 /// 8675 /// OpInfo describes the operand 8676 /// RefOpInfo describes the matching operand if any, the operand otherwise 8677 static std::optional<unsigned> 8678 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8679 SDISelAsmOperandInfo &OpInfo, 8680 SDISelAsmOperandInfo &RefOpInfo) { 8681 LLVMContext &Context = *DAG.getContext(); 8682 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8683 8684 MachineFunction &MF = DAG.getMachineFunction(); 8685 SmallVector<unsigned, 4> Regs; 8686 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8687 8688 // No work to do for memory/address operands. 8689 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8690 OpInfo.ConstraintType == TargetLowering::C_Address) 8691 return std::nullopt; 8692 8693 // If this is a constraint for a single physreg, or a constraint for a 8694 // register class, find it. 8695 unsigned AssignedReg; 8696 const TargetRegisterClass *RC; 8697 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8698 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8699 // RC is unset only on failure. Return immediately. 8700 if (!RC) 8701 return std::nullopt; 8702 8703 // Get the actual register value type. This is important, because the user 8704 // may have asked for (e.g.) the AX register in i32 type. We need to 8705 // remember that AX is actually i16 to get the right extension. 8706 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8707 8708 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8709 // If this is an FP operand in an integer register (or visa versa), or more 8710 // generally if the operand value disagrees with the register class we plan 8711 // to stick it in, fix the operand type. 8712 // 8713 // If this is an input value, the bitcast to the new type is done now. 8714 // Bitcast for output value is done at the end of visitInlineAsm(). 8715 if ((OpInfo.Type == InlineAsm::isOutput || 8716 OpInfo.Type == InlineAsm::isInput) && 8717 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8718 // Try to convert to the first EVT that the reg class contains. If the 8719 // types are identical size, use a bitcast to convert (e.g. two differing 8720 // vector types). Note: output bitcast is done at the end of 8721 // visitInlineAsm(). 8722 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8723 // Exclude indirect inputs while they are unsupported because the code 8724 // to perform the load is missing and thus OpInfo.CallOperand still 8725 // refers to the input address rather than the pointed-to value. 8726 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8727 OpInfo.CallOperand = 8728 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8729 OpInfo.ConstraintVT = RegVT; 8730 // If the operand is an FP value and we want it in integer registers, 8731 // use the corresponding integer type. This turns an f64 value into 8732 // i64, which can be passed with two i32 values on a 32-bit machine. 8733 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8734 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8735 if (OpInfo.Type == InlineAsm::isInput) 8736 OpInfo.CallOperand = 8737 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8738 OpInfo.ConstraintVT = VT; 8739 } 8740 } 8741 } 8742 8743 // No need to allocate a matching input constraint since the constraint it's 8744 // matching to has already been allocated. 8745 if (OpInfo.isMatchingInputConstraint()) 8746 return std::nullopt; 8747 8748 EVT ValueVT = OpInfo.ConstraintVT; 8749 if (OpInfo.ConstraintVT == MVT::Other) 8750 ValueVT = RegVT; 8751 8752 // Initialize NumRegs. 8753 unsigned NumRegs = 1; 8754 if (OpInfo.ConstraintVT != MVT::Other) 8755 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8756 8757 // If this is a constraint for a specific physical register, like {r17}, 8758 // assign it now. 8759 8760 // If this associated to a specific register, initialize iterator to correct 8761 // place. If virtual, make sure we have enough registers 8762 8763 // Initialize iterator if necessary 8764 TargetRegisterClass::iterator I = RC->begin(); 8765 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8766 8767 // Do not check for single registers. 8768 if (AssignedReg) { 8769 I = std::find(I, RC->end(), AssignedReg); 8770 if (I == RC->end()) { 8771 // RC does not contain the selected register, which indicates a 8772 // mismatch between the register and the required type/bitwidth. 8773 return {AssignedReg}; 8774 } 8775 } 8776 8777 for (; NumRegs; --NumRegs, ++I) { 8778 assert(I != RC->end() && "Ran out of registers to allocate!"); 8779 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8780 Regs.push_back(R); 8781 } 8782 8783 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8784 return std::nullopt; 8785 } 8786 8787 static unsigned 8788 findMatchingInlineAsmOperand(unsigned OperandNo, 8789 const std::vector<SDValue> &AsmNodeOperands) { 8790 // Scan until we find the definition we already emitted of this operand. 8791 unsigned CurOp = InlineAsm::Op_FirstOperand; 8792 for (; OperandNo; --OperandNo) { 8793 // Advance to the next operand. 8794 unsigned OpFlag = 8795 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8796 assert((InlineAsm::isRegDefKind(OpFlag) || 8797 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8798 InlineAsm::isMemKind(OpFlag)) && 8799 "Skipped past definitions?"); 8800 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8801 } 8802 return CurOp; 8803 } 8804 8805 namespace { 8806 8807 class ExtraFlags { 8808 unsigned Flags = 0; 8809 8810 public: 8811 explicit ExtraFlags(const CallBase &Call) { 8812 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8813 if (IA->hasSideEffects()) 8814 Flags |= InlineAsm::Extra_HasSideEffects; 8815 if (IA->isAlignStack()) 8816 Flags |= InlineAsm::Extra_IsAlignStack; 8817 if (Call.isConvergent()) 8818 Flags |= InlineAsm::Extra_IsConvergent; 8819 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8820 } 8821 8822 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8823 // Ideally, we would only check against memory constraints. However, the 8824 // meaning of an Other constraint can be target-specific and we can't easily 8825 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8826 // for Other constraints as well. 8827 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8828 OpInfo.ConstraintType == TargetLowering::C_Other) { 8829 if (OpInfo.Type == InlineAsm::isInput) 8830 Flags |= InlineAsm::Extra_MayLoad; 8831 else if (OpInfo.Type == InlineAsm::isOutput) 8832 Flags |= InlineAsm::Extra_MayStore; 8833 else if (OpInfo.Type == InlineAsm::isClobber) 8834 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8835 } 8836 } 8837 8838 unsigned get() const { return Flags; } 8839 }; 8840 8841 } // end anonymous namespace 8842 8843 static bool isFunction(SDValue Op) { 8844 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8845 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8846 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8847 8848 // In normal "call dllimport func" instruction (non-inlineasm) it force 8849 // indirect access by specifing call opcode. And usually specially print 8850 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 8851 // not do in this way now. (In fact, this is similar with "Data Access" 8852 // action). So here we ignore dllimport function. 8853 if (Fn && !Fn->hasDLLImportStorageClass()) 8854 return true; 8855 } 8856 } 8857 return false; 8858 } 8859 8860 /// visitInlineAsm - Handle a call to an InlineAsm object. 8861 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 8862 const BasicBlock *EHPadBB) { 8863 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8864 8865 /// ConstraintOperands - Information about all of the constraints. 8866 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8867 8868 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8869 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8870 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8871 8872 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8873 // AsmDialect, MayLoad, MayStore). 8874 bool HasSideEffect = IA->hasSideEffects(); 8875 ExtraFlags ExtraInfo(Call); 8876 8877 for (auto &T : TargetConstraints) { 8878 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8879 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8880 8881 if (OpInfo.CallOperandVal) 8882 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8883 8884 if (!HasSideEffect) 8885 HasSideEffect = OpInfo.hasMemory(TLI); 8886 8887 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8888 // FIXME: Could we compute this on OpInfo rather than T? 8889 8890 // Compute the constraint code and ConstraintType to use. 8891 TLI.ComputeConstraintToUse(T, SDValue()); 8892 8893 if (T.ConstraintType == TargetLowering::C_Immediate && 8894 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8895 // We've delayed emitting a diagnostic like the "n" constraint because 8896 // inlining could cause an integer showing up. 8897 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8898 "' expects an integer constant " 8899 "expression"); 8900 8901 ExtraInfo.update(T); 8902 } 8903 8904 // We won't need to flush pending loads if this asm doesn't touch 8905 // memory and is nonvolatile. 8906 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8907 8908 bool EmitEHLabels = isa<InvokeInst>(Call); 8909 if (EmitEHLabels) { 8910 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 8911 } 8912 bool IsCallBr = isa<CallBrInst>(Call); 8913 8914 if (IsCallBr || EmitEHLabels) { 8915 // If this is a callbr or invoke we need to flush pending exports since 8916 // inlineasm_br and invoke are terminators. 8917 // We need to do this before nodes are glued to the inlineasm_br node. 8918 Chain = getControlRoot(); 8919 } 8920 8921 MCSymbol *BeginLabel = nullptr; 8922 if (EmitEHLabels) { 8923 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 8924 } 8925 8926 int OpNo = -1; 8927 SmallVector<StringRef> AsmStrs; 8928 IA->collectAsmStrs(AsmStrs); 8929 8930 // Second pass over the constraints: compute which constraint option to use. 8931 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8932 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 8933 OpNo++; 8934 8935 // If this is an output operand with a matching input operand, look up the 8936 // matching input. If their types mismatch, e.g. one is an integer, the 8937 // other is floating point, or their sizes are different, flag it as an 8938 // error. 8939 if (OpInfo.hasMatchingInput()) { 8940 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8941 patchMatchingInput(OpInfo, Input, DAG); 8942 } 8943 8944 // Compute the constraint code and ConstraintType to use. 8945 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8946 8947 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 8948 OpInfo.Type == InlineAsm::isClobber) || 8949 OpInfo.ConstraintType == TargetLowering::C_Address) 8950 continue; 8951 8952 // In Linux PIC model, there are 4 cases about value/label addressing: 8953 // 8954 // 1: Function call or Label jmp inside the module. 8955 // 2: Data access (such as global variable, static variable) inside module. 8956 // 3: Function call or Label jmp outside the module. 8957 // 4: Data access (such as global variable) outside the module. 8958 // 8959 // Due to current llvm inline asm architecture designed to not "recognize" 8960 // the asm code, there are quite troubles for us to treat mem addressing 8961 // differently for same value/adress used in different instuctions. 8962 // For example, in pic model, call a func may in plt way or direclty 8963 // pc-related, but lea/mov a function adress may use got. 8964 // 8965 // Here we try to "recognize" function call for the case 1 and case 3 in 8966 // inline asm. And try to adjust the constraint for them. 8967 // 8968 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 8969 // label, so here we don't handle jmp function label now, but we need to 8970 // enhance it (especilly in PIC model) if we meet meaningful requirements. 8971 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 8972 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 8973 TM.getCodeModel() != CodeModel::Large) { 8974 OpInfo.isIndirect = false; 8975 OpInfo.ConstraintType = TargetLowering::C_Address; 8976 } 8977 8978 // If this is a memory input, and if the operand is not indirect, do what we 8979 // need to provide an address for the memory input. 8980 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8981 !OpInfo.isIndirect) { 8982 assert((OpInfo.isMultipleAlternative || 8983 (OpInfo.Type == InlineAsm::isInput)) && 8984 "Can only indirectify direct input operands!"); 8985 8986 // Memory operands really want the address of the value. 8987 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8988 8989 // There is no longer a Value* corresponding to this operand. 8990 OpInfo.CallOperandVal = nullptr; 8991 8992 // It is now an indirect operand. 8993 OpInfo.isIndirect = true; 8994 } 8995 8996 } 8997 8998 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8999 std::vector<SDValue> AsmNodeOperands; 9000 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9001 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9002 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9003 9004 // If we have a !srcloc metadata node associated with it, we want to attach 9005 // this to the ultimately generated inline asm machineinstr. To do this, we 9006 // pass in the third operand as this (potentially null) inline asm MDNode. 9007 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9008 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9009 9010 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9011 // bits as operand 3. 9012 AsmNodeOperands.push_back(DAG.getTargetConstant( 9013 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9014 9015 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9016 // this, assign virtual and physical registers for inputs and otput. 9017 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9018 // Assign Registers. 9019 SDISelAsmOperandInfo &RefOpInfo = 9020 OpInfo.isMatchingInputConstraint() 9021 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9022 : OpInfo; 9023 const auto RegError = 9024 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9025 if (RegError) { 9026 const MachineFunction &MF = DAG.getMachineFunction(); 9027 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9028 const char *RegName = TRI.getName(*RegError); 9029 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9030 "' allocated for constraint '" + 9031 Twine(OpInfo.ConstraintCode) + 9032 "' does not match required type"); 9033 return; 9034 } 9035 9036 auto DetectWriteToReservedRegister = [&]() { 9037 const MachineFunction &MF = DAG.getMachineFunction(); 9038 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9039 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9040 if (Register::isPhysicalRegister(Reg) && 9041 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9042 const char *RegName = TRI.getName(Reg); 9043 emitInlineAsmError(Call, "write to reserved register '" + 9044 Twine(RegName) + "'"); 9045 return true; 9046 } 9047 } 9048 return false; 9049 }; 9050 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9051 (OpInfo.Type == InlineAsm::isInput && 9052 !OpInfo.isMatchingInputConstraint())) && 9053 "Only address as input operand is allowed."); 9054 9055 switch (OpInfo.Type) { 9056 case InlineAsm::isOutput: 9057 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9058 unsigned ConstraintID = 9059 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9060 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9061 "Failed to convert memory constraint code to constraint id."); 9062 9063 // Add information to the INLINEASM node to know about this output. 9064 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9065 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9066 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9067 MVT::i32)); 9068 AsmNodeOperands.push_back(OpInfo.CallOperand); 9069 } else { 9070 // Otherwise, this outputs to a register (directly for C_Register / 9071 // C_RegisterClass, and a target-defined fashion for 9072 // C_Immediate/C_Other). Find a register that we can use. 9073 if (OpInfo.AssignedRegs.Regs.empty()) { 9074 emitInlineAsmError( 9075 Call, "couldn't allocate output register for constraint '" + 9076 Twine(OpInfo.ConstraintCode) + "'"); 9077 return; 9078 } 9079 9080 if (DetectWriteToReservedRegister()) 9081 return; 9082 9083 // Add information to the INLINEASM node to know that this register is 9084 // set. 9085 OpInfo.AssignedRegs.AddInlineAsmOperands( 9086 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9087 : InlineAsm::Kind_RegDef, 9088 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9089 } 9090 break; 9091 9092 case InlineAsm::isInput: 9093 case InlineAsm::isLabel: { 9094 SDValue InOperandVal = OpInfo.CallOperand; 9095 9096 if (OpInfo.isMatchingInputConstraint()) { 9097 // If this is required to match an output register we have already set, 9098 // just use its register. 9099 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9100 AsmNodeOperands); 9101 unsigned OpFlag = 9102 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9103 if (InlineAsm::isRegDefKind(OpFlag) || 9104 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9105 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9106 if (OpInfo.isIndirect) { 9107 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9108 emitInlineAsmError(Call, "inline asm not supported yet: " 9109 "don't know how to handle tied " 9110 "indirect register inputs"); 9111 return; 9112 } 9113 9114 SmallVector<unsigned, 4> Regs; 9115 MachineFunction &MF = DAG.getMachineFunction(); 9116 MachineRegisterInfo &MRI = MF.getRegInfo(); 9117 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9118 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9119 Register TiedReg = R->getReg(); 9120 MVT RegVT = R->getSimpleValueType(0); 9121 const TargetRegisterClass *RC = 9122 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9123 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9124 : TRI.getMinimalPhysRegClass(TiedReg); 9125 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9126 for (unsigned i = 0; i != NumRegs; ++i) 9127 Regs.push_back(MRI.createVirtualRegister(RC)); 9128 9129 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9130 9131 SDLoc dl = getCurSDLoc(); 9132 // Use the produced MatchedRegs object to 9133 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 9134 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9135 true, OpInfo.getMatchedOperand(), dl, 9136 DAG, AsmNodeOperands); 9137 break; 9138 } 9139 9140 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9141 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9142 "Unexpected number of operands"); 9143 // Add information to the INLINEASM node to know about this input. 9144 // See InlineAsm.h isUseOperandTiedToDef. 9145 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9146 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9147 OpInfo.getMatchedOperand()); 9148 AsmNodeOperands.push_back(DAG.getTargetConstant( 9149 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9150 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9151 break; 9152 } 9153 9154 // Treat indirect 'X' constraint as memory. 9155 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9156 OpInfo.isIndirect) 9157 OpInfo.ConstraintType = TargetLowering::C_Memory; 9158 9159 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9160 OpInfo.ConstraintType == TargetLowering::C_Other) { 9161 std::vector<SDValue> Ops; 9162 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9163 Ops, DAG); 9164 if (Ops.empty()) { 9165 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9166 if (isa<ConstantSDNode>(InOperandVal)) { 9167 emitInlineAsmError(Call, "value out of range for constraint '" + 9168 Twine(OpInfo.ConstraintCode) + "'"); 9169 return; 9170 } 9171 9172 emitInlineAsmError(Call, 9173 "invalid operand for inline asm constraint '" + 9174 Twine(OpInfo.ConstraintCode) + "'"); 9175 return; 9176 } 9177 9178 // Add information to the INLINEASM node to know about this input. 9179 unsigned ResOpType = 9180 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9181 AsmNodeOperands.push_back(DAG.getTargetConstant( 9182 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9183 llvm::append_range(AsmNodeOperands, Ops); 9184 break; 9185 } 9186 9187 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9188 assert((OpInfo.isIndirect || 9189 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9190 "Operand must be indirect to be a mem!"); 9191 assert(InOperandVal.getValueType() == 9192 TLI.getPointerTy(DAG.getDataLayout()) && 9193 "Memory operands expect pointer values"); 9194 9195 unsigned ConstraintID = 9196 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9197 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9198 "Failed to convert memory constraint code to constraint id."); 9199 9200 // Add information to the INLINEASM node to know about this input. 9201 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9202 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9203 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9204 getCurSDLoc(), 9205 MVT::i32)); 9206 AsmNodeOperands.push_back(InOperandVal); 9207 break; 9208 } 9209 9210 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9211 assert(InOperandVal.getValueType() == 9212 TLI.getPointerTy(DAG.getDataLayout()) && 9213 "Address operands expect pointer values"); 9214 9215 unsigned ConstraintID = 9216 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9217 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9218 "Failed to convert memory constraint code to constraint id."); 9219 9220 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9221 9222 SDValue AsmOp = InOperandVal; 9223 if (isFunction(InOperandVal)) { 9224 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9225 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9226 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9227 InOperandVal.getValueType(), 9228 GA->getOffset()); 9229 } 9230 9231 // Add information to the INLINEASM node to know about this input. 9232 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9233 9234 AsmNodeOperands.push_back( 9235 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9236 9237 AsmNodeOperands.push_back(AsmOp); 9238 break; 9239 } 9240 9241 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9242 OpInfo.ConstraintType == TargetLowering::C_Register) && 9243 "Unknown constraint type!"); 9244 9245 // TODO: Support this. 9246 if (OpInfo.isIndirect) { 9247 emitInlineAsmError( 9248 Call, "Don't know how to handle indirect register inputs yet " 9249 "for constraint '" + 9250 Twine(OpInfo.ConstraintCode) + "'"); 9251 return; 9252 } 9253 9254 // Copy the input into the appropriate registers. 9255 if (OpInfo.AssignedRegs.Regs.empty()) { 9256 emitInlineAsmError(Call, 9257 "couldn't allocate input reg for constraint '" + 9258 Twine(OpInfo.ConstraintCode) + "'"); 9259 return; 9260 } 9261 9262 if (DetectWriteToReservedRegister()) 9263 return; 9264 9265 SDLoc dl = getCurSDLoc(); 9266 9267 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 9268 &Call); 9269 9270 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9271 dl, DAG, AsmNodeOperands); 9272 break; 9273 } 9274 case InlineAsm::isClobber: 9275 // Add the clobbered value to the operand list, so that the register 9276 // allocator is aware that the physreg got clobbered. 9277 if (!OpInfo.AssignedRegs.Regs.empty()) 9278 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9279 false, 0, getCurSDLoc(), DAG, 9280 AsmNodeOperands); 9281 break; 9282 } 9283 } 9284 9285 // Finish up input operands. Set the input chain and add the flag last. 9286 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9287 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 9288 9289 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9290 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9291 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9292 Flag = Chain.getValue(1); 9293 9294 // Do additional work to generate outputs. 9295 9296 SmallVector<EVT, 1> ResultVTs; 9297 SmallVector<SDValue, 1> ResultValues; 9298 SmallVector<SDValue, 8> OutChains; 9299 9300 llvm::Type *CallResultType = Call.getType(); 9301 ArrayRef<Type *> ResultTypes; 9302 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9303 ResultTypes = StructResult->elements(); 9304 else if (!CallResultType->isVoidTy()) 9305 ResultTypes = ArrayRef(CallResultType); 9306 9307 auto CurResultType = ResultTypes.begin(); 9308 auto handleRegAssign = [&](SDValue V) { 9309 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9310 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9311 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9312 ++CurResultType; 9313 // If the type of the inline asm call site return value is different but has 9314 // same size as the type of the asm output bitcast it. One example of this 9315 // is for vectors with different width / number of elements. This can 9316 // happen for register classes that can contain multiple different value 9317 // types. The preg or vreg allocated may not have the same VT as was 9318 // expected. 9319 // 9320 // This can also happen for a return value that disagrees with the register 9321 // class it is put in, eg. a double in a general-purpose register on a 9322 // 32-bit machine. 9323 if (ResultVT != V.getValueType() && 9324 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9325 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9326 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9327 V.getValueType().isInteger()) { 9328 // If a result value was tied to an input value, the computed result 9329 // may have a wider width than the expected result. Extract the 9330 // relevant portion. 9331 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9332 } 9333 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9334 ResultVTs.push_back(ResultVT); 9335 ResultValues.push_back(V); 9336 }; 9337 9338 // Deal with output operands. 9339 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9340 if (OpInfo.Type == InlineAsm::isOutput) { 9341 SDValue Val; 9342 // Skip trivial output operands. 9343 if (OpInfo.AssignedRegs.Regs.empty()) 9344 continue; 9345 9346 switch (OpInfo.ConstraintType) { 9347 case TargetLowering::C_Register: 9348 case TargetLowering::C_RegisterClass: 9349 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9350 Chain, &Flag, &Call); 9351 break; 9352 case TargetLowering::C_Immediate: 9353 case TargetLowering::C_Other: 9354 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 9355 OpInfo, DAG); 9356 break; 9357 case TargetLowering::C_Memory: 9358 break; // Already handled. 9359 case TargetLowering::C_Address: 9360 break; // Silence warning. 9361 case TargetLowering::C_Unknown: 9362 assert(false && "Unexpected unknown constraint"); 9363 } 9364 9365 // Indirect output manifest as stores. Record output chains. 9366 if (OpInfo.isIndirect) { 9367 const Value *Ptr = OpInfo.CallOperandVal; 9368 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9369 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9370 MachinePointerInfo(Ptr)); 9371 OutChains.push_back(Store); 9372 } else { 9373 // generate CopyFromRegs to associated registers. 9374 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9375 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9376 for (const SDValue &V : Val->op_values()) 9377 handleRegAssign(V); 9378 } else 9379 handleRegAssign(Val); 9380 } 9381 } 9382 } 9383 9384 // Set results. 9385 if (!ResultValues.empty()) { 9386 assert(CurResultType == ResultTypes.end() && 9387 "Mismatch in number of ResultTypes"); 9388 assert(ResultValues.size() == ResultTypes.size() && 9389 "Mismatch in number of output operands in asm result"); 9390 9391 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9392 DAG.getVTList(ResultVTs), ResultValues); 9393 setValue(&Call, V); 9394 } 9395 9396 // Collect store chains. 9397 if (!OutChains.empty()) 9398 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9399 9400 if (EmitEHLabels) { 9401 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9402 } 9403 9404 // Only Update Root if inline assembly has a memory effect. 9405 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9406 EmitEHLabels) 9407 DAG.setRoot(Chain); 9408 } 9409 9410 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9411 const Twine &Message) { 9412 LLVMContext &Ctx = *DAG.getContext(); 9413 Ctx.emitError(&Call, Message); 9414 9415 // Make sure we leave the DAG in a valid state 9416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9417 SmallVector<EVT, 1> ValueVTs; 9418 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9419 9420 if (ValueVTs.empty()) 9421 return; 9422 9423 SmallVector<SDValue, 1> Ops; 9424 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9425 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9426 9427 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9428 } 9429 9430 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9431 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9432 MVT::Other, getRoot(), 9433 getValue(I.getArgOperand(0)), 9434 DAG.getSrcValue(I.getArgOperand(0)))); 9435 } 9436 9437 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9439 const DataLayout &DL = DAG.getDataLayout(); 9440 SDValue V = DAG.getVAArg( 9441 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9442 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9443 DL.getABITypeAlign(I.getType()).value()); 9444 DAG.setRoot(V.getValue(1)); 9445 9446 if (I.getType()->isPointerTy()) 9447 V = DAG.getPtrExtOrTrunc( 9448 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9449 setValue(&I, V); 9450 } 9451 9452 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9453 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9454 MVT::Other, getRoot(), 9455 getValue(I.getArgOperand(0)), 9456 DAG.getSrcValue(I.getArgOperand(0)))); 9457 } 9458 9459 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9460 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9461 MVT::Other, getRoot(), 9462 getValue(I.getArgOperand(0)), 9463 getValue(I.getArgOperand(1)), 9464 DAG.getSrcValue(I.getArgOperand(0)), 9465 DAG.getSrcValue(I.getArgOperand(1)))); 9466 } 9467 9468 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9469 const Instruction &I, 9470 SDValue Op) { 9471 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9472 if (!Range) 9473 return Op; 9474 9475 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9476 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9477 return Op; 9478 9479 APInt Lo = CR.getUnsignedMin(); 9480 if (!Lo.isMinValue()) 9481 return Op; 9482 9483 APInt Hi = CR.getUnsignedMax(); 9484 unsigned Bits = std::max(Hi.getActiveBits(), 9485 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9486 9487 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9488 9489 SDLoc SL = getCurSDLoc(); 9490 9491 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9492 DAG.getValueType(SmallVT)); 9493 unsigned NumVals = Op.getNode()->getNumValues(); 9494 if (NumVals == 1) 9495 return ZExt; 9496 9497 SmallVector<SDValue, 4> Ops; 9498 9499 Ops.push_back(ZExt); 9500 for (unsigned I = 1; I != NumVals; ++I) 9501 Ops.push_back(Op.getValue(I)); 9502 9503 return DAG.getMergeValues(Ops, SL); 9504 } 9505 9506 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9507 /// the call being lowered. 9508 /// 9509 /// This is a helper for lowering intrinsics that follow a target calling 9510 /// convention or require stack pointer adjustment. Only a subset of the 9511 /// intrinsic's operands need to participate in the calling convention. 9512 void SelectionDAGBuilder::populateCallLoweringInfo( 9513 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9514 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9515 bool IsPatchPoint) { 9516 TargetLowering::ArgListTy Args; 9517 Args.reserve(NumArgs); 9518 9519 // Populate the argument list. 9520 // Attributes for args start at offset 1, after the return attribute. 9521 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9522 ArgI != ArgE; ++ArgI) { 9523 const Value *V = Call->getOperand(ArgI); 9524 9525 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9526 9527 TargetLowering::ArgListEntry Entry; 9528 Entry.Node = getValue(V); 9529 Entry.Ty = V->getType(); 9530 Entry.setAttributes(Call, ArgI); 9531 Args.push_back(Entry); 9532 } 9533 9534 CLI.setDebugLoc(getCurSDLoc()) 9535 .setChain(getRoot()) 9536 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9537 .setDiscardResult(Call->use_empty()) 9538 .setIsPatchPoint(IsPatchPoint) 9539 .setIsPreallocated( 9540 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9541 } 9542 9543 /// Add a stack map intrinsic call's live variable operands to a stackmap 9544 /// or patchpoint target node's operand list. 9545 /// 9546 /// Constants are converted to TargetConstants purely as an optimization to 9547 /// avoid constant materialization and register allocation. 9548 /// 9549 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9550 /// generate addess computation nodes, and so FinalizeISel can convert the 9551 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9552 /// address materialization and register allocation, but may also be required 9553 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9554 /// alloca in the entry block, then the runtime may assume that the alloca's 9555 /// StackMap location can be read immediately after compilation and that the 9556 /// location is valid at any point during execution (this is similar to the 9557 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9558 /// only available in a register, then the runtime would need to trap when 9559 /// execution reaches the StackMap in order to read the alloca's location. 9560 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9561 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9562 SelectionDAGBuilder &Builder) { 9563 SelectionDAG &DAG = Builder.DAG; 9564 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9565 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9566 9567 // Things on the stack are pointer-typed, meaning that they are already 9568 // legal and can be emitted directly to target nodes. 9569 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9570 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9571 } else { 9572 // Otherwise emit a target independent node to be legalised. 9573 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9574 } 9575 } 9576 } 9577 9578 /// Lower llvm.experimental.stackmap. 9579 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9580 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9581 // [live variables...]) 9582 9583 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9584 9585 SDValue Chain, InFlag, Callee; 9586 SmallVector<SDValue, 32> Ops; 9587 9588 SDLoc DL = getCurSDLoc(); 9589 Callee = getValue(CI.getCalledOperand()); 9590 9591 // The stackmap intrinsic only records the live variables (the arguments 9592 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9593 // intrinsic, this won't be lowered to a function call. This means we don't 9594 // have to worry about calling conventions and target specific lowering code. 9595 // Instead we perform the call lowering right here. 9596 // 9597 // chain, flag = CALLSEQ_START(chain, 0, 0) 9598 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9599 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9600 // 9601 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9602 InFlag = Chain.getValue(1); 9603 9604 // Add the STACKMAP operands, starting with DAG house-keeping. 9605 Ops.push_back(Chain); 9606 Ops.push_back(InFlag); 9607 9608 // Add the <id>, <numShadowBytes> operands. 9609 // 9610 // These do not require legalisation, and can be emitted directly to target 9611 // constant nodes. 9612 SDValue ID = getValue(CI.getArgOperand(0)); 9613 assert(ID.getValueType() == MVT::i64); 9614 SDValue IDConst = DAG.getTargetConstant( 9615 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9616 Ops.push_back(IDConst); 9617 9618 SDValue Shad = getValue(CI.getArgOperand(1)); 9619 assert(Shad.getValueType() == MVT::i32); 9620 SDValue ShadConst = DAG.getTargetConstant( 9621 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9622 Ops.push_back(ShadConst); 9623 9624 // Add the live variables. 9625 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9626 9627 // Create the STACKMAP node. 9628 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9629 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9630 InFlag = Chain.getValue(1); 9631 9632 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL); 9633 9634 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9635 9636 // Set the root to the target-lowered call chain. 9637 DAG.setRoot(Chain); 9638 9639 // Inform the Frame Information that we have a stackmap in this function. 9640 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9641 } 9642 9643 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9644 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9645 const BasicBlock *EHPadBB) { 9646 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9647 // i32 <numBytes>, 9648 // i8* <target>, 9649 // i32 <numArgs>, 9650 // [Args...], 9651 // [live variables...]) 9652 9653 CallingConv::ID CC = CB.getCallingConv(); 9654 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9655 bool HasDef = !CB.getType()->isVoidTy(); 9656 SDLoc dl = getCurSDLoc(); 9657 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9658 9659 // Handle immediate and symbolic callees. 9660 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9661 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9662 /*isTarget=*/true); 9663 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9664 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9665 SDLoc(SymbolicCallee), 9666 SymbolicCallee->getValueType(0)); 9667 9668 // Get the real number of arguments participating in the call <numArgs> 9669 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9670 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9671 9672 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9673 // Intrinsics include all meta-operands up to but not including CC. 9674 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9675 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9676 "Not enough arguments provided to the patchpoint intrinsic"); 9677 9678 // For AnyRegCC the arguments are lowered later on manually. 9679 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9680 Type *ReturnTy = 9681 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9682 9683 TargetLowering::CallLoweringInfo CLI(DAG); 9684 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9685 ReturnTy, true); 9686 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9687 9688 SDNode *CallEnd = Result.second.getNode(); 9689 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9690 CallEnd = CallEnd->getOperand(0).getNode(); 9691 9692 /// Get a call instruction from the call sequence chain. 9693 /// Tail calls are not allowed. 9694 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9695 "Expected a callseq node."); 9696 SDNode *Call = CallEnd->getOperand(0).getNode(); 9697 bool HasGlue = Call->getGluedNode(); 9698 9699 // Replace the target specific call node with the patchable intrinsic. 9700 SmallVector<SDValue, 8> Ops; 9701 9702 // Push the chain. 9703 Ops.push_back(*(Call->op_begin())); 9704 9705 // Optionally, push the glue (if any). 9706 if (HasGlue) 9707 Ops.push_back(*(Call->op_end() - 1)); 9708 9709 // Push the register mask info. 9710 if (HasGlue) 9711 Ops.push_back(*(Call->op_end() - 2)); 9712 else 9713 Ops.push_back(*(Call->op_end() - 1)); 9714 9715 // Add the <id> and <numBytes> constants. 9716 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9717 Ops.push_back(DAG.getTargetConstant( 9718 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9719 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9720 Ops.push_back(DAG.getTargetConstant( 9721 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9722 MVT::i32)); 9723 9724 // Add the callee. 9725 Ops.push_back(Callee); 9726 9727 // Adjust <numArgs> to account for any arguments that have been passed on the 9728 // stack instead. 9729 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9730 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9731 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9732 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9733 9734 // Add the calling convention 9735 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9736 9737 // Add the arguments we omitted previously. The register allocator should 9738 // place these in any free register. 9739 if (IsAnyRegCC) 9740 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9741 Ops.push_back(getValue(CB.getArgOperand(i))); 9742 9743 // Push the arguments from the call instruction. 9744 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9745 Ops.append(Call->op_begin() + 2, e); 9746 9747 // Push live variables for the stack map. 9748 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9749 9750 SDVTList NodeTys; 9751 if (IsAnyRegCC && HasDef) { 9752 // Create the return types based on the intrinsic definition 9753 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9754 SmallVector<EVT, 3> ValueVTs; 9755 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9756 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9757 9758 // There is always a chain and a glue type at the end 9759 ValueVTs.push_back(MVT::Other); 9760 ValueVTs.push_back(MVT::Glue); 9761 NodeTys = DAG.getVTList(ValueVTs); 9762 } else 9763 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9764 9765 // Replace the target specific call node with a PATCHPOINT node. 9766 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9767 9768 // Update the NodeMap. 9769 if (HasDef) { 9770 if (IsAnyRegCC) 9771 setValue(&CB, SDValue(PPV.getNode(), 0)); 9772 else 9773 setValue(&CB, Result.first); 9774 } 9775 9776 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9777 // call sequence. Furthermore the location of the chain and glue can change 9778 // when the AnyReg calling convention is used and the intrinsic returns a 9779 // value. 9780 if (IsAnyRegCC && HasDef) { 9781 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9782 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9783 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9784 } else 9785 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9786 DAG.DeleteNode(Call); 9787 9788 // Inform the Frame Information that we have a patchpoint in this function. 9789 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9790 } 9791 9792 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9793 unsigned Intrinsic) { 9794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9795 SDValue Op1 = getValue(I.getArgOperand(0)); 9796 SDValue Op2; 9797 if (I.arg_size() > 1) 9798 Op2 = getValue(I.getArgOperand(1)); 9799 SDLoc dl = getCurSDLoc(); 9800 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9801 SDValue Res; 9802 SDNodeFlags SDFlags; 9803 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9804 SDFlags.copyFMF(*FPMO); 9805 9806 switch (Intrinsic) { 9807 case Intrinsic::vector_reduce_fadd: 9808 if (SDFlags.hasAllowReassociation()) 9809 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9810 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9811 SDFlags); 9812 else 9813 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9814 break; 9815 case Intrinsic::vector_reduce_fmul: 9816 if (SDFlags.hasAllowReassociation()) 9817 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9818 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9819 SDFlags); 9820 else 9821 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9822 break; 9823 case Intrinsic::vector_reduce_add: 9824 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9825 break; 9826 case Intrinsic::vector_reduce_mul: 9827 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9828 break; 9829 case Intrinsic::vector_reduce_and: 9830 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9831 break; 9832 case Intrinsic::vector_reduce_or: 9833 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9834 break; 9835 case Intrinsic::vector_reduce_xor: 9836 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9837 break; 9838 case Intrinsic::vector_reduce_smax: 9839 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9840 break; 9841 case Intrinsic::vector_reduce_smin: 9842 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9843 break; 9844 case Intrinsic::vector_reduce_umax: 9845 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9846 break; 9847 case Intrinsic::vector_reduce_umin: 9848 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9849 break; 9850 case Intrinsic::vector_reduce_fmax: 9851 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9852 break; 9853 case Intrinsic::vector_reduce_fmin: 9854 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9855 break; 9856 default: 9857 llvm_unreachable("Unhandled vector reduce intrinsic"); 9858 } 9859 setValue(&I, Res); 9860 } 9861 9862 /// Returns an AttributeList representing the attributes applied to the return 9863 /// value of the given call. 9864 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9865 SmallVector<Attribute::AttrKind, 2> Attrs; 9866 if (CLI.RetSExt) 9867 Attrs.push_back(Attribute::SExt); 9868 if (CLI.RetZExt) 9869 Attrs.push_back(Attribute::ZExt); 9870 if (CLI.IsInReg) 9871 Attrs.push_back(Attribute::InReg); 9872 9873 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9874 Attrs); 9875 } 9876 9877 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9878 /// implementation, which just calls LowerCall. 9879 /// FIXME: When all targets are 9880 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9881 std::pair<SDValue, SDValue> 9882 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9883 // Handle the incoming return values from the call. 9884 CLI.Ins.clear(); 9885 Type *OrigRetTy = CLI.RetTy; 9886 SmallVector<EVT, 4> RetTys; 9887 SmallVector<uint64_t, 4> Offsets; 9888 auto &DL = CLI.DAG.getDataLayout(); 9889 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9890 9891 if (CLI.IsPostTypeLegalization) { 9892 // If we are lowering a libcall after legalization, split the return type. 9893 SmallVector<EVT, 4> OldRetTys; 9894 SmallVector<uint64_t, 4> OldOffsets; 9895 RetTys.swap(OldRetTys); 9896 Offsets.swap(OldOffsets); 9897 9898 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9899 EVT RetVT = OldRetTys[i]; 9900 uint64_t Offset = OldOffsets[i]; 9901 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9902 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9903 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9904 RetTys.append(NumRegs, RegisterVT); 9905 for (unsigned j = 0; j != NumRegs; ++j) 9906 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9907 } 9908 } 9909 9910 SmallVector<ISD::OutputArg, 4> Outs; 9911 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9912 9913 bool CanLowerReturn = 9914 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9915 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9916 9917 SDValue DemoteStackSlot; 9918 int DemoteStackIdx = -100; 9919 if (!CanLowerReturn) { 9920 // FIXME: equivalent assert? 9921 // assert(!CS.hasInAllocaArgument() && 9922 // "sret demotion is incompatible with inalloca"); 9923 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9924 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9925 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9926 DemoteStackIdx = 9927 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9928 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9929 DL.getAllocaAddrSpace()); 9930 9931 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9932 ArgListEntry Entry; 9933 Entry.Node = DemoteStackSlot; 9934 Entry.Ty = StackSlotPtrType; 9935 Entry.IsSExt = false; 9936 Entry.IsZExt = false; 9937 Entry.IsInReg = false; 9938 Entry.IsSRet = true; 9939 Entry.IsNest = false; 9940 Entry.IsByVal = false; 9941 Entry.IsByRef = false; 9942 Entry.IsReturned = false; 9943 Entry.IsSwiftSelf = false; 9944 Entry.IsSwiftAsync = false; 9945 Entry.IsSwiftError = false; 9946 Entry.IsCFGuardTarget = false; 9947 Entry.Alignment = Alignment; 9948 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9949 CLI.NumFixedArgs += 1; 9950 CLI.getArgs()[0].IndirectType = CLI.RetTy; 9951 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9952 9953 // sret demotion isn't compatible with tail-calls, since the sret argument 9954 // points into the callers stack frame. 9955 CLI.IsTailCall = false; 9956 } else { 9957 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9958 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 9959 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9960 ISD::ArgFlagsTy Flags; 9961 if (NeedsRegBlock) { 9962 Flags.setInConsecutiveRegs(); 9963 if (I == RetTys.size() - 1) 9964 Flags.setInConsecutiveRegsLast(); 9965 } 9966 EVT VT = RetTys[I]; 9967 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9968 CLI.CallConv, VT); 9969 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9970 CLI.CallConv, VT); 9971 for (unsigned i = 0; i != NumRegs; ++i) { 9972 ISD::InputArg MyFlags; 9973 MyFlags.Flags = Flags; 9974 MyFlags.VT = RegisterVT; 9975 MyFlags.ArgVT = VT; 9976 MyFlags.Used = CLI.IsReturnValueUsed; 9977 if (CLI.RetTy->isPointerTy()) { 9978 MyFlags.Flags.setPointer(); 9979 MyFlags.Flags.setPointerAddrSpace( 9980 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9981 } 9982 if (CLI.RetSExt) 9983 MyFlags.Flags.setSExt(); 9984 if (CLI.RetZExt) 9985 MyFlags.Flags.setZExt(); 9986 if (CLI.IsInReg) 9987 MyFlags.Flags.setInReg(); 9988 CLI.Ins.push_back(MyFlags); 9989 } 9990 } 9991 } 9992 9993 // We push in swifterror return as the last element of CLI.Ins. 9994 ArgListTy &Args = CLI.getArgs(); 9995 if (supportSwiftError()) { 9996 for (const ArgListEntry &Arg : Args) { 9997 if (Arg.IsSwiftError) { 9998 ISD::InputArg MyFlags; 9999 MyFlags.VT = getPointerTy(DL); 10000 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10001 MyFlags.Flags.setSwiftError(); 10002 CLI.Ins.push_back(MyFlags); 10003 } 10004 } 10005 } 10006 10007 // Handle all of the outgoing arguments. 10008 CLI.Outs.clear(); 10009 CLI.OutVals.clear(); 10010 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10011 SmallVector<EVT, 4> ValueVTs; 10012 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10013 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10014 Type *FinalType = Args[i].Ty; 10015 if (Args[i].IsByVal) 10016 FinalType = Args[i].IndirectType; 10017 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10018 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10019 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10020 ++Value) { 10021 EVT VT = ValueVTs[Value]; 10022 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10023 SDValue Op = SDValue(Args[i].Node.getNode(), 10024 Args[i].Node.getResNo() + Value); 10025 ISD::ArgFlagsTy Flags; 10026 10027 // Certain targets (such as MIPS), may have a different ABI alignment 10028 // for a type depending on the context. Give the target a chance to 10029 // specify the alignment it wants. 10030 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10031 Flags.setOrigAlign(OriginalAlignment); 10032 10033 if (Args[i].Ty->isPointerTy()) { 10034 Flags.setPointer(); 10035 Flags.setPointerAddrSpace( 10036 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10037 } 10038 if (Args[i].IsZExt) 10039 Flags.setZExt(); 10040 if (Args[i].IsSExt) 10041 Flags.setSExt(); 10042 if (Args[i].IsInReg) { 10043 // If we are using vectorcall calling convention, a structure that is 10044 // passed InReg - is surely an HVA 10045 if (CLI.CallConv == CallingConv::X86_VectorCall && 10046 isa<StructType>(FinalType)) { 10047 // The first value of a structure is marked 10048 if (0 == Value) 10049 Flags.setHvaStart(); 10050 Flags.setHva(); 10051 } 10052 // Set InReg Flag 10053 Flags.setInReg(); 10054 } 10055 if (Args[i].IsSRet) 10056 Flags.setSRet(); 10057 if (Args[i].IsSwiftSelf) 10058 Flags.setSwiftSelf(); 10059 if (Args[i].IsSwiftAsync) 10060 Flags.setSwiftAsync(); 10061 if (Args[i].IsSwiftError) 10062 Flags.setSwiftError(); 10063 if (Args[i].IsCFGuardTarget) 10064 Flags.setCFGuardTarget(); 10065 if (Args[i].IsByVal) 10066 Flags.setByVal(); 10067 if (Args[i].IsByRef) 10068 Flags.setByRef(); 10069 if (Args[i].IsPreallocated) { 10070 Flags.setPreallocated(); 10071 // Set the byval flag for CCAssignFn callbacks that don't know about 10072 // preallocated. This way we can know how many bytes we should've 10073 // allocated and how many bytes a callee cleanup function will pop. If 10074 // we port preallocated to more targets, we'll have to add custom 10075 // preallocated handling in the various CC lowering callbacks. 10076 Flags.setByVal(); 10077 } 10078 if (Args[i].IsInAlloca) { 10079 Flags.setInAlloca(); 10080 // Set the byval flag for CCAssignFn callbacks that don't know about 10081 // inalloca. This way we can know how many bytes we should've allocated 10082 // and how many bytes a callee cleanup function will pop. If we port 10083 // inalloca to more targets, we'll have to add custom inalloca handling 10084 // in the various CC lowering callbacks. 10085 Flags.setByVal(); 10086 } 10087 Align MemAlign; 10088 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10089 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10090 Flags.setByValSize(FrameSize); 10091 10092 // info is not there but there are cases it cannot get right. 10093 if (auto MA = Args[i].Alignment) 10094 MemAlign = *MA; 10095 else 10096 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10097 } else if (auto MA = Args[i].Alignment) { 10098 MemAlign = *MA; 10099 } else { 10100 MemAlign = OriginalAlignment; 10101 } 10102 Flags.setMemAlign(MemAlign); 10103 if (Args[i].IsNest) 10104 Flags.setNest(); 10105 if (NeedsRegBlock) 10106 Flags.setInConsecutiveRegs(); 10107 10108 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10109 CLI.CallConv, VT); 10110 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10111 CLI.CallConv, VT); 10112 SmallVector<SDValue, 4> Parts(NumParts); 10113 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10114 10115 if (Args[i].IsSExt) 10116 ExtendKind = ISD::SIGN_EXTEND; 10117 else if (Args[i].IsZExt) 10118 ExtendKind = ISD::ZERO_EXTEND; 10119 10120 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10121 // for now. 10122 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10123 CanLowerReturn) { 10124 assert((CLI.RetTy == Args[i].Ty || 10125 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10126 CLI.RetTy->getPointerAddressSpace() == 10127 Args[i].Ty->getPointerAddressSpace())) && 10128 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10129 // Before passing 'returned' to the target lowering code, ensure that 10130 // either the register MVT and the actual EVT are the same size or that 10131 // the return value and argument are extended in the same way; in these 10132 // cases it's safe to pass the argument register value unchanged as the 10133 // return register value (although it's at the target's option whether 10134 // to do so) 10135 // TODO: allow code generation to take advantage of partially preserved 10136 // registers rather than clobbering the entire register when the 10137 // parameter extension method is not compatible with the return 10138 // extension method 10139 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10140 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10141 CLI.RetZExt == Args[i].IsZExt)) 10142 Flags.setReturned(); 10143 } 10144 10145 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10146 CLI.CallConv, ExtendKind); 10147 10148 for (unsigned j = 0; j != NumParts; ++j) { 10149 // if it isn't first piece, alignment must be 1 10150 // For scalable vectors the scalable part is currently handled 10151 // by individual targets, so we just use the known minimum size here. 10152 ISD::OutputArg MyFlags( 10153 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10154 i < CLI.NumFixedArgs, i, 10155 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10156 if (NumParts > 1 && j == 0) 10157 MyFlags.Flags.setSplit(); 10158 else if (j != 0) { 10159 MyFlags.Flags.setOrigAlign(Align(1)); 10160 if (j == NumParts - 1) 10161 MyFlags.Flags.setSplitEnd(); 10162 } 10163 10164 CLI.Outs.push_back(MyFlags); 10165 CLI.OutVals.push_back(Parts[j]); 10166 } 10167 10168 if (NeedsRegBlock && Value == NumValues - 1) 10169 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10170 } 10171 } 10172 10173 SmallVector<SDValue, 4> InVals; 10174 CLI.Chain = LowerCall(CLI, InVals); 10175 10176 // Update CLI.InVals to use outside of this function. 10177 CLI.InVals = InVals; 10178 10179 // Verify that the target's LowerCall behaved as expected. 10180 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10181 "LowerCall didn't return a valid chain!"); 10182 assert((!CLI.IsTailCall || InVals.empty()) && 10183 "LowerCall emitted a return value for a tail call!"); 10184 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10185 "LowerCall didn't emit the correct number of values!"); 10186 10187 // For a tail call, the return value is merely live-out and there aren't 10188 // any nodes in the DAG representing it. Return a special value to 10189 // indicate that a tail call has been emitted and no more Instructions 10190 // should be processed in the current block. 10191 if (CLI.IsTailCall) { 10192 CLI.DAG.setRoot(CLI.Chain); 10193 return std::make_pair(SDValue(), SDValue()); 10194 } 10195 10196 #ifndef NDEBUG 10197 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10198 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10199 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10200 "LowerCall emitted a value with the wrong type!"); 10201 } 10202 #endif 10203 10204 SmallVector<SDValue, 4> ReturnValues; 10205 if (!CanLowerReturn) { 10206 // The instruction result is the result of loading from the 10207 // hidden sret parameter. 10208 SmallVector<EVT, 1> PVTs; 10209 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10210 10211 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10212 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10213 EVT PtrVT = PVTs[0]; 10214 10215 unsigned NumValues = RetTys.size(); 10216 ReturnValues.resize(NumValues); 10217 SmallVector<SDValue, 4> Chains(NumValues); 10218 10219 // An aggregate return value cannot wrap around the address space, so 10220 // offsets to its parts don't wrap either. 10221 SDNodeFlags Flags; 10222 Flags.setNoUnsignedWrap(true); 10223 10224 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10225 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10226 for (unsigned i = 0; i < NumValues; ++i) { 10227 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10228 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10229 PtrVT), Flags); 10230 SDValue L = CLI.DAG.getLoad( 10231 RetTys[i], CLI.DL, CLI.Chain, Add, 10232 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10233 DemoteStackIdx, Offsets[i]), 10234 HiddenSRetAlign); 10235 ReturnValues[i] = L; 10236 Chains[i] = L.getValue(1); 10237 } 10238 10239 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10240 } else { 10241 // Collect the legal value parts into potentially illegal values 10242 // that correspond to the original function's return values. 10243 std::optional<ISD::NodeType> AssertOp; 10244 if (CLI.RetSExt) 10245 AssertOp = ISD::AssertSext; 10246 else if (CLI.RetZExt) 10247 AssertOp = ISD::AssertZext; 10248 unsigned CurReg = 0; 10249 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10250 EVT VT = RetTys[I]; 10251 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10252 CLI.CallConv, VT); 10253 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10254 CLI.CallConv, VT); 10255 10256 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10257 NumRegs, RegisterVT, VT, nullptr, 10258 CLI.CallConv, AssertOp)); 10259 CurReg += NumRegs; 10260 } 10261 10262 // For a function returning void, there is no return value. We can't create 10263 // such a node, so we just return a null return value in that case. In 10264 // that case, nothing will actually look at the value. 10265 if (ReturnValues.empty()) 10266 return std::make_pair(SDValue(), CLI.Chain); 10267 } 10268 10269 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10270 CLI.DAG.getVTList(RetTys), ReturnValues); 10271 return std::make_pair(Res, CLI.Chain); 10272 } 10273 10274 /// Places new result values for the node in Results (their number 10275 /// and types must exactly match those of the original return values of 10276 /// the node), or leaves Results empty, which indicates that the node is not 10277 /// to be custom lowered after all. 10278 void TargetLowering::LowerOperationWrapper(SDNode *N, 10279 SmallVectorImpl<SDValue> &Results, 10280 SelectionDAG &DAG) const { 10281 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10282 10283 if (!Res.getNode()) 10284 return; 10285 10286 // If the original node has one result, take the return value from 10287 // LowerOperation as is. It might not be result number 0. 10288 if (N->getNumValues() == 1) { 10289 Results.push_back(Res); 10290 return; 10291 } 10292 10293 // If the original node has multiple results, then the return node should 10294 // have the same number of results. 10295 assert((N->getNumValues() == Res->getNumValues()) && 10296 "Lowering returned the wrong number of results!"); 10297 10298 // Places new result values base on N result number. 10299 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10300 Results.push_back(Res.getValue(I)); 10301 } 10302 10303 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10304 llvm_unreachable("LowerOperation not implemented for this target!"); 10305 } 10306 10307 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10308 unsigned Reg, 10309 ISD::NodeType ExtendType) { 10310 SDValue Op = getNonRegisterValue(V); 10311 assert((Op.getOpcode() != ISD::CopyFromReg || 10312 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10313 "Copy from a reg to the same reg!"); 10314 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10315 10316 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10317 // If this is an InlineAsm we have to match the registers required, not the 10318 // notional registers required by the type. 10319 10320 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10321 std::nullopt); // This is not an ABI copy. 10322 SDValue Chain = DAG.getEntryNode(); 10323 10324 if (ExtendType == ISD::ANY_EXTEND) { 10325 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10326 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10327 ExtendType = PreferredExtendIt->second; 10328 } 10329 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10330 PendingExports.push_back(Chain); 10331 } 10332 10333 #include "llvm/CodeGen/SelectionDAGISel.h" 10334 10335 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10336 /// entry block, return true. This includes arguments used by switches, since 10337 /// the switch may expand into multiple basic blocks. 10338 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10339 // With FastISel active, we may be splitting blocks, so force creation 10340 // of virtual registers for all non-dead arguments. 10341 if (FastISel) 10342 return A->use_empty(); 10343 10344 const BasicBlock &Entry = A->getParent()->front(); 10345 for (const User *U : A->users()) 10346 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10347 return false; // Use not in entry block. 10348 10349 return true; 10350 } 10351 10352 using ArgCopyElisionMapTy = 10353 DenseMap<const Argument *, 10354 std::pair<const AllocaInst *, const StoreInst *>>; 10355 10356 /// Scan the entry block of the function in FuncInfo for arguments that look 10357 /// like copies into a local alloca. Record any copied arguments in 10358 /// ArgCopyElisionCandidates. 10359 static void 10360 findArgumentCopyElisionCandidates(const DataLayout &DL, 10361 FunctionLoweringInfo *FuncInfo, 10362 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10363 // Record the state of every static alloca used in the entry block. Argument 10364 // allocas are all used in the entry block, so we need approximately as many 10365 // entries as we have arguments. 10366 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10367 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10368 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10369 StaticAllocas.reserve(NumArgs * 2); 10370 10371 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10372 if (!V) 10373 return nullptr; 10374 V = V->stripPointerCasts(); 10375 const auto *AI = dyn_cast<AllocaInst>(V); 10376 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10377 return nullptr; 10378 auto Iter = StaticAllocas.insert({AI, Unknown}); 10379 return &Iter.first->second; 10380 }; 10381 10382 // Look for stores of arguments to static allocas. Look through bitcasts and 10383 // GEPs to handle type coercions, as long as the alloca is fully initialized 10384 // by the store. Any non-store use of an alloca escapes it and any subsequent 10385 // unanalyzed store might write it. 10386 // FIXME: Handle structs initialized with multiple stores. 10387 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10388 // Look for stores, and handle non-store uses conservatively. 10389 const auto *SI = dyn_cast<StoreInst>(&I); 10390 if (!SI) { 10391 // We will look through cast uses, so ignore them completely. 10392 if (I.isCast()) 10393 continue; 10394 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10395 // to allocas. 10396 if (I.isDebugOrPseudoInst()) 10397 continue; 10398 // This is an unknown instruction. Assume it escapes or writes to all 10399 // static alloca operands. 10400 for (const Use &U : I.operands()) { 10401 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10402 *Info = StaticAllocaInfo::Clobbered; 10403 } 10404 continue; 10405 } 10406 10407 // If the stored value is a static alloca, mark it as escaped. 10408 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10409 *Info = StaticAllocaInfo::Clobbered; 10410 10411 // Check if the destination is a static alloca. 10412 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10413 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10414 if (!Info) 10415 continue; 10416 const AllocaInst *AI = cast<AllocaInst>(Dst); 10417 10418 // Skip allocas that have been initialized or clobbered. 10419 if (*Info != StaticAllocaInfo::Unknown) 10420 continue; 10421 10422 // Check if the stored value is an argument, and that this store fully 10423 // initializes the alloca. 10424 // If the argument type has padding bits we can't directly forward a pointer 10425 // as the upper bits may contain garbage. 10426 // Don't elide copies from the same argument twice. 10427 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10428 const auto *Arg = dyn_cast<Argument>(Val); 10429 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10430 Arg->getType()->isEmptyTy() || 10431 DL.getTypeStoreSize(Arg->getType()) != 10432 DL.getTypeAllocSize(AI->getAllocatedType()) || 10433 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10434 ArgCopyElisionCandidates.count(Arg)) { 10435 *Info = StaticAllocaInfo::Clobbered; 10436 continue; 10437 } 10438 10439 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10440 << '\n'); 10441 10442 // Mark this alloca and store for argument copy elision. 10443 *Info = StaticAllocaInfo::Elidable; 10444 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10445 10446 // Stop scanning if we've seen all arguments. This will happen early in -O0 10447 // builds, which is useful, because -O0 builds have large entry blocks and 10448 // many allocas. 10449 if (ArgCopyElisionCandidates.size() == NumArgs) 10450 break; 10451 } 10452 } 10453 10454 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10455 /// ArgVal is a load from a suitable fixed stack object. 10456 static void tryToElideArgumentCopy( 10457 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10458 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10459 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10460 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10461 SDValue ArgVal, bool &ArgHasUses) { 10462 // Check if this is a load from a fixed stack object. 10463 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 10464 if (!LNode) 10465 return; 10466 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10467 if (!FINode) 10468 return; 10469 10470 // Check that the fixed stack object is the right size and alignment. 10471 // Look at the alignment that the user wrote on the alloca instead of looking 10472 // at the stack object. 10473 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10474 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10475 const AllocaInst *AI = ArgCopyIter->second.first; 10476 int FixedIndex = FINode->getIndex(); 10477 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10478 int OldIndex = AllocaIndex; 10479 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10480 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10481 LLVM_DEBUG( 10482 dbgs() << " argument copy elision failed due to bad fixed stack " 10483 "object size\n"); 10484 return; 10485 } 10486 Align RequiredAlignment = AI->getAlign(); 10487 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10488 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10489 "greater than stack argument alignment (" 10490 << DebugStr(RequiredAlignment) << " vs " 10491 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10492 return; 10493 } 10494 10495 // Perform the elision. Delete the old stack object and replace its only use 10496 // in the variable info map. Mark the stack object as mutable. 10497 LLVM_DEBUG({ 10498 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10499 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10500 << '\n'; 10501 }); 10502 MFI.RemoveStackObject(OldIndex); 10503 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10504 AllocaIndex = FixedIndex; 10505 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10506 Chains.push_back(ArgVal.getValue(1)); 10507 10508 // Avoid emitting code for the store implementing the copy. 10509 const StoreInst *SI = ArgCopyIter->second.second; 10510 ElidedArgCopyInstrs.insert(SI); 10511 10512 // Check for uses of the argument again so that we can avoid exporting ArgVal 10513 // if it is't used by anything other than the store. 10514 for (const Value *U : Arg.users()) { 10515 if (U != SI) { 10516 ArgHasUses = true; 10517 break; 10518 } 10519 } 10520 } 10521 10522 void SelectionDAGISel::LowerArguments(const Function &F) { 10523 SelectionDAG &DAG = SDB->DAG; 10524 SDLoc dl = SDB->getCurSDLoc(); 10525 const DataLayout &DL = DAG.getDataLayout(); 10526 SmallVector<ISD::InputArg, 16> Ins; 10527 10528 // In Naked functions we aren't going to save any registers. 10529 if (F.hasFnAttribute(Attribute::Naked)) 10530 return; 10531 10532 if (!FuncInfo->CanLowerReturn) { 10533 // Put in an sret pointer parameter before all the other parameters. 10534 SmallVector<EVT, 1> ValueVTs; 10535 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10536 F.getReturnType()->getPointerTo( 10537 DAG.getDataLayout().getAllocaAddrSpace()), 10538 ValueVTs); 10539 10540 // NOTE: Assuming that a pointer will never break down to more than one VT 10541 // or one register. 10542 ISD::ArgFlagsTy Flags; 10543 Flags.setSRet(); 10544 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10545 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10546 ISD::InputArg::NoArgIndex, 0); 10547 Ins.push_back(RetArg); 10548 } 10549 10550 // Look for stores of arguments to static allocas. Mark such arguments with a 10551 // flag to ask the target to give us the memory location of that argument if 10552 // available. 10553 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10554 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10555 ArgCopyElisionCandidates); 10556 10557 // Set up the incoming argument description vector. 10558 for (const Argument &Arg : F.args()) { 10559 unsigned ArgNo = Arg.getArgNo(); 10560 SmallVector<EVT, 4> ValueVTs; 10561 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10562 bool isArgValueUsed = !Arg.use_empty(); 10563 unsigned PartBase = 0; 10564 Type *FinalType = Arg.getType(); 10565 if (Arg.hasAttribute(Attribute::ByVal)) 10566 FinalType = Arg.getParamByValType(); 10567 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10568 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10569 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10570 Value != NumValues; ++Value) { 10571 EVT VT = ValueVTs[Value]; 10572 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10573 ISD::ArgFlagsTy Flags; 10574 10575 10576 if (Arg.getType()->isPointerTy()) { 10577 Flags.setPointer(); 10578 Flags.setPointerAddrSpace( 10579 cast<PointerType>(Arg.getType())->getAddressSpace()); 10580 } 10581 if (Arg.hasAttribute(Attribute::ZExt)) 10582 Flags.setZExt(); 10583 if (Arg.hasAttribute(Attribute::SExt)) 10584 Flags.setSExt(); 10585 if (Arg.hasAttribute(Attribute::InReg)) { 10586 // If we are using vectorcall calling convention, a structure that is 10587 // passed InReg - is surely an HVA 10588 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10589 isa<StructType>(Arg.getType())) { 10590 // The first value of a structure is marked 10591 if (0 == Value) 10592 Flags.setHvaStart(); 10593 Flags.setHva(); 10594 } 10595 // Set InReg Flag 10596 Flags.setInReg(); 10597 } 10598 if (Arg.hasAttribute(Attribute::StructRet)) 10599 Flags.setSRet(); 10600 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10601 Flags.setSwiftSelf(); 10602 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10603 Flags.setSwiftAsync(); 10604 if (Arg.hasAttribute(Attribute::SwiftError)) 10605 Flags.setSwiftError(); 10606 if (Arg.hasAttribute(Attribute::ByVal)) 10607 Flags.setByVal(); 10608 if (Arg.hasAttribute(Attribute::ByRef)) 10609 Flags.setByRef(); 10610 if (Arg.hasAttribute(Attribute::InAlloca)) { 10611 Flags.setInAlloca(); 10612 // Set the byval flag for CCAssignFn callbacks that don't know about 10613 // inalloca. This way we can know how many bytes we should've allocated 10614 // and how many bytes a callee cleanup function will pop. If we port 10615 // inalloca to more targets, we'll have to add custom inalloca handling 10616 // in the various CC lowering callbacks. 10617 Flags.setByVal(); 10618 } 10619 if (Arg.hasAttribute(Attribute::Preallocated)) { 10620 Flags.setPreallocated(); 10621 // Set the byval flag for CCAssignFn callbacks that don't know about 10622 // preallocated. This way we can know how many bytes we should've 10623 // allocated and how many bytes a callee cleanup function will pop. If 10624 // we port preallocated to more targets, we'll have to add custom 10625 // preallocated handling in the various CC lowering callbacks. 10626 Flags.setByVal(); 10627 } 10628 10629 // Certain targets (such as MIPS), may have a different ABI alignment 10630 // for a type depending on the context. Give the target a chance to 10631 // specify the alignment it wants. 10632 const Align OriginalAlignment( 10633 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10634 Flags.setOrigAlign(OriginalAlignment); 10635 10636 Align MemAlign; 10637 Type *ArgMemTy = nullptr; 10638 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10639 Flags.isByRef()) { 10640 if (!ArgMemTy) 10641 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10642 10643 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10644 10645 // For in-memory arguments, size and alignment should be passed from FE. 10646 // BE will guess if this info is not there but there are cases it cannot 10647 // get right. 10648 if (auto ParamAlign = Arg.getParamStackAlign()) 10649 MemAlign = *ParamAlign; 10650 else if ((ParamAlign = Arg.getParamAlign())) 10651 MemAlign = *ParamAlign; 10652 else 10653 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10654 if (Flags.isByRef()) 10655 Flags.setByRefSize(MemSize); 10656 else 10657 Flags.setByValSize(MemSize); 10658 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10659 MemAlign = *ParamAlign; 10660 } else { 10661 MemAlign = OriginalAlignment; 10662 } 10663 Flags.setMemAlign(MemAlign); 10664 10665 if (Arg.hasAttribute(Attribute::Nest)) 10666 Flags.setNest(); 10667 if (NeedsRegBlock) 10668 Flags.setInConsecutiveRegs(); 10669 if (ArgCopyElisionCandidates.count(&Arg)) 10670 Flags.setCopyElisionCandidate(); 10671 if (Arg.hasAttribute(Attribute::Returned)) 10672 Flags.setReturned(); 10673 10674 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10675 *CurDAG->getContext(), F.getCallingConv(), VT); 10676 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10677 *CurDAG->getContext(), F.getCallingConv(), VT); 10678 for (unsigned i = 0; i != NumRegs; ++i) { 10679 // For scalable vectors, use the minimum size; individual targets 10680 // are responsible for handling scalable vector arguments and 10681 // return values. 10682 ISD::InputArg MyFlags( 10683 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10684 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10685 if (NumRegs > 1 && i == 0) 10686 MyFlags.Flags.setSplit(); 10687 // if it isn't first piece, alignment must be 1 10688 else if (i > 0) { 10689 MyFlags.Flags.setOrigAlign(Align(1)); 10690 if (i == NumRegs - 1) 10691 MyFlags.Flags.setSplitEnd(); 10692 } 10693 Ins.push_back(MyFlags); 10694 } 10695 if (NeedsRegBlock && Value == NumValues - 1) 10696 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10697 PartBase += VT.getStoreSize().getKnownMinValue(); 10698 } 10699 } 10700 10701 // Call the target to set up the argument values. 10702 SmallVector<SDValue, 8> InVals; 10703 SDValue NewRoot = TLI->LowerFormalArguments( 10704 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10705 10706 // Verify that the target's LowerFormalArguments behaved as expected. 10707 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10708 "LowerFormalArguments didn't return a valid chain!"); 10709 assert(InVals.size() == Ins.size() && 10710 "LowerFormalArguments didn't emit the correct number of values!"); 10711 LLVM_DEBUG({ 10712 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10713 assert(InVals[i].getNode() && 10714 "LowerFormalArguments emitted a null value!"); 10715 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10716 "LowerFormalArguments emitted a value with the wrong type!"); 10717 } 10718 }); 10719 10720 // Update the DAG with the new chain value resulting from argument lowering. 10721 DAG.setRoot(NewRoot); 10722 10723 // Set up the argument values. 10724 unsigned i = 0; 10725 if (!FuncInfo->CanLowerReturn) { 10726 // Create a virtual register for the sret pointer, and put in a copy 10727 // from the sret argument into it. 10728 SmallVector<EVT, 1> ValueVTs; 10729 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10730 F.getReturnType()->getPointerTo( 10731 DAG.getDataLayout().getAllocaAddrSpace()), 10732 ValueVTs); 10733 MVT VT = ValueVTs[0].getSimpleVT(); 10734 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10735 std::optional<ISD::NodeType> AssertOp; 10736 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10737 nullptr, F.getCallingConv(), AssertOp); 10738 10739 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10740 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10741 Register SRetReg = 10742 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10743 FuncInfo->DemoteRegister = SRetReg; 10744 NewRoot = 10745 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10746 DAG.setRoot(NewRoot); 10747 10748 // i indexes lowered arguments. Bump it past the hidden sret argument. 10749 ++i; 10750 } 10751 10752 SmallVector<SDValue, 4> Chains; 10753 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10754 for (const Argument &Arg : F.args()) { 10755 SmallVector<SDValue, 4> ArgValues; 10756 SmallVector<EVT, 4> ValueVTs; 10757 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10758 unsigned NumValues = ValueVTs.size(); 10759 if (NumValues == 0) 10760 continue; 10761 10762 bool ArgHasUses = !Arg.use_empty(); 10763 10764 // Elide the copying store if the target loaded this argument from a 10765 // suitable fixed stack object. 10766 if (Ins[i].Flags.isCopyElisionCandidate()) { 10767 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10768 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10769 InVals[i], ArgHasUses); 10770 } 10771 10772 // If this argument is unused then remember its value. It is used to generate 10773 // debugging information. 10774 bool isSwiftErrorArg = 10775 TLI->supportSwiftError() && 10776 Arg.hasAttribute(Attribute::SwiftError); 10777 if (!ArgHasUses && !isSwiftErrorArg) { 10778 SDB->setUnusedArgValue(&Arg, InVals[i]); 10779 10780 // Also remember any frame index for use in FastISel. 10781 if (FrameIndexSDNode *FI = 10782 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10783 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10784 } 10785 10786 for (unsigned Val = 0; Val != NumValues; ++Val) { 10787 EVT VT = ValueVTs[Val]; 10788 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10789 F.getCallingConv(), VT); 10790 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10791 *CurDAG->getContext(), F.getCallingConv(), VT); 10792 10793 // Even an apparent 'unused' swifterror argument needs to be returned. So 10794 // we do generate a copy for it that can be used on return from the 10795 // function. 10796 if (ArgHasUses || isSwiftErrorArg) { 10797 std::optional<ISD::NodeType> AssertOp; 10798 if (Arg.hasAttribute(Attribute::SExt)) 10799 AssertOp = ISD::AssertSext; 10800 else if (Arg.hasAttribute(Attribute::ZExt)) 10801 AssertOp = ISD::AssertZext; 10802 10803 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10804 PartVT, VT, nullptr, 10805 F.getCallingConv(), AssertOp)); 10806 } 10807 10808 i += NumParts; 10809 } 10810 10811 // We don't need to do anything else for unused arguments. 10812 if (ArgValues.empty()) 10813 continue; 10814 10815 // Note down frame index. 10816 if (FrameIndexSDNode *FI = 10817 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10818 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10819 10820 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10821 SDB->getCurSDLoc()); 10822 10823 SDB->setValue(&Arg, Res); 10824 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10825 // We want to associate the argument with the frame index, among 10826 // involved operands, that correspond to the lowest address. The 10827 // getCopyFromParts function, called earlier, is swapping the order of 10828 // the operands to BUILD_PAIR depending on endianness. The result of 10829 // that swapping is that the least significant bits of the argument will 10830 // be in the first operand of the BUILD_PAIR node, and the most 10831 // significant bits will be in the second operand. 10832 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10833 if (LoadSDNode *LNode = 10834 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10835 if (FrameIndexSDNode *FI = 10836 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10837 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10838 } 10839 10840 // Analyses past this point are naive and don't expect an assertion. 10841 if (Res.getOpcode() == ISD::AssertZext) 10842 Res = Res.getOperand(0); 10843 10844 // Update the SwiftErrorVRegDefMap. 10845 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10846 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10847 if (Register::isVirtualRegister(Reg)) 10848 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10849 Reg); 10850 } 10851 10852 // If this argument is live outside of the entry block, insert a copy from 10853 // wherever we got it to the vreg that other BB's will reference it as. 10854 if (Res.getOpcode() == ISD::CopyFromReg) { 10855 // If we can, though, try to skip creating an unnecessary vreg. 10856 // FIXME: This isn't very clean... it would be nice to make this more 10857 // general. 10858 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10859 if (Register::isVirtualRegister(Reg)) { 10860 FuncInfo->ValueMap[&Arg] = Reg; 10861 continue; 10862 } 10863 } 10864 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10865 FuncInfo->InitializeRegForValue(&Arg); 10866 SDB->CopyToExportRegsIfNeeded(&Arg); 10867 } 10868 } 10869 10870 if (!Chains.empty()) { 10871 Chains.push_back(NewRoot); 10872 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10873 } 10874 10875 DAG.setRoot(NewRoot); 10876 10877 assert(i == InVals.size() && "Argument register count mismatch!"); 10878 10879 // If any argument copy elisions occurred and we have debug info, update the 10880 // stale frame indices used in the dbg.declare variable info table. 10881 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10882 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10883 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10884 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10885 if (I != ArgCopyElisionFrameIndexMap.end()) 10886 VI.Slot = I->second; 10887 } 10888 } 10889 10890 // Finally, if the target has anything special to do, allow it to do so. 10891 emitFunctionEntryCode(); 10892 } 10893 10894 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10895 /// ensure constants are generated when needed. Remember the virtual registers 10896 /// that need to be added to the Machine PHI nodes as input. We cannot just 10897 /// directly add them, because expansion might result in multiple MBB's for one 10898 /// BB. As such, the start of the BB might correspond to a different MBB than 10899 /// the end. 10900 void 10901 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10902 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10903 10904 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10905 10906 // Check PHI nodes in successors that expect a value to be available from this 10907 // block. 10908 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 10909 if (!isa<PHINode>(SuccBB->begin())) continue; 10910 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10911 10912 // If this terminator has multiple identical successors (common for 10913 // switches), only handle each succ once. 10914 if (!SuccsHandled.insert(SuccMBB).second) 10915 continue; 10916 10917 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10918 10919 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10920 // nodes and Machine PHI nodes, but the incoming operands have not been 10921 // emitted yet. 10922 for (const PHINode &PN : SuccBB->phis()) { 10923 // Ignore dead phi's. 10924 if (PN.use_empty()) 10925 continue; 10926 10927 // Skip empty types 10928 if (PN.getType()->isEmptyTy()) 10929 continue; 10930 10931 unsigned Reg; 10932 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10933 10934 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 10935 unsigned &RegOut = ConstantsOut[C]; 10936 if (RegOut == 0) { 10937 RegOut = FuncInfo.CreateRegs(C); 10938 // We need to zero/sign extend ConstantInt phi operands to match 10939 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 10940 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 10941 if (auto *CI = dyn_cast<ConstantInt>(C)) 10942 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 10943 : ISD::ZERO_EXTEND; 10944 CopyValueToVirtualRegister(C, RegOut, ExtendType); 10945 } 10946 Reg = RegOut; 10947 } else { 10948 DenseMap<const Value *, Register>::iterator I = 10949 FuncInfo.ValueMap.find(PHIOp); 10950 if (I != FuncInfo.ValueMap.end()) 10951 Reg = I->second; 10952 else { 10953 assert(isa<AllocaInst>(PHIOp) && 10954 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10955 "Didn't codegen value into a register!??"); 10956 Reg = FuncInfo.CreateRegs(PHIOp); 10957 CopyValueToVirtualRegister(PHIOp, Reg); 10958 } 10959 } 10960 10961 // Remember that this register needs to added to the machine PHI node as 10962 // the input for this MBB. 10963 SmallVector<EVT, 4> ValueVTs; 10964 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10965 for (EVT VT : ValueVTs) { 10966 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10967 for (unsigned i = 0; i != NumRegisters; ++i) 10968 FuncInfo.PHINodesToUpdate.push_back( 10969 std::make_pair(&*MBBI++, Reg + i)); 10970 Reg += NumRegisters; 10971 } 10972 } 10973 } 10974 10975 ConstantsOut.clear(); 10976 } 10977 10978 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10979 MachineFunction::iterator I(MBB); 10980 if (++I == FuncInfo.MF->end()) 10981 return nullptr; 10982 return &*I; 10983 } 10984 10985 /// During lowering new call nodes can be created (such as memset, etc.). 10986 /// Those will become new roots of the current DAG, but complications arise 10987 /// when they are tail calls. In such cases, the call lowering will update 10988 /// the root, but the builder still needs to know that a tail call has been 10989 /// lowered in order to avoid generating an additional return. 10990 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10991 // If the node is null, we do have a tail call. 10992 if (MaybeTC.getNode() != nullptr) 10993 DAG.setRoot(MaybeTC); 10994 else 10995 HasTailCall = true; 10996 } 10997 10998 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10999 MachineBasicBlock *SwitchMBB, 11000 MachineBasicBlock *DefaultMBB) { 11001 MachineFunction *CurMF = FuncInfo.MF; 11002 MachineBasicBlock *NextMBB = nullptr; 11003 MachineFunction::iterator BBI(W.MBB); 11004 if (++BBI != FuncInfo.MF->end()) 11005 NextMBB = &*BBI; 11006 11007 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11008 11009 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11010 11011 if (Size == 2 && W.MBB == SwitchMBB) { 11012 // If any two of the cases has the same destination, and if one value 11013 // is the same as the other, but has one bit unset that the other has set, 11014 // use bit manipulation to do two compares at once. For example: 11015 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11016 // TODO: This could be extended to merge any 2 cases in switches with 3 11017 // cases. 11018 // TODO: Handle cases where W.CaseBB != SwitchBB. 11019 CaseCluster &Small = *W.FirstCluster; 11020 CaseCluster &Big = *W.LastCluster; 11021 11022 if (Small.Low == Small.High && Big.Low == Big.High && 11023 Small.MBB == Big.MBB) { 11024 const APInt &SmallValue = Small.Low->getValue(); 11025 const APInt &BigValue = Big.Low->getValue(); 11026 11027 // Check that there is only one bit different. 11028 APInt CommonBit = BigValue ^ SmallValue; 11029 if (CommonBit.isPowerOf2()) { 11030 SDValue CondLHS = getValue(Cond); 11031 EVT VT = CondLHS.getValueType(); 11032 SDLoc DL = getCurSDLoc(); 11033 11034 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11035 DAG.getConstant(CommonBit, DL, VT)); 11036 SDValue Cond = DAG.getSetCC( 11037 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11038 ISD::SETEQ); 11039 11040 // Update successor info. 11041 // Both Small and Big will jump to Small.BB, so we sum up the 11042 // probabilities. 11043 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11044 if (BPI) 11045 addSuccessorWithProb( 11046 SwitchMBB, DefaultMBB, 11047 // The default destination is the first successor in IR. 11048 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11049 else 11050 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11051 11052 // Insert the true branch. 11053 SDValue BrCond = 11054 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11055 DAG.getBasicBlock(Small.MBB)); 11056 // Insert the false branch. 11057 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11058 DAG.getBasicBlock(DefaultMBB)); 11059 11060 DAG.setRoot(BrCond); 11061 return; 11062 } 11063 } 11064 } 11065 11066 if (TM.getOptLevel() != CodeGenOpt::None) { 11067 // Here, we order cases by probability so the most likely case will be 11068 // checked first. However, two clusters can have the same probability in 11069 // which case their relative ordering is non-deterministic. So we use Low 11070 // as a tie-breaker as clusters are guaranteed to never overlap. 11071 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11072 [](const CaseCluster &a, const CaseCluster &b) { 11073 return a.Prob != b.Prob ? 11074 a.Prob > b.Prob : 11075 a.Low->getValue().slt(b.Low->getValue()); 11076 }); 11077 11078 // Rearrange the case blocks so that the last one falls through if possible 11079 // without changing the order of probabilities. 11080 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11081 --I; 11082 if (I->Prob > W.LastCluster->Prob) 11083 break; 11084 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11085 std::swap(*I, *W.LastCluster); 11086 break; 11087 } 11088 } 11089 } 11090 11091 // Compute total probability. 11092 BranchProbability DefaultProb = W.DefaultProb; 11093 BranchProbability UnhandledProbs = DefaultProb; 11094 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11095 UnhandledProbs += I->Prob; 11096 11097 MachineBasicBlock *CurMBB = W.MBB; 11098 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11099 bool FallthroughUnreachable = false; 11100 MachineBasicBlock *Fallthrough; 11101 if (I == W.LastCluster) { 11102 // For the last cluster, fall through to the default destination. 11103 Fallthrough = DefaultMBB; 11104 FallthroughUnreachable = isa<UnreachableInst>( 11105 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11106 } else { 11107 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11108 CurMF->insert(BBI, Fallthrough); 11109 // Put Cond in a virtual register to make it available from the new blocks. 11110 ExportFromCurrentBlock(Cond); 11111 } 11112 UnhandledProbs -= I->Prob; 11113 11114 switch (I->Kind) { 11115 case CC_JumpTable: { 11116 // FIXME: Optimize away range check based on pivot comparisons. 11117 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11118 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11119 11120 // The jump block hasn't been inserted yet; insert it here. 11121 MachineBasicBlock *JumpMBB = JT->MBB; 11122 CurMF->insert(BBI, JumpMBB); 11123 11124 auto JumpProb = I->Prob; 11125 auto FallthroughProb = UnhandledProbs; 11126 11127 // If the default statement is a target of the jump table, we evenly 11128 // distribute the default probability to successors of CurMBB. Also 11129 // update the probability on the edge from JumpMBB to Fallthrough. 11130 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11131 SE = JumpMBB->succ_end(); 11132 SI != SE; ++SI) { 11133 if (*SI == DefaultMBB) { 11134 JumpProb += DefaultProb / 2; 11135 FallthroughProb -= DefaultProb / 2; 11136 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11137 JumpMBB->normalizeSuccProbs(); 11138 break; 11139 } 11140 } 11141 11142 if (FallthroughUnreachable) 11143 JTH->FallthroughUnreachable = true; 11144 11145 if (!JTH->FallthroughUnreachable) 11146 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11147 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11148 CurMBB->normalizeSuccProbs(); 11149 11150 // The jump table header will be inserted in our current block, do the 11151 // range check, and fall through to our fallthrough block. 11152 JTH->HeaderBB = CurMBB; 11153 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11154 11155 // If we're in the right place, emit the jump table header right now. 11156 if (CurMBB == SwitchMBB) { 11157 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11158 JTH->Emitted = true; 11159 } 11160 break; 11161 } 11162 case CC_BitTests: { 11163 // FIXME: Optimize away range check based on pivot comparisons. 11164 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11165 11166 // The bit test blocks haven't been inserted yet; insert them here. 11167 for (BitTestCase &BTC : BTB->Cases) 11168 CurMF->insert(BBI, BTC.ThisBB); 11169 11170 // Fill in fields of the BitTestBlock. 11171 BTB->Parent = CurMBB; 11172 BTB->Default = Fallthrough; 11173 11174 BTB->DefaultProb = UnhandledProbs; 11175 // If the cases in bit test don't form a contiguous range, we evenly 11176 // distribute the probability on the edge to Fallthrough to two 11177 // successors of CurMBB. 11178 if (!BTB->ContiguousRange) { 11179 BTB->Prob += DefaultProb / 2; 11180 BTB->DefaultProb -= DefaultProb / 2; 11181 } 11182 11183 if (FallthroughUnreachable) 11184 BTB->FallthroughUnreachable = true; 11185 11186 // If we're in the right place, emit the bit test header right now. 11187 if (CurMBB == SwitchMBB) { 11188 visitBitTestHeader(*BTB, SwitchMBB); 11189 BTB->Emitted = true; 11190 } 11191 break; 11192 } 11193 case CC_Range: { 11194 const Value *RHS, *LHS, *MHS; 11195 ISD::CondCode CC; 11196 if (I->Low == I->High) { 11197 // Check Cond == I->Low. 11198 CC = ISD::SETEQ; 11199 LHS = Cond; 11200 RHS=I->Low; 11201 MHS = nullptr; 11202 } else { 11203 // Check I->Low <= Cond <= I->High. 11204 CC = ISD::SETLE; 11205 LHS = I->Low; 11206 MHS = Cond; 11207 RHS = I->High; 11208 } 11209 11210 // If Fallthrough is unreachable, fold away the comparison. 11211 if (FallthroughUnreachable) 11212 CC = ISD::SETTRUE; 11213 11214 // The false probability is the sum of all unhandled cases. 11215 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11216 getCurSDLoc(), I->Prob, UnhandledProbs); 11217 11218 if (CurMBB == SwitchMBB) 11219 visitSwitchCase(CB, SwitchMBB); 11220 else 11221 SL->SwitchCases.push_back(CB); 11222 11223 break; 11224 } 11225 } 11226 CurMBB = Fallthrough; 11227 } 11228 } 11229 11230 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11231 CaseClusterIt First, 11232 CaseClusterIt Last) { 11233 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11234 if (X.Prob != CC.Prob) 11235 return X.Prob > CC.Prob; 11236 11237 // Ties are broken by comparing the case value. 11238 return X.Low->getValue().slt(CC.Low->getValue()); 11239 }); 11240 } 11241 11242 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11243 const SwitchWorkListItem &W, 11244 Value *Cond, 11245 MachineBasicBlock *SwitchMBB) { 11246 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11247 "Clusters not sorted?"); 11248 11249 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11250 11251 // Balance the tree based on branch probabilities to create a near-optimal (in 11252 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11253 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11254 CaseClusterIt LastLeft = W.FirstCluster; 11255 CaseClusterIt FirstRight = W.LastCluster; 11256 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11257 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11258 11259 // Move LastLeft and FirstRight towards each other from opposite directions to 11260 // find a partitioning of the clusters which balances the probability on both 11261 // sides. If LeftProb and RightProb are equal, alternate which side is 11262 // taken to ensure 0-probability nodes are distributed evenly. 11263 unsigned I = 0; 11264 while (LastLeft + 1 < FirstRight) { 11265 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11266 LeftProb += (++LastLeft)->Prob; 11267 else 11268 RightProb += (--FirstRight)->Prob; 11269 I++; 11270 } 11271 11272 while (true) { 11273 // Our binary search tree differs from a typical BST in that ours can have up 11274 // to three values in each leaf. The pivot selection above doesn't take that 11275 // into account, which means the tree might require more nodes and be less 11276 // efficient. We compensate for this here. 11277 11278 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11279 unsigned NumRight = W.LastCluster - FirstRight + 1; 11280 11281 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11282 // If one side has less than 3 clusters, and the other has more than 3, 11283 // consider taking a cluster from the other side. 11284 11285 if (NumLeft < NumRight) { 11286 // Consider moving the first cluster on the right to the left side. 11287 CaseCluster &CC = *FirstRight; 11288 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11289 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11290 if (LeftSideRank <= RightSideRank) { 11291 // Moving the cluster to the left does not demote it. 11292 ++LastLeft; 11293 ++FirstRight; 11294 continue; 11295 } 11296 } else { 11297 assert(NumRight < NumLeft); 11298 // Consider moving the last element on the left to the right side. 11299 CaseCluster &CC = *LastLeft; 11300 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11301 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11302 if (RightSideRank <= LeftSideRank) { 11303 // Moving the cluster to the right does not demot it. 11304 --LastLeft; 11305 --FirstRight; 11306 continue; 11307 } 11308 } 11309 } 11310 break; 11311 } 11312 11313 assert(LastLeft + 1 == FirstRight); 11314 assert(LastLeft >= W.FirstCluster); 11315 assert(FirstRight <= W.LastCluster); 11316 11317 // Use the first element on the right as pivot since we will make less-than 11318 // comparisons against it. 11319 CaseClusterIt PivotCluster = FirstRight; 11320 assert(PivotCluster > W.FirstCluster); 11321 assert(PivotCluster <= W.LastCluster); 11322 11323 CaseClusterIt FirstLeft = W.FirstCluster; 11324 CaseClusterIt LastRight = W.LastCluster; 11325 11326 const ConstantInt *Pivot = PivotCluster->Low; 11327 11328 // New blocks will be inserted immediately after the current one. 11329 MachineFunction::iterator BBI(W.MBB); 11330 ++BBI; 11331 11332 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11333 // we can branch to its destination directly if it's squeezed exactly in 11334 // between the known lower bound and Pivot - 1. 11335 MachineBasicBlock *LeftMBB; 11336 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11337 FirstLeft->Low == W.GE && 11338 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11339 LeftMBB = FirstLeft->MBB; 11340 } else { 11341 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11342 FuncInfo.MF->insert(BBI, LeftMBB); 11343 WorkList.push_back( 11344 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11345 // Put Cond in a virtual register to make it available from the new blocks. 11346 ExportFromCurrentBlock(Cond); 11347 } 11348 11349 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11350 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11351 // directly if RHS.High equals the current upper bound. 11352 MachineBasicBlock *RightMBB; 11353 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11354 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11355 RightMBB = FirstRight->MBB; 11356 } else { 11357 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11358 FuncInfo.MF->insert(BBI, RightMBB); 11359 WorkList.push_back( 11360 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11361 // Put Cond in a virtual register to make it available from the new blocks. 11362 ExportFromCurrentBlock(Cond); 11363 } 11364 11365 // Create the CaseBlock record that will be used to lower the branch. 11366 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11367 getCurSDLoc(), LeftProb, RightProb); 11368 11369 if (W.MBB == SwitchMBB) 11370 visitSwitchCase(CB, SwitchMBB); 11371 else 11372 SL->SwitchCases.push_back(CB); 11373 } 11374 11375 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11376 // from the swith statement. 11377 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11378 BranchProbability PeeledCaseProb) { 11379 if (PeeledCaseProb == BranchProbability::getOne()) 11380 return BranchProbability::getZero(); 11381 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11382 11383 uint32_t Numerator = CaseProb.getNumerator(); 11384 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11385 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11386 } 11387 11388 // Try to peel the top probability case if it exceeds the threshold. 11389 // Return current MachineBasicBlock for the switch statement if the peeling 11390 // does not occur. 11391 // If the peeling is performed, return the newly created MachineBasicBlock 11392 // for the peeled switch statement. Also update Clusters to remove the peeled 11393 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11394 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11395 const SwitchInst &SI, CaseClusterVector &Clusters, 11396 BranchProbability &PeeledCaseProb) { 11397 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11398 // Don't perform if there is only one cluster or optimizing for size. 11399 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11400 TM.getOptLevel() == CodeGenOpt::None || 11401 SwitchMBB->getParent()->getFunction().hasMinSize()) 11402 return SwitchMBB; 11403 11404 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11405 unsigned PeeledCaseIndex = 0; 11406 bool SwitchPeeled = false; 11407 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11408 CaseCluster &CC = Clusters[Index]; 11409 if (CC.Prob < TopCaseProb) 11410 continue; 11411 TopCaseProb = CC.Prob; 11412 PeeledCaseIndex = Index; 11413 SwitchPeeled = true; 11414 } 11415 if (!SwitchPeeled) 11416 return SwitchMBB; 11417 11418 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11419 << TopCaseProb << "\n"); 11420 11421 // Record the MBB for the peeled switch statement. 11422 MachineFunction::iterator BBI(SwitchMBB); 11423 ++BBI; 11424 MachineBasicBlock *PeeledSwitchMBB = 11425 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11426 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11427 11428 ExportFromCurrentBlock(SI.getCondition()); 11429 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11430 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11431 nullptr, nullptr, TopCaseProb.getCompl()}; 11432 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11433 11434 Clusters.erase(PeeledCaseIt); 11435 for (CaseCluster &CC : Clusters) { 11436 LLVM_DEBUG( 11437 dbgs() << "Scale the probablity for one cluster, before scaling: " 11438 << CC.Prob << "\n"); 11439 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11440 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11441 } 11442 PeeledCaseProb = TopCaseProb; 11443 return PeeledSwitchMBB; 11444 } 11445 11446 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11447 // Extract cases from the switch. 11448 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11449 CaseClusterVector Clusters; 11450 Clusters.reserve(SI.getNumCases()); 11451 for (auto I : SI.cases()) { 11452 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11453 const ConstantInt *CaseVal = I.getCaseValue(); 11454 BranchProbability Prob = 11455 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11456 : BranchProbability(1, SI.getNumCases() + 1); 11457 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11458 } 11459 11460 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11461 11462 // Cluster adjacent cases with the same destination. We do this at all 11463 // optimization levels because it's cheap to do and will make codegen faster 11464 // if there are many clusters. 11465 sortAndRangeify(Clusters); 11466 11467 // The branch probablity of the peeled case. 11468 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11469 MachineBasicBlock *PeeledSwitchMBB = 11470 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11471 11472 // If there is only the default destination, jump there directly. 11473 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11474 if (Clusters.empty()) { 11475 assert(PeeledSwitchMBB == SwitchMBB); 11476 SwitchMBB->addSuccessor(DefaultMBB); 11477 if (DefaultMBB != NextBlock(SwitchMBB)) { 11478 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11479 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11480 } 11481 return; 11482 } 11483 11484 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11485 SL->findBitTestClusters(Clusters, &SI); 11486 11487 LLVM_DEBUG({ 11488 dbgs() << "Case clusters: "; 11489 for (const CaseCluster &C : Clusters) { 11490 if (C.Kind == CC_JumpTable) 11491 dbgs() << "JT:"; 11492 if (C.Kind == CC_BitTests) 11493 dbgs() << "BT:"; 11494 11495 C.Low->getValue().print(dbgs(), true); 11496 if (C.Low != C.High) { 11497 dbgs() << '-'; 11498 C.High->getValue().print(dbgs(), true); 11499 } 11500 dbgs() << ' '; 11501 } 11502 dbgs() << '\n'; 11503 }); 11504 11505 assert(!Clusters.empty()); 11506 SwitchWorkList WorkList; 11507 CaseClusterIt First = Clusters.begin(); 11508 CaseClusterIt Last = Clusters.end() - 1; 11509 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11510 // Scale the branchprobability for DefaultMBB if the peel occurs and 11511 // DefaultMBB is not replaced. 11512 if (PeeledCaseProb != BranchProbability::getZero() && 11513 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11514 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11515 WorkList.push_back( 11516 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11517 11518 while (!WorkList.empty()) { 11519 SwitchWorkListItem W = WorkList.pop_back_val(); 11520 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11521 11522 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11523 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11524 // For optimized builds, lower large range as a balanced binary tree. 11525 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11526 continue; 11527 } 11528 11529 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11530 } 11531 } 11532 11533 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11535 auto DL = getCurSDLoc(); 11536 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11537 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11538 } 11539 11540 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11542 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11543 11544 SDLoc DL = getCurSDLoc(); 11545 SDValue V = getValue(I.getOperand(0)); 11546 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11547 11548 if (VT.isScalableVector()) { 11549 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11550 return; 11551 } 11552 11553 // Use VECTOR_SHUFFLE for the fixed-length vector 11554 // to maintain existing behavior. 11555 SmallVector<int, 8> Mask; 11556 unsigned NumElts = VT.getVectorMinNumElements(); 11557 for (unsigned i = 0; i != NumElts; ++i) 11558 Mask.push_back(NumElts - 1 - i); 11559 11560 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11561 } 11562 11563 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11564 SmallVector<EVT, 4> ValueVTs; 11565 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11566 ValueVTs); 11567 unsigned NumValues = ValueVTs.size(); 11568 if (NumValues == 0) return; 11569 11570 SmallVector<SDValue, 4> Values(NumValues); 11571 SDValue Op = getValue(I.getOperand(0)); 11572 11573 for (unsigned i = 0; i != NumValues; ++i) 11574 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11575 SDValue(Op.getNode(), Op.getResNo() + i)); 11576 11577 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11578 DAG.getVTList(ValueVTs), Values)); 11579 } 11580 11581 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11583 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11584 11585 SDLoc DL = getCurSDLoc(); 11586 SDValue V1 = getValue(I.getOperand(0)); 11587 SDValue V2 = getValue(I.getOperand(1)); 11588 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11589 11590 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11591 if (VT.isScalableVector()) { 11592 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11593 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11594 DAG.getConstant(Imm, DL, IdxVT))); 11595 return; 11596 } 11597 11598 unsigned NumElts = VT.getVectorNumElements(); 11599 11600 uint64_t Idx = (NumElts + Imm) % NumElts; 11601 11602 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11603 SmallVector<int, 8> Mask; 11604 for (unsigned i = 0; i < NumElts; ++i) 11605 Mask.push_back(Idx + i); 11606 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11607 } 11608