1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/Loads.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/Analysis/VectorUtils.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 33 #include "llvm/CodeGen/CodeGenCommonISel.h" 34 #include "llvm/CodeGen/FunctionLoweringInfo.h" 35 #include "llvm/CodeGen/GCMetadata.h" 36 #include "llvm/CodeGen/ISDOpcodes.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineInstrBundleIterator.h" 42 #include "llvm/CodeGen/MachineMemOperand.h" 43 #include "llvm/CodeGen/MachineModuleInfo.h" 44 #include "llvm/CodeGen/MachineOperand.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/CodeGen/RuntimeLibcalls.h" 47 #include "llvm/CodeGen/SelectionDAG.h" 48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 49 #include "llvm/CodeGen/StackMaps.h" 50 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 51 #include "llvm/CodeGen/TargetFrameLowering.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetOpcodes.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/WinEHFuncInfo.h" 57 #include "llvm/IR/Argument.h" 58 #include "llvm/IR/Attributes.h" 59 #include "llvm/IR/BasicBlock.h" 60 #include "llvm/IR/CFG.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/ConstantRange.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfo.h" 67 #include "llvm/IR/DebugInfoMetadata.h" 68 #include "llvm/IR/DerivedTypes.h" 69 #include "llvm/IR/DiagnosticInfo.h" 70 #include "llvm/IR/EHPersonalities.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsWebAssembly.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Metadata.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/PatternMatch.h" 85 #include "llvm/IR/Statepoint.h" 86 #include "llvm/IR/Type.h" 87 #include "llvm/IR/User.h" 88 #include "llvm/IR/Value.h" 89 #include "llvm/MC/MCContext.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/Casting.h" 92 #include "llvm/Support/CommandLine.h" 93 #include "llvm/Support/Compiler.h" 94 #include "llvm/Support/Debug.h" 95 #include "llvm/Support/MathExtras.h" 96 #include "llvm/Support/raw_ostream.h" 97 #include "llvm/Target/TargetIntrinsicInfo.h" 98 #include "llvm/Target/TargetMachine.h" 99 #include "llvm/Target/TargetOptions.h" 100 #include "llvm/TargetParser/Triple.h" 101 #include "llvm/Transforms/Utils/Local.h" 102 #include <cstddef> 103 #include <iterator> 104 #include <limits> 105 #include <optional> 106 #include <tuple> 107 108 using namespace llvm; 109 using namespace PatternMatch; 110 using namespace SwitchCG; 111 112 #define DEBUG_TYPE "isel" 113 114 /// LimitFloatPrecision - Generate low-precision inline sequences for 115 /// some float libcalls (6, 8 or 12 bits). 116 static unsigned LimitFloatPrecision; 117 118 static cl::opt<bool> 119 InsertAssertAlign("insert-assert-align", cl::init(true), 120 cl::desc("Insert the experimental `assertalign` node."), 121 cl::ReallyHidden); 122 123 static cl::opt<unsigned, true> 124 LimitFPPrecision("limit-float-precision", 125 cl::desc("Generate low-precision inline sequences " 126 "for some float libcalls"), 127 cl::location(LimitFloatPrecision), cl::Hidden, 128 cl::init(0)); 129 130 static cl::opt<unsigned> SwitchPeelThreshold( 131 "switch-peel-threshold", cl::Hidden, cl::init(66), 132 cl::desc("Set the case probability threshold for peeling the case from a " 133 "switch statement. A value greater than 100 will void this " 134 "optimization")); 135 136 // Limit the width of DAG chains. This is important in general to prevent 137 // DAG-based analysis from blowing up. For example, alias analysis and 138 // load clustering may not complete in reasonable time. It is difficult to 139 // recognize and avoid this situation within each individual analysis, and 140 // future analyses are likely to have the same behavior. Limiting DAG width is 141 // the safe approach and will be especially important with global DAGs. 142 // 143 // MaxParallelChains default is arbitrarily high to avoid affecting 144 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 145 // sequence over this should have been converted to llvm.memcpy by the 146 // frontend. It is easy to induce this behavior with .ll code such as: 147 // %buffer = alloca [4096 x i8] 148 // %data = load [4096 x i8]* %argPtr 149 // store [4096 x i8] %data, [4096 x i8]* %buffer 150 static const unsigned MaxParallelChains = 64; 151 152 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 153 const SDValue *Parts, unsigned NumParts, 154 MVT PartVT, EVT ValueVT, const Value *V, 155 std::optional<CallingConv::ID> CC); 156 157 /// getCopyFromParts - Create a value that contains the specified legal parts 158 /// combined into the value they represent. If the parts combine to a type 159 /// larger than ValueVT then AssertOp can be used to specify whether the extra 160 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 161 /// (ISD::AssertSext). 162 static SDValue 163 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, 164 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, 165 std::optional<CallingConv::ID> CC = std::nullopt, 166 std::optional<ISD::NodeType> AssertOp = std::nullopt) { 167 // Let the target assemble the parts if it wants to 168 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 169 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 170 PartVT, ValueVT, CC)) 171 return Val; 172 173 if (ValueVT.isVector()) 174 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 175 CC); 176 177 assert(NumParts > 0 && "No parts to assemble!"); 178 SDValue Val = Parts[0]; 179 180 if (NumParts > 1) { 181 // Assemble the value from multiple parts. 182 if (ValueVT.isInteger()) { 183 unsigned PartBits = PartVT.getSizeInBits(); 184 unsigned ValueBits = ValueVT.getSizeInBits(); 185 186 // Assemble the power of 2 part. 187 unsigned RoundParts = llvm::bit_floor(NumParts); 188 unsigned RoundBits = PartBits * RoundParts; 189 EVT RoundVT = RoundBits == ValueBits ? 190 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 191 SDValue Lo, Hi; 192 193 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 194 195 if (RoundParts > 2) { 196 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 197 PartVT, HalfVT, V); 198 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 199 RoundParts / 2, PartVT, HalfVT, V); 200 } else { 201 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 202 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 203 } 204 205 if (DAG.getDataLayout().isBigEndian()) 206 std::swap(Lo, Hi); 207 208 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 209 210 if (RoundParts < NumParts) { 211 // Assemble the trailing non-power-of-2 part. 212 unsigned OddParts = NumParts - RoundParts; 213 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 214 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 215 OddVT, V, CC); 216 217 // Combine the round and odd parts. 218 Lo = Val; 219 if (DAG.getDataLayout().isBigEndian()) 220 std::swap(Lo, Hi); 221 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 222 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 223 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 224 DAG.getConstant(Lo.getValueSizeInBits(), DL, 225 TLI.getShiftAmountTy( 226 TotalVT, DAG.getDataLayout()))); 227 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 228 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 229 } 230 } else if (PartVT.isFloatingPoint()) { 231 // FP split into multiple FP parts (for ppcf128) 232 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 233 "Unexpected split"); 234 SDValue Lo, Hi; 235 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 236 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 237 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 238 std::swap(Lo, Hi); 239 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 240 } else { 241 // FP split into integer parts (soft fp) 242 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 243 !PartVT.isVector() && "Unexpected split"); 244 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 245 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 246 } 247 } 248 249 // There is now one part, held in Val. Correct it to match ValueVT. 250 // PartEVT is the type of the register class that holds the value. 251 // ValueVT is the type of the inline asm operation. 252 EVT PartEVT = Val.getValueType(); 253 254 if (PartEVT == ValueVT) 255 return Val; 256 257 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 258 ValueVT.bitsLT(PartEVT)) { 259 // For an FP value in an integer part, we need to truncate to the right 260 // width first. 261 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 262 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 263 } 264 265 // Handle types that have the same size. 266 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 267 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 268 269 // Handle types with different sizes. 270 if (PartEVT.isInteger() && ValueVT.isInteger()) { 271 if (ValueVT.bitsLT(PartEVT)) { 272 // For a truncate, see if we have any information to 273 // indicate whether the truncated bits will always be 274 // zero or sign-extension. 275 if (AssertOp) 276 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 277 DAG.getValueType(ValueVT)); 278 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 279 } 280 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 281 } 282 283 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 284 // FP_ROUND's are always exact here. 285 if (ValueVT.bitsLT(Val.getValueType())) 286 return DAG.getNode( 287 ISD::FP_ROUND, DL, ValueVT, Val, 288 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 289 290 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 291 } 292 293 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 294 // then truncating. 295 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 296 ValueVT.bitsLT(PartEVT)) { 297 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 298 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 299 } 300 301 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 302 } 303 304 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 305 const Twine &ErrMsg) { 306 const Instruction *I = dyn_cast_or_null<Instruction>(V); 307 if (!V) 308 return Ctx.emitError(ErrMsg); 309 310 const char *AsmError = ", possible invalid constraint for vector type"; 311 if (const CallInst *CI = dyn_cast<CallInst>(I)) 312 if (CI->isInlineAsm()) 313 return Ctx.emitError(I, ErrMsg + AsmError); 314 315 return Ctx.emitError(I, ErrMsg); 316 } 317 318 /// getCopyFromPartsVector - Create a value that contains the specified legal 319 /// parts combined into the value they represent. If the parts combine to a 320 /// type larger than ValueVT then AssertOp can be used to specify whether the 321 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 322 /// ValueVT (ISD::AssertSext). 323 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 324 const SDValue *Parts, unsigned NumParts, 325 MVT PartVT, EVT ValueVT, const Value *V, 326 std::optional<CallingConv::ID> CallConv) { 327 assert(ValueVT.isVector() && "Not a vector value"); 328 assert(NumParts > 0 && "No parts to assemble!"); 329 const bool IsABIRegCopy = CallConv.has_value(); 330 331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 332 SDValue Val = Parts[0]; 333 334 // Handle a multi-element vector. 335 if (NumParts > 1) { 336 EVT IntermediateVT; 337 MVT RegisterVT; 338 unsigned NumIntermediates; 339 unsigned NumRegs; 340 341 if (IsABIRegCopy) { 342 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 343 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, 344 NumIntermediates, RegisterVT); 345 } else { 346 NumRegs = 347 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 348 NumIntermediates, RegisterVT); 349 } 350 351 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 352 NumParts = NumRegs; // Silence a compiler warning. 353 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 354 assert(RegisterVT.getSizeInBits() == 355 Parts[0].getSimpleValueType().getSizeInBits() && 356 "Part type sizes don't match!"); 357 358 // Assemble the parts into intermediate operands. 359 SmallVector<SDValue, 8> Ops(NumIntermediates); 360 if (NumIntermediates == NumParts) { 361 // If the register was not expanded, truncate or copy the value, 362 // as appropriate. 363 for (unsigned i = 0; i != NumParts; ++i) 364 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 365 PartVT, IntermediateVT, V, CallConv); 366 } else if (NumParts > 0) { 367 // If the intermediate type was expanded, build the intermediate 368 // operands from the parts. 369 assert(NumParts % NumIntermediates == 0 && 370 "Must expand into a divisible number of parts!"); 371 unsigned Factor = NumParts / NumIntermediates; 372 for (unsigned i = 0; i != NumIntermediates; ++i) 373 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 374 PartVT, IntermediateVT, V, CallConv); 375 } 376 377 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 378 // intermediate operands. 379 EVT BuiltVectorTy = 380 IntermediateVT.isVector() 381 ? EVT::getVectorVT( 382 *DAG.getContext(), IntermediateVT.getScalarType(), 383 IntermediateVT.getVectorElementCount() * NumParts) 384 : EVT::getVectorVT(*DAG.getContext(), 385 IntermediateVT.getScalarType(), 386 NumIntermediates); 387 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 388 : ISD::BUILD_VECTOR, 389 DL, BuiltVectorTy, Ops); 390 } 391 392 // There is now one part, held in Val. Correct it to match ValueVT. 393 EVT PartEVT = Val.getValueType(); 394 395 if (PartEVT == ValueVT) 396 return Val; 397 398 if (PartEVT.isVector()) { 399 // Vector/Vector bitcast. 400 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 401 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 402 403 // If the parts vector has more elements than the value vector, then we 404 // have a vector widening case (e.g. <2 x float> -> <4 x float>). 405 // Extract the elements we want. 406 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 PartEVT = 413 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(), 414 ValueVT.getVectorElementCount()); 415 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val, 416 DAG.getVectorIdxConstant(0, DL)); 417 if (PartEVT == ValueVT) 418 return Val; 419 if (PartEVT.isInteger() && ValueVT.isFloatingPoint()) 420 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 421 422 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>). 423 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 424 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 425 } 426 427 // Promoted vector extract 428 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 429 } 430 431 // Trivial bitcast if the types are the same size and the destination 432 // vector type is legal. 433 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 434 TLI.isTypeLegal(ValueVT)) 435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 436 437 if (ValueVT.getVectorNumElements() != 1) { 438 // Certain ABIs require that vectors are passed as integers. For vectors 439 // are the same size, this is an obvious bitcast. 440 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 441 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 442 } else if (ValueVT.bitsLT(PartEVT)) { 443 const uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 444 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 445 // Drop the extra bits. 446 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 447 return DAG.getBitcast(ValueVT, Val); 448 } 449 450 diagnosePossiblyInvalidConstraint( 451 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 452 return DAG.getUNDEF(ValueVT); 453 } 454 455 // Handle cases such as i8 -> <1 x i1> 456 EVT ValueSVT = ValueVT.getVectorElementType(); 457 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 458 unsigned ValueSize = ValueSVT.getSizeInBits(); 459 if (ValueSize == PartEVT.getSizeInBits()) { 460 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 461 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) { 462 // It's possible a scalar floating point type gets softened to integer and 463 // then promoted to a larger integer. If PartEVT is the larger integer 464 // we need to truncate it and then bitcast to the FP type. 465 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types"); 466 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 467 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val); 468 Val = DAG.getBitcast(ValueSVT, Val); 469 } else { 470 Val = ValueVT.isFloatingPoint() 471 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 472 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 473 } 474 } 475 476 return DAG.getBuildVector(ValueVT, DL, Val); 477 } 478 479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 480 SDValue Val, SDValue *Parts, unsigned NumParts, 481 MVT PartVT, const Value *V, 482 std::optional<CallingConv::ID> CallConv); 483 484 /// getCopyToParts - Create a series of nodes that contain the specified value 485 /// split into legal parts. If the parts contain more bits than Val, then, for 486 /// integers, ExtendKind can be used to specify how to generate the extra bits. 487 static void 488 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 489 unsigned NumParts, MVT PartVT, const Value *V, 490 std::optional<CallingConv::ID> CallConv = std::nullopt, 491 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 492 // Let the target split the parts if it wants to 493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 494 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 495 CallConv)) 496 return; 497 EVT ValueVT = Val.getValueType(); 498 499 // Handle the vector case separately. 500 if (ValueVT.isVector()) 501 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 502 CallConv); 503 504 unsigned OrigNumParts = NumParts; 505 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 506 "Copying to an illegal type!"); 507 508 if (NumParts == 0) 509 return; 510 511 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 512 EVT PartEVT = PartVT; 513 if (PartEVT == ValueVT) { 514 assert(NumParts == 1 && "No-op copy with multiple parts!"); 515 Parts[0] = Val; 516 return; 517 } 518 519 unsigned PartBits = PartVT.getSizeInBits(); 520 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 521 // If the parts cover more bits than the value has, promote the value. 522 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 523 assert(NumParts == 1 && "Do not know what to promote to!"); 524 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 525 } else { 526 if (ValueVT.isFloatingPoint()) { 527 // FP values need to be bitcast, then extended if they are being put 528 // into a larger container. 529 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 530 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 531 } 532 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 533 ValueVT.isInteger() && 534 "Unknown mismatch!"); 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 536 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 537 if (PartVT == MVT::x86mmx) 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } 540 } else if (PartBits == ValueVT.getSizeInBits()) { 541 // Different types of the same size. 542 assert(NumParts == 1 && PartEVT != ValueVT); 543 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 544 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 545 // If the parts cover less bits than value has, truncate the value. 546 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 547 ValueVT.isInteger() && 548 "Unknown mismatch!"); 549 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 550 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 551 if (PartVT == MVT::x86mmx) 552 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 553 } 554 555 // The value may have changed - recompute ValueVT. 556 ValueVT = Val.getValueType(); 557 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 558 "Failed to tile the value with PartVT!"); 559 560 if (NumParts == 1) { 561 if (PartEVT != ValueVT) { 562 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 563 "scalar-to-vector conversion failed"); 564 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 565 } 566 567 Parts[0] = Val; 568 return; 569 } 570 571 // Expand the value into multiple parts. 572 if (NumParts & (NumParts - 1)) { 573 // The number of parts is not a power of 2. Split off and copy the tail. 574 assert(PartVT.isInteger() && ValueVT.isInteger() && 575 "Do not know what to expand to!"); 576 unsigned RoundParts = llvm::bit_floor(NumParts); 577 unsigned RoundBits = RoundParts * PartBits; 578 unsigned OddParts = NumParts - RoundParts; 579 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 580 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL)); 581 582 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 583 CallConv); 584 585 if (DAG.getDataLayout().isBigEndian()) 586 // The odd parts were reversed by getCopyToParts - unreverse them. 587 std::reverse(Parts + RoundParts, Parts + NumParts); 588 589 NumParts = RoundParts; 590 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 591 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 592 } 593 594 // The number of parts is a power of 2. Repeatedly bisect the value using 595 // EXTRACT_ELEMENT. 596 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 597 EVT::getIntegerVT(*DAG.getContext(), 598 ValueVT.getSizeInBits()), 599 Val); 600 601 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 602 for (unsigned i = 0; i < NumParts; i += StepSize) { 603 unsigned ThisBits = StepSize * PartBits / 2; 604 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 605 SDValue &Part0 = Parts[i]; 606 SDValue &Part1 = Parts[i+StepSize/2]; 607 608 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 609 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 610 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 611 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 612 613 if (ThisBits == PartBits && ThisVT != PartVT) { 614 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 615 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 616 } 617 } 618 } 619 620 if (DAG.getDataLayout().isBigEndian()) 621 std::reverse(Parts, Parts + OrigNumParts); 622 } 623 624 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, 625 const SDLoc &DL, EVT PartVT) { 626 if (!PartVT.isVector()) 627 return SDValue(); 628 629 EVT ValueVT = Val.getValueType(); 630 EVT PartEVT = PartVT.getVectorElementType(); 631 EVT ValueEVT = ValueVT.getVectorElementType(); 632 ElementCount PartNumElts = PartVT.getVectorElementCount(); 633 ElementCount ValueNumElts = ValueVT.getVectorElementCount(); 634 635 // We only support widening vectors with equivalent element types and 636 // fixed/scalable properties. If a target needs to widen a fixed-length type 637 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below. 638 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) || 639 PartNumElts.isScalable() != ValueNumElts.isScalable()) 640 return SDValue(); 641 642 // Have a try for bf16 because some targets share its ABI with fp16. 643 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) { 644 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 645 "Cannot widen to illegal type"); 646 Val = DAG.getNode(ISD::BITCAST, DL, 647 ValueVT.changeVectorElementType(MVT::f16), Val); 648 } else if (PartEVT != ValueEVT) { 649 return SDValue(); 650 } 651 652 // Widening a scalable vector to another scalable vector is done by inserting 653 // the vector into a larger undef one. 654 if (PartNumElts.isScalable()) 655 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 656 Val, DAG.getVectorIdxConstant(0, DL)); 657 658 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 659 // undef elements. 660 SmallVector<SDValue, 16> Ops; 661 DAG.ExtractVectorElements(Val, Ops); 662 SDValue EltUndef = DAG.getUNDEF(PartEVT); 663 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef); 664 665 // FIXME: Use CONCAT for 2x -> 4x. 666 return DAG.getBuildVector(PartVT, DL, Ops); 667 } 668 669 /// getCopyToPartsVector - Create a series of nodes that contain the specified 670 /// value split into legal parts. 671 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 672 SDValue Val, SDValue *Parts, unsigned NumParts, 673 MVT PartVT, const Value *V, 674 std::optional<CallingConv::ID> CallConv) { 675 EVT ValueVT = Val.getValueType(); 676 assert(ValueVT.isVector() && "Not a vector"); 677 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 678 const bool IsABIRegCopy = CallConv.has_value(); 679 680 if (NumParts == 1) { 681 EVT PartEVT = PartVT; 682 if (PartEVT == ValueVT) { 683 // Nothing to do. 684 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 685 // Bitconvert vector->vector case. 686 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 687 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 688 Val = Widened; 689 } else if (PartVT.isVector() && 690 PartEVT.getVectorElementType().bitsGE( 691 ValueVT.getVectorElementType()) && 692 PartEVT.getVectorElementCount() == 693 ValueVT.getVectorElementCount()) { 694 695 // Promoted vector extract 696 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 697 } else if (PartEVT.isVector() && 698 PartEVT.getVectorElementType() != 699 ValueVT.getVectorElementType() && 700 TLI.getTypeAction(*DAG.getContext(), ValueVT) == 701 TargetLowering::TypeWidenVector) { 702 // Combination of widening and promotion. 703 EVT WidenVT = 704 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(), 705 PartVT.getVectorElementCount()); 706 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT); 707 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT); 708 } else { 709 // Don't extract an integer from a float vector. This can happen if the 710 // FP type gets softened to integer and then promoted. The promotion 711 // prevents it from being picked up by the earlier bitcast case. 712 if (ValueVT.getVectorElementCount().isScalar() && 713 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) { 714 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 715 DAG.getVectorIdxConstant(0, DL)); 716 } else { 717 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 718 assert(PartVT.getFixedSizeInBits() > ValueSize && 719 "lossy conversion of vector to scalar type"); 720 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 721 Val = DAG.getBitcast(IntermediateType, Val); 722 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 723 } 724 } 725 726 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 727 Parts[0] = Val; 728 return; 729 } 730 731 // Handle a multi-element vector. 732 EVT IntermediateVT; 733 MVT RegisterVT; 734 unsigned NumIntermediates; 735 unsigned NumRegs; 736 if (IsABIRegCopy) { 737 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 738 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates, 739 RegisterVT); 740 } else { 741 NumRegs = 742 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 743 NumIntermediates, RegisterVT); 744 } 745 746 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 747 NumParts = NumRegs; // Silence a compiler warning. 748 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 749 750 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 751 "Mixing scalable and fixed vectors when copying in parts"); 752 753 std::optional<ElementCount> DestEltCnt; 754 755 if (IntermediateVT.isVector()) 756 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 757 else 758 DestEltCnt = ElementCount::getFixed(NumIntermediates); 759 760 EVT BuiltVectorTy = EVT::getVectorVT( 761 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt); 762 763 if (ValueVT == BuiltVectorTy) { 764 // Nothing to do. 765 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) { 766 // Bitconvert vector->vector case. 767 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 768 } else { 769 if (BuiltVectorTy.getVectorElementType().bitsGT( 770 ValueVT.getVectorElementType())) { 771 // Integer promotion. 772 ValueVT = EVT::getVectorVT(*DAG.getContext(), 773 BuiltVectorTy.getVectorElementType(), 774 ValueVT.getVectorElementCount()); 775 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 776 } 777 778 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) { 779 Val = Widened; 780 } 781 } 782 783 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type"); 784 785 // Split the vector into intermediate operands. 786 SmallVector<SDValue, 8> Ops(NumIntermediates); 787 for (unsigned i = 0; i != NumIntermediates; ++i) { 788 if (IntermediateVT.isVector()) { 789 // This does something sensible for scalable vectors - see the 790 // definition of EXTRACT_SUBVECTOR for further details. 791 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 792 Ops[i] = 793 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 794 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 795 } else { 796 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 797 DAG.getVectorIdxConstant(i, DL)); 798 } 799 } 800 801 // Split the intermediate operands into legal parts. 802 if (NumParts == NumIntermediates) { 803 // If the register was not expanded, promote or copy the value, 804 // as appropriate. 805 for (unsigned i = 0; i != NumParts; ++i) 806 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 807 } else if (NumParts > 0) { 808 // If the intermediate type was expanded, split each the value into 809 // legal parts. 810 assert(NumIntermediates != 0 && "division by zero"); 811 assert(NumParts % NumIntermediates == 0 && 812 "Must expand into a divisible number of parts!"); 813 unsigned Factor = NumParts / NumIntermediates; 814 for (unsigned i = 0; i != NumIntermediates; ++i) 815 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 816 CallConv); 817 } 818 } 819 820 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 821 EVT valuevt, std::optional<CallingConv::ID> CC) 822 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 823 RegCount(1, regs.size()), CallConv(CC) {} 824 825 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 826 const DataLayout &DL, unsigned Reg, Type *Ty, 827 std::optional<CallingConv::ID> CC) { 828 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 829 830 CallConv = CC; 831 832 for (EVT ValueVT : ValueVTs) { 833 unsigned NumRegs = 834 isABIMangled() 835 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT) 836 : TLI.getNumRegisters(Context, ValueVT); 837 MVT RegisterVT = 838 isABIMangled() 839 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT) 840 : TLI.getRegisterType(Context, ValueVT); 841 for (unsigned i = 0; i != NumRegs; ++i) 842 Regs.push_back(Reg + i); 843 RegVTs.push_back(RegisterVT); 844 RegCount.push_back(NumRegs); 845 Reg += NumRegs; 846 } 847 } 848 849 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 850 FunctionLoweringInfo &FuncInfo, 851 const SDLoc &dl, SDValue &Chain, 852 SDValue *Glue, const Value *V) const { 853 // A Value with type {} or [0 x %t] needs no registers. 854 if (ValueVTs.empty()) 855 return SDValue(); 856 857 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 858 859 // Assemble the legal parts into the final values. 860 SmallVector<SDValue, 4> Values(ValueVTs.size()); 861 SmallVector<SDValue, 8> Parts; 862 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 863 // Copy the legal parts from the registers. 864 EVT ValueVT = ValueVTs[Value]; 865 unsigned NumRegs = RegCount[Value]; 866 MVT RegisterVT = isABIMangled() 867 ? TLI.getRegisterTypeForCallingConv( 868 *DAG.getContext(), *CallConv, RegVTs[Value]) 869 : RegVTs[Value]; 870 871 Parts.resize(NumRegs); 872 for (unsigned i = 0; i != NumRegs; ++i) { 873 SDValue P; 874 if (!Glue) { 875 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 876 } else { 877 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue); 878 *Glue = P.getValue(2); 879 } 880 881 Chain = P.getValue(1); 882 Parts[i] = P; 883 884 // If the source register was virtual and if we know something about it, 885 // add an assert node. 886 if (!Register::isVirtualRegister(Regs[Part + i]) || 887 !RegisterVT.isInteger()) 888 continue; 889 890 const FunctionLoweringInfo::LiveOutInfo *LOI = 891 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 892 if (!LOI) 893 continue; 894 895 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 896 unsigned NumSignBits = LOI->NumSignBits; 897 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 898 899 if (NumZeroBits == RegSize) { 900 // The current value is a zero. 901 // Explicitly express that as it would be easier for 902 // optimizations to kick in. 903 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 904 continue; 905 } 906 907 // FIXME: We capture more information than the dag can represent. For 908 // now, just use the tightest assertzext/assertsext possible. 909 bool isSExt; 910 EVT FromVT(MVT::Other); 911 if (NumZeroBits) { 912 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 913 isSExt = false; 914 } else if (NumSignBits > 1) { 915 FromVT = 916 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 917 isSExt = true; 918 } else { 919 continue; 920 } 921 // Add an assertion node. 922 assert(FromVT != MVT::Other); 923 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 924 RegisterVT, P, DAG.getValueType(FromVT)); 925 } 926 927 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 928 RegisterVT, ValueVT, V, CallConv); 929 Part += NumRegs; 930 Parts.clear(); 931 } 932 933 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 934 } 935 936 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 937 const SDLoc &dl, SDValue &Chain, SDValue *Glue, 938 const Value *V, 939 ISD::NodeType PreferredExtendType) const { 940 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 941 ISD::NodeType ExtendKind = PreferredExtendType; 942 943 // Get the list of the values's legal parts. 944 unsigned NumRegs = Regs.size(); 945 SmallVector<SDValue, 8> Parts(NumRegs); 946 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 947 unsigned NumParts = RegCount[Value]; 948 949 MVT RegisterVT = isABIMangled() 950 ? TLI.getRegisterTypeForCallingConv( 951 *DAG.getContext(), *CallConv, RegVTs[Value]) 952 : RegVTs[Value]; 953 954 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 955 ExtendKind = ISD::ZERO_EXTEND; 956 957 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 958 NumParts, RegisterVT, V, CallConv, ExtendKind); 959 Part += NumParts; 960 } 961 962 // Copy the parts into the registers. 963 SmallVector<SDValue, 8> Chains(NumRegs); 964 for (unsigned i = 0; i != NumRegs; ++i) { 965 SDValue Part; 966 if (!Glue) { 967 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 968 } else { 969 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue); 970 *Glue = Part.getValue(1); 971 } 972 973 Chains[i] = Part.getValue(0); 974 } 975 976 if (NumRegs == 1 || Glue) 977 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is 978 // flagged to it. That is the CopyToReg nodes and the user are considered 979 // a single scheduling unit. If we create a TokenFactor and return it as 980 // chain, then the TokenFactor is both a predecessor (operand) of the 981 // user as well as a successor (the TF operands are flagged to the user). 982 // c1, f1 = CopyToReg 983 // c2, f2 = CopyToReg 984 // c3 = TokenFactor c1, c2 985 // ... 986 // = op c3, ..., f2 987 Chain = Chains[NumRegs-1]; 988 else 989 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 990 } 991 992 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 993 unsigned MatchingIdx, const SDLoc &dl, 994 SelectionDAG &DAG, 995 std::vector<SDValue> &Ops) const { 996 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 997 998 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 999 if (HasMatching) 1000 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 1001 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 1002 // Put the register class of the virtual registers in the flag word. That 1003 // way, later passes can recompute register class constraints for inline 1004 // assembly as well as normal instructions. 1005 // Don't do this for tied operands that can use the regclass information 1006 // from the def. 1007 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1008 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 1009 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 1010 } 1011 1012 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 1013 Ops.push_back(Res); 1014 1015 if (Code == InlineAsm::Kind_Clobber) { 1016 // Clobbers should always have a 1:1 mapping with registers, and may 1017 // reference registers that have illegal (e.g. vector) types. Hence, we 1018 // shouldn't try to apply any sort of splitting logic to them. 1019 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1020 "No 1:1 mapping from clobbers to regs?"); 1021 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 1022 (void)SP; 1023 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1024 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1025 assert( 1026 (Regs[I] != SP || 1027 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1028 "If we clobbered the stack pointer, MFI should know about it."); 1029 } 1030 return; 1031 } 1032 1033 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1034 MVT RegisterVT = RegVTs[Value]; 1035 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value], 1036 RegisterVT); 1037 for (unsigned i = 0; i != NumRegs; ++i) { 1038 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1039 unsigned TheReg = Regs[Reg++]; 1040 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1041 } 1042 } 1043 } 1044 1045 SmallVector<std::pair<unsigned, TypeSize>, 4> 1046 RegsForValue::getRegsAndSizes() const { 1047 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec; 1048 unsigned I = 0; 1049 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1050 unsigned RegCount = std::get<0>(CountAndVT); 1051 MVT RegisterVT = std::get<1>(CountAndVT); 1052 TypeSize RegisterSize = RegisterVT.getSizeInBits(); 1053 for (unsigned E = I + RegCount; I != E; ++I) 1054 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1055 } 1056 return OutVec; 1057 } 1058 1059 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1060 AssumptionCache *ac, 1061 const TargetLibraryInfo *li) { 1062 AA = aa; 1063 AC = ac; 1064 GFI = gfi; 1065 LibInfo = li; 1066 Context = DAG.getContext(); 1067 LPadToCallSiteMap.clear(); 1068 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1069 AssignmentTrackingEnabled = isAssignmentTrackingEnabled( 1070 *DAG.getMachineFunction().getFunction().getParent()); 1071 } 1072 1073 void SelectionDAGBuilder::clear() { 1074 NodeMap.clear(); 1075 UnusedArgNodeMap.clear(); 1076 PendingLoads.clear(); 1077 PendingExports.clear(); 1078 PendingConstrainedFP.clear(); 1079 PendingConstrainedFPStrict.clear(); 1080 CurInst = nullptr; 1081 HasTailCall = false; 1082 SDNodeOrder = LowestSDNodeOrder; 1083 StatepointLowering.clear(); 1084 } 1085 1086 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1087 DanglingDebugInfoMap.clear(); 1088 } 1089 1090 // Update DAG root to include dependencies on Pending chains. 1091 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1092 SDValue Root = DAG.getRoot(); 1093 1094 if (Pending.empty()) 1095 return Root; 1096 1097 // Add current root to PendingChains, unless we already indirectly 1098 // depend on it. 1099 if (Root.getOpcode() != ISD::EntryToken) { 1100 unsigned i = 0, e = Pending.size(); 1101 for (; i != e; ++i) { 1102 assert(Pending[i].getNode()->getNumOperands() > 1); 1103 if (Pending[i].getNode()->getOperand(0) == Root) 1104 break; // Don't add the root if we already indirectly depend on it. 1105 } 1106 1107 if (i == e) 1108 Pending.push_back(Root); 1109 } 1110 1111 if (Pending.size() == 1) 1112 Root = Pending[0]; 1113 else 1114 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1115 1116 DAG.setRoot(Root); 1117 Pending.clear(); 1118 return Root; 1119 } 1120 1121 SDValue SelectionDAGBuilder::getMemoryRoot() { 1122 return updateRoot(PendingLoads); 1123 } 1124 1125 SDValue SelectionDAGBuilder::getRoot() { 1126 // Chain up all pending constrained intrinsics together with all 1127 // pending loads, by simply appending them to PendingLoads and 1128 // then calling getMemoryRoot(). 1129 PendingLoads.reserve(PendingLoads.size() + 1130 PendingConstrainedFP.size() + 1131 PendingConstrainedFPStrict.size()); 1132 PendingLoads.append(PendingConstrainedFP.begin(), 1133 PendingConstrainedFP.end()); 1134 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1135 PendingConstrainedFPStrict.end()); 1136 PendingConstrainedFP.clear(); 1137 PendingConstrainedFPStrict.clear(); 1138 return getMemoryRoot(); 1139 } 1140 1141 SDValue SelectionDAGBuilder::getControlRoot() { 1142 // We need to emit pending fpexcept.strict constrained intrinsics, 1143 // so append them to the PendingExports list. 1144 PendingExports.append(PendingConstrainedFPStrict.begin(), 1145 PendingConstrainedFPStrict.end()); 1146 PendingConstrainedFPStrict.clear(); 1147 return updateRoot(PendingExports); 1148 } 1149 1150 void SelectionDAGBuilder::visit(const Instruction &I) { 1151 // Set up outgoing PHI node register values before emitting the terminator. 1152 if (I.isTerminator()) { 1153 HandlePHINodesInSuccessorBlocks(I.getParent()); 1154 } 1155 1156 // Add SDDbgValue nodes for any var locs here. Do so before updating 1157 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1158 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) { 1159 // Add SDDbgValue nodes for any var locs here. Do so before updating 1160 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}. 1161 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I); 1162 It != End; ++It) { 1163 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID); 1164 dropDanglingDebugInfo(Var, It->Expr); 1165 if (It->Values.isKillLocation(It->Expr)) { 1166 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder); 1167 continue; 1168 } 1169 SmallVector<Value *> Values(It->Values.location_ops()); 1170 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder, 1171 It->Values.hasArgList())) 1172 addDanglingDebugInfo(It, SDNodeOrder); 1173 } 1174 } 1175 1176 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1177 if (!isa<DbgInfoIntrinsic>(I)) 1178 ++SDNodeOrder; 1179 1180 CurInst = &I; 1181 1182 // Set inserted listener only if required. 1183 bool NodeInserted = false; 1184 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener; 1185 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections); 1186 if (PCSectionsMD) { 1187 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>( 1188 DAG, [&](SDNode *) { NodeInserted = true; }); 1189 } 1190 1191 visit(I.getOpcode(), I); 1192 1193 if (!I.isTerminator() && !HasTailCall && 1194 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1195 CopyToExportRegsIfNeeded(&I); 1196 1197 // Handle metadata. 1198 if (PCSectionsMD) { 1199 auto It = NodeMap.find(&I); 1200 if (It != NodeMap.end()) { 1201 DAG.addPCSections(It->second.getNode(), PCSectionsMD); 1202 } else if (NodeInserted) { 1203 // This should not happen; if it does, don't let it go unnoticed so we can 1204 // fix it. Relevant visit*() function is probably missing a setValue(). 1205 errs() << "warning: loosing !pcsections metadata [" 1206 << I.getModule()->getName() << "]\n"; 1207 LLVM_DEBUG(I.dump()); 1208 assert(false); 1209 } 1210 } 1211 1212 CurInst = nullptr; 1213 } 1214 1215 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1216 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1217 } 1218 1219 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1220 // Note: this doesn't use InstVisitor, because it has to work with 1221 // ConstantExpr's in addition to instructions. 1222 switch (Opcode) { 1223 default: llvm_unreachable("Unknown instruction type encountered!"); 1224 // Build the switch statement using the Instruction.def file. 1225 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1226 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1227 #include "llvm/IR/Instruction.def" 1228 } 1229 } 1230 1231 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, 1232 DILocalVariable *Variable, 1233 DebugLoc DL, unsigned Order, 1234 RawLocationWrapper Values, 1235 DIExpression *Expression) { 1236 if (!Values.hasArgList()) 1237 return false; 1238 // For variadic dbg_values we will now insert an undef. 1239 // FIXME: We can potentially recover these! 1240 SmallVector<SDDbgOperand, 2> Locs; 1241 for (const Value *V : Values.location_ops()) { 1242 auto *Undef = UndefValue::get(V->getType()); 1243 Locs.push_back(SDDbgOperand::fromConst(Undef)); 1244 } 1245 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {}, 1246 /*IsIndirect=*/false, DL, Order, 1247 /*IsVariadic=*/true); 1248 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1249 return true; 1250 } 1251 1252 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc, 1253 unsigned Order) { 1254 if (!handleDanglingVariadicDebugInfo( 1255 DAG, 1256 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs() 1257 ->getVariable(VarLoc->VariableID) 1258 .getVariable()), 1259 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) { 1260 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back( 1261 VarLoc, Order); 1262 } 1263 } 1264 1265 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI, 1266 unsigned Order) { 1267 // We treat variadic dbg_values differently at this stage. 1268 if (!handleDanglingVariadicDebugInfo( 1269 DAG, DI->getVariable(), DI->getDebugLoc(), Order, 1270 DI->getWrappedLocation(), DI->getExpression())) { 1271 // TODO: Dangling debug info will eventually either be resolved or produce 1272 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 1273 // between the original dbg.value location and its resolved DBG_VALUE, 1274 // which we should ideally fill with an extra Undef DBG_VALUE. 1275 assert(DI->getNumVariableLocationOps() == 1 && 1276 "DbgValueInst without an ArgList should have a single location " 1277 "operand."); 1278 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order); 1279 } 1280 } 1281 1282 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1283 const DIExpression *Expr) { 1284 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1285 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs()); 1286 DIExpression *DanglingExpr = DDI.getExpression(); 1287 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1288 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI) 1289 << "\n"); 1290 return true; 1291 } 1292 return false; 1293 }; 1294 1295 for (auto &DDIMI : DanglingDebugInfoMap) { 1296 DanglingDebugInfoVector &DDIV = DDIMI.second; 1297 1298 // If debug info is to be dropped, run it through final checks to see 1299 // whether it can be salvaged. 1300 for (auto &DDI : DDIV) 1301 if (isMatchingDbgValue(DDI)) 1302 salvageUnresolvedDbgValue(DDI); 1303 1304 erase_if(DDIV, isMatchingDbgValue); 1305 } 1306 } 1307 1308 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1309 // generate the debug data structures now that we've seen its definition. 1310 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1311 SDValue Val) { 1312 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1313 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1314 return; 1315 1316 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1317 for (auto &DDI : DDIV) { 1318 DebugLoc DL = DDI.getDebugLoc(); 1319 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1320 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1321 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs()); 1322 DIExpression *Expr = DDI.getExpression(); 1323 assert(Variable->isValidLocationForIntrinsic(DL) && 1324 "Expected inlined-at fields to agree"); 1325 SDDbgValue *SDV; 1326 if (Val.getNode()) { 1327 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1328 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1329 // we couldn't resolve it directly when examining the DbgValue intrinsic 1330 // in the first place we should not be more successful here). Unless we 1331 // have some test case that prove this to be correct we should avoid 1332 // calling EmitFuncArgumentDbgValue here. 1333 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL, 1334 FuncArgumentDbgValueKind::Value, Val)) { 1335 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI) 1336 << "\n"); 1337 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1338 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1339 // inserted after the definition of Val when emitting the instructions 1340 // after ISel. An alternative could be to teach 1341 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1342 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1343 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1344 << ValSDNodeOrder << "\n"); 1345 SDV = getDbgValue(Val, Variable, Expr, DL, 1346 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1347 DAG.AddDbgValue(SDV, false); 1348 } else 1349 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " 1350 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"); 1351 } else { 1352 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n"); 1353 auto Undef = UndefValue::get(V->getType()); 1354 auto SDV = 1355 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder); 1356 DAG.AddDbgValue(SDV, false); 1357 } 1358 } 1359 DDIV.clear(); 1360 } 1361 1362 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1363 // TODO: For the variadic implementation, instead of only checking the fail 1364 // state of `handleDebugValue`, we need know specifically which values were 1365 // invalid, so that we attempt to salvage only those values when processing 1366 // a DIArgList. 1367 Value *V = DDI.getVariableLocationOp(0); 1368 Value *OrigV = V; 1369 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs()); 1370 DIExpression *Expr = DDI.getExpression(); 1371 DebugLoc DL = DDI.getDebugLoc(); 1372 unsigned SDOrder = DDI.getSDNodeOrder(); 1373 1374 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1375 // that DW_OP_stack_value is desired. 1376 bool StackValue = true; 1377 1378 // Can this Value can be encoded without any further work? 1379 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) 1380 return; 1381 1382 // Attempt to salvage back through as many instructions as possible. Bail if 1383 // a non-instruction is seen, such as a constant expression or global 1384 // variable. FIXME: Further work could recover those too. 1385 while (isa<Instruction>(V)) { 1386 Instruction &VAsInst = *cast<Instruction>(V); 1387 // Temporary "0", awaiting real implementation. 1388 SmallVector<uint64_t, 16> Ops; 1389 SmallVector<Value *, 4> AdditionalValues; 1390 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops, 1391 AdditionalValues); 1392 // If we cannot salvage any further, and haven't yet found a suitable debug 1393 // expression, bail out. 1394 if (!V) 1395 break; 1396 1397 // TODO: If AdditionalValues isn't empty, then the salvage can only be 1398 // represented with a DBG_VALUE_LIST, so we give up. When we have support 1399 // here for variadic dbg_values, remove that condition. 1400 if (!AdditionalValues.empty()) 1401 break; 1402 1403 // New value and expr now represent this debuginfo. 1404 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue); 1405 1406 // Some kind of simplification occurred: check whether the operand of the 1407 // salvaged debug expression can be encoded in this DAG. 1408 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) { 1409 LLVM_DEBUG( 1410 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n" 1411 << *OrigV << "\nBy stripping back to:\n " << *V << "\n"); 1412 return; 1413 } 1414 } 1415 1416 // This was the final opportunity to salvage this debug information, and it 1417 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1418 // any earlier variable location. 1419 assert(OrigV && "V shouldn't be null"); 1420 auto *Undef = UndefValue::get(OrigV->getType()); 1421 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1422 DAG.AddDbgValue(SDV, false); 1423 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI) 1424 << "\n"); 1425 } 1426 1427 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var, 1428 DIExpression *Expr, 1429 DebugLoc DbgLoc, 1430 unsigned Order) { 1431 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context)); 1432 DIExpression *NewExpr = 1433 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr)); 1434 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order, 1435 /*IsVariadic*/ false); 1436 } 1437 1438 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values, 1439 DILocalVariable *Var, 1440 DIExpression *Expr, DebugLoc DbgLoc, 1441 unsigned Order, bool IsVariadic) { 1442 if (Values.empty()) 1443 return true; 1444 SmallVector<SDDbgOperand> LocationOps; 1445 SmallVector<SDNode *> Dependencies; 1446 for (const Value *V : Values) { 1447 // Constant value. 1448 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1449 isa<ConstantPointerNull>(V)) { 1450 LocationOps.emplace_back(SDDbgOperand::fromConst(V)); 1451 continue; 1452 } 1453 1454 // Look through IntToPtr constants. 1455 if (auto *CE = dyn_cast<ConstantExpr>(V)) 1456 if (CE->getOpcode() == Instruction::IntToPtr) { 1457 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0))); 1458 continue; 1459 } 1460 1461 // If the Value is a frame index, we can create a FrameIndex debug value 1462 // without relying on the DAG at all. 1463 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1464 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1465 if (SI != FuncInfo.StaticAllocaMap.end()) { 1466 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second)); 1467 continue; 1468 } 1469 } 1470 1471 // Do not use getValue() in here; we don't want to generate code at 1472 // this point if it hasn't been done yet. 1473 SDValue N = NodeMap[V]; 1474 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1475 N = UnusedArgNodeMap[V]; 1476 if (N.getNode()) { 1477 // Only emit func arg dbg value for non-variadic dbg.values for now. 1478 if (!IsVariadic && 1479 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc, 1480 FuncArgumentDbgValueKind::Value, N)) 1481 return true; 1482 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 1483 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can 1484 // describe stack slot locations. 1485 // 1486 // Consider "int x = 0; int *px = &x;". There are two kinds of 1487 // interesting debug values here after optimization: 1488 // 1489 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 1490 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 1491 // 1492 // Both describe the direct values of their associated variables. 1493 Dependencies.push_back(N.getNode()); 1494 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex())); 1495 continue; 1496 } 1497 LocationOps.emplace_back( 1498 SDDbgOperand::fromNode(N.getNode(), N.getResNo())); 1499 continue; 1500 } 1501 1502 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1503 // Special rules apply for the first dbg.values of parameter variables in a 1504 // function. Identify them by the fact they reference Argument Values, that 1505 // they're parameters, and they are parameters of the current function. We 1506 // need to let them dangle until they get an SDNode. 1507 bool IsParamOfFunc = 1508 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt(); 1509 if (IsParamOfFunc) 1510 return false; 1511 1512 // The value is not used in this block yet (or it would have an SDNode). 1513 // We still want the value to appear for the user if possible -- if it has 1514 // an associated VReg, we can refer to that instead. 1515 auto VMI = FuncInfo.ValueMap.find(V); 1516 if (VMI != FuncInfo.ValueMap.end()) { 1517 unsigned Reg = VMI->second; 1518 // If this is a PHI node, it may be split up into several MI PHI nodes 1519 // (in FunctionLoweringInfo::set). 1520 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1521 V->getType(), std::nullopt); 1522 if (RFV.occupiesMultipleRegs()) { 1523 // FIXME: We could potentially support variadic dbg_values here. 1524 if (IsVariadic) 1525 return false; 1526 unsigned Offset = 0; 1527 unsigned BitsToDescribe = 0; 1528 if (auto VarSize = Var->getSizeInBits()) 1529 BitsToDescribe = *VarSize; 1530 if (auto Fragment = Expr->getFragmentInfo()) 1531 BitsToDescribe = Fragment->SizeInBits; 1532 for (const auto &RegAndSize : RFV.getRegsAndSizes()) { 1533 // Bail out if all bits are described already. 1534 if (Offset >= BitsToDescribe) 1535 break; 1536 // TODO: handle scalable vectors. 1537 unsigned RegisterSize = RegAndSize.second; 1538 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1539 ? BitsToDescribe - Offset 1540 : RegisterSize; 1541 auto FragmentExpr = DIExpression::createFragmentExpression( 1542 Expr, Offset, FragmentSize); 1543 if (!FragmentExpr) 1544 continue; 1545 SDDbgValue *SDV = DAG.getVRegDbgValue( 1546 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder); 1547 DAG.AddDbgValue(SDV, false); 1548 Offset += RegisterSize; 1549 } 1550 return true; 1551 } 1552 // We can use simple vreg locations for variadic dbg_values as well. 1553 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg)); 1554 continue; 1555 } 1556 // We failed to create a SDDbgOperand for V. 1557 return false; 1558 } 1559 1560 // We have created a SDDbgOperand for each Value in Values. 1561 // Should use Order instead of SDNodeOrder? 1562 assert(!LocationOps.empty()); 1563 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies, 1564 /*IsIndirect=*/false, DbgLoc, 1565 SDNodeOrder, IsVariadic); 1566 DAG.AddDbgValue(SDV, /*isParameter=*/false); 1567 return true; 1568 } 1569 1570 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1571 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1572 for (auto &Pair : DanglingDebugInfoMap) 1573 for (auto &DDI : Pair.second) 1574 salvageUnresolvedDbgValue(DDI); 1575 clearDanglingDebugInfo(); 1576 } 1577 1578 /// getCopyFromRegs - If there was virtual register allocated for the value V 1579 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1580 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1581 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1582 SDValue Result; 1583 1584 if (It != FuncInfo.ValueMap.end()) { 1585 Register InReg = It->second; 1586 1587 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1588 DAG.getDataLayout(), InReg, Ty, 1589 std::nullopt); // This is not an ABI copy. 1590 SDValue Chain = DAG.getEntryNode(); 1591 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1592 V); 1593 resolveDanglingDebugInfo(V, Result); 1594 } 1595 1596 return Result; 1597 } 1598 1599 /// getValue - Return an SDValue for the given Value. 1600 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1601 // If we already have an SDValue for this value, use it. It's important 1602 // to do this first, so that we don't create a CopyFromReg if we already 1603 // have a regular SDValue. 1604 SDValue &N = NodeMap[V]; 1605 if (N.getNode()) return N; 1606 1607 // If there's a virtual register allocated and initialized for this 1608 // value, use it. 1609 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1610 return copyFromReg; 1611 1612 // Otherwise create a new SDValue and remember it. 1613 SDValue Val = getValueImpl(V); 1614 NodeMap[V] = Val; 1615 resolveDanglingDebugInfo(V, Val); 1616 return Val; 1617 } 1618 1619 /// getNonRegisterValue - Return an SDValue for the given Value, but 1620 /// don't look in FuncInfo.ValueMap for a virtual register. 1621 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1622 // If we already have an SDValue for this value, use it. 1623 SDValue &N = NodeMap[V]; 1624 if (N.getNode()) { 1625 if (isIntOrFPConstant(N)) { 1626 // Remove the debug location from the node as the node is about to be used 1627 // in a location which may differ from the original debug location. This 1628 // is relevant to Constant and ConstantFP nodes because they can appear 1629 // as constant expressions inside PHI nodes. 1630 N->setDebugLoc(DebugLoc()); 1631 } 1632 return N; 1633 } 1634 1635 // Otherwise create a new SDValue and remember it. 1636 SDValue Val = getValueImpl(V); 1637 NodeMap[V] = Val; 1638 resolveDanglingDebugInfo(V, Val); 1639 return Val; 1640 } 1641 1642 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1643 /// Create an SDValue for the given value. 1644 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1645 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1646 1647 if (const Constant *C = dyn_cast<Constant>(V)) { 1648 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1649 1650 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1651 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1652 1653 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1654 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1655 1656 if (isa<ConstantPointerNull>(C)) { 1657 unsigned AS = V->getType()->getPointerAddressSpace(); 1658 return DAG.getConstant(0, getCurSDLoc(), 1659 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1660 } 1661 1662 if (match(C, m_VScale())) 1663 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1664 1665 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1666 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1667 1668 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1669 return DAG.getUNDEF(VT); 1670 1671 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1672 visit(CE->getOpcode(), *CE); 1673 SDValue N1 = NodeMap[V]; 1674 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1675 return N1; 1676 } 1677 1678 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1679 SmallVector<SDValue, 4> Constants; 1680 for (const Use &U : C->operands()) { 1681 SDNode *Val = getValue(U).getNode(); 1682 // If the operand is an empty aggregate, there are no values. 1683 if (!Val) continue; 1684 // Add each leaf value from the operand to the Constants list 1685 // to form a flattened list of all the values. 1686 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1687 Constants.push_back(SDValue(Val, i)); 1688 } 1689 1690 return DAG.getMergeValues(Constants, getCurSDLoc()); 1691 } 1692 1693 if (const ConstantDataSequential *CDS = 1694 dyn_cast<ConstantDataSequential>(C)) { 1695 SmallVector<SDValue, 4> Ops; 1696 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1697 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1698 // Add each leaf value from the operand to the Constants list 1699 // to form a flattened list of all the values. 1700 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1701 Ops.push_back(SDValue(Val, i)); 1702 } 1703 1704 if (isa<ArrayType>(CDS->getType())) 1705 return DAG.getMergeValues(Ops, getCurSDLoc()); 1706 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1707 } 1708 1709 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1710 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1711 "Unknown struct or array constant!"); 1712 1713 SmallVector<EVT, 4> ValueVTs; 1714 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1715 unsigned NumElts = ValueVTs.size(); 1716 if (NumElts == 0) 1717 return SDValue(); // empty struct 1718 SmallVector<SDValue, 4> Constants(NumElts); 1719 for (unsigned i = 0; i != NumElts; ++i) { 1720 EVT EltVT = ValueVTs[i]; 1721 if (isa<UndefValue>(C)) 1722 Constants[i] = DAG.getUNDEF(EltVT); 1723 else if (EltVT.isFloatingPoint()) 1724 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1725 else 1726 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1727 } 1728 1729 return DAG.getMergeValues(Constants, getCurSDLoc()); 1730 } 1731 1732 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1733 return DAG.getBlockAddress(BA, VT); 1734 1735 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1736 return getValue(Equiv->getGlobalValue()); 1737 1738 if (const auto *NC = dyn_cast<NoCFIValue>(C)) 1739 return getValue(NC->getGlobalValue()); 1740 1741 VectorType *VecTy = cast<VectorType>(V->getType()); 1742 1743 // Now that we know the number and type of the elements, get that number of 1744 // elements into the Ops array based on what kind of constant it is. 1745 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1746 SmallVector<SDValue, 16> Ops; 1747 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1748 for (unsigned i = 0; i != NumElements; ++i) 1749 Ops.push_back(getValue(CV->getOperand(i))); 1750 1751 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1752 } 1753 1754 if (isa<ConstantAggregateZero>(C)) { 1755 EVT EltVT = 1756 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1757 1758 SDValue Op; 1759 if (EltVT.isFloatingPoint()) 1760 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1761 else 1762 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1763 1764 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op); 1765 } 1766 1767 llvm_unreachable("Unknown vector constant"); 1768 } 1769 1770 // If this is a static alloca, generate it as the frameindex instead of 1771 // computation. 1772 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1773 DenseMap<const AllocaInst*, int>::iterator SI = 1774 FuncInfo.StaticAllocaMap.find(AI); 1775 if (SI != FuncInfo.StaticAllocaMap.end()) 1776 return DAG.getFrameIndex( 1777 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType())); 1778 } 1779 1780 // If this is an instruction which fast-isel has deferred, select it now. 1781 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1782 Register InReg = FuncInfo.InitializeRegForValue(Inst); 1783 1784 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1785 Inst->getType(), std::nullopt); 1786 SDValue Chain = DAG.getEntryNode(); 1787 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1788 } 1789 1790 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) 1791 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1792 1793 if (const auto *BB = dyn_cast<BasicBlock>(V)) 1794 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 1795 1796 llvm_unreachable("Can't get register for value!"); 1797 } 1798 1799 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1800 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1801 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1802 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1803 bool IsSEH = isAsynchronousEHPersonality(Pers); 1804 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1805 if (!IsSEH) 1806 CatchPadMBB->setIsEHScopeEntry(); 1807 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1808 if (IsMSVCCXX || IsCoreCLR) 1809 CatchPadMBB->setIsEHFuncletEntry(); 1810 } 1811 1812 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1813 // Update machine-CFG edge. 1814 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1815 FuncInfo.MBB->addSuccessor(TargetMBB); 1816 TargetMBB->setIsEHCatchretTarget(true); 1817 DAG.getMachineFunction().setHasEHCatchret(true); 1818 1819 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1820 bool IsSEH = isAsynchronousEHPersonality(Pers); 1821 if (IsSEH) { 1822 // If this is not a fall-through branch or optimizations are switched off, 1823 // emit the branch. 1824 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1825 TM.getOptLevel() == CodeGenOpt::None) 1826 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1827 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1828 return; 1829 } 1830 1831 // Figure out the funclet membership for the catchret's successor. 1832 // This will be used by the FuncletLayout pass to determine how to order the 1833 // BB's. 1834 // A 'catchret' returns to the outer scope's color. 1835 Value *ParentPad = I.getCatchSwitchParentPad(); 1836 const BasicBlock *SuccessorColor; 1837 if (isa<ConstantTokenNone>(ParentPad)) 1838 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1839 else 1840 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1841 assert(SuccessorColor && "No parent funclet for catchret!"); 1842 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1843 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1844 1845 // Create the terminator node. 1846 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1847 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1848 DAG.getBasicBlock(SuccessorColorMBB)); 1849 DAG.setRoot(Ret); 1850 } 1851 1852 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1853 // Don't emit any special code for the cleanuppad instruction. It just marks 1854 // the start of an EH scope/funclet. 1855 FuncInfo.MBB->setIsEHScopeEntry(); 1856 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1857 if (Pers != EHPersonality::Wasm_CXX) { 1858 FuncInfo.MBB->setIsEHFuncletEntry(); 1859 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1860 } 1861 } 1862 1863 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1864 // not match, it is OK to add only the first unwind destination catchpad to the 1865 // successors, because there will be at least one invoke instruction within the 1866 // catch scope that points to the next unwind destination, if one exists, so 1867 // CFGSort cannot mess up with BB sorting order. 1868 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1869 // call within them, and catchpads only consisting of 'catch (...)' have a 1870 // '__cxa_end_catch' call within them, both of which generate invokes in case 1871 // the next unwind destination exists, i.e., the next unwind destination is not 1872 // the caller.) 1873 // 1874 // Having at most one EH pad successor is also simpler and helps later 1875 // transformations. 1876 // 1877 // For example, 1878 // current: 1879 // invoke void @foo to ... unwind label %catch.dispatch 1880 // catch.dispatch: 1881 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1882 // catch.start: 1883 // ... 1884 // ... in this BB or some other child BB dominated by this BB there will be an 1885 // invoke that points to 'next' BB as an unwind destination 1886 // 1887 // next: ; We don't need to add this to 'current' BB's successor 1888 // ... 1889 static void findWasmUnwindDestinations( 1890 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1891 BranchProbability Prob, 1892 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1893 &UnwindDests) { 1894 while (EHPadBB) { 1895 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1896 if (isa<CleanupPadInst>(Pad)) { 1897 // Stop on cleanup pads. 1898 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1899 UnwindDests.back().first->setIsEHScopeEntry(); 1900 break; 1901 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1902 // Add the catchpad handlers to the possible destinations. We don't 1903 // continue to the unwind destination of the catchswitch for wasm. 1904 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1905 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1906 UnwindDests.back().first->setIsEHScopeEntry(); 1907 } 1908 break; 1909 } else { 1910 continue; 1911 } 1912 } 1913 } 1914 1915 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1916 /// many places it could ultimately go. In the IR, we have a single unwind 1917 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1918 /// This function skips over imaginary basic blocks that hold catchswitch 1919 /// instructions, and finds all the "real" machine 1920 /// basic block destinations. As those destinations may not be successors of 1921 /// EHPadBB, here we also calculate the edge probability to those destinations. 1922 /// The passed-in Prob is the edge probability to EHPadBB. 1923 static void findUnwindDestinations( 1924 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1925 BranchProbability Prob, 1926 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1927 &UnwindDests) { 1928 EHPersonality Personality = 1929 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1930 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1931 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1932 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1933 bool IsSEH = isAsynchronousEHPersonality(Personality); 1934 1935 if (IsWasmCXX) { 1936 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1937 assert(UnwindDests.size() <= 1 && 1938 "There should be at most one unwind destination for wasm"); 1939 return; 1940 } 1941 1942 while (EHPadBB) { 1943 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1944 BasicBlock *NewEHPadBB = nullptr; 1945 if (isa<LandingPadInst>(Pad)) { 1946 // Stop on landingpads. They are not funclets. 1947 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1948 break; 1949 } else if (isa<CleanupPadInst>(Pad)) { 1950 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1951 // personalities. 1952 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1953 UnwindDests.back().first->setIsEHScopeEntry(); 1954 UnwindDests.back().first->setIsEHFuncletEntry(); 1955 break; 1956 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1957 // Add the catchpad handlers to the possible destinations. 1958 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1959 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1960 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1961 if (IsMSVCCXX || IsCoreCLR) 1962 UnwindDests.back().first->setIsEHFuncletEntry(); 1963 if (!IsSEH) 1964 UnwindDests.back().first->setIsEHScopeEntry(); 1965 } 1966 NewEHPadBB = CatchSwitch->getUnwindDest(); 1967 } else { 1968 continue; 1969 } 1970 1971 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1972 if (BPI && NewEHPadBB) 1973 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1974 EHPadBB = NewEHPadBB; 1975 } 1976 } 1977 1978 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1979 // Update successor info. 1980 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1981 auto UnwindDest = I.getUnwindDest(); 1982 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1983 BranchProbability UnwindDestProb = 1984 (BPI && UnwindDest) 1985 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1986 : BranchProbability::getZero(); 1987 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1988 for (auto &UnwindDest : UnwindDests) { 1989 UnwindDest.first->setIsEHPad(); 1990 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1991 } 1992 FuncInfo.MBB->normalizeSuccProbs(); 1993 1994 // Create the terminator node. 1995 SDValue Ret = 1996 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1997 DAG.setRoot(Ret); 1998 } 1999 2000 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 2001 report_fatal_error("visitCatchSwitch not yet implemented!"); 2002 } 2003 2004 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 2005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2006 auto &DL = DAG.getDataLayout(); 2007 SDValue Chain = getControlRoot(); 2008 SmallVector<ISD::OutputArg, 8> Outs; 2009 SmallVector<SDValue, 8> OutVals; 2010 2011 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 2012 // lower 2013 // 2014 // %val = call <ty> @llvm.experimental.deoptimize() 2015 // ret <ty> %val 2016 // 2017 // differently. 2018 if (I.getParent()->getTerminatingDeoptimizeCall()) { 2019 LowerDeoptimizingReturn(); 2020 return; 2021 } 2022 2023 if (!FuncInfo.CanLowerReturn) { 2024 unsigned DemoteReg = FuncInfo.DemoteRegister; 2025 const Function *F = I.getParent()->getParent(); 2026 2027 // Emit a store of the return value through the virtual register. 2028 // Leave Outs empty so that LowerReturn won't try to load return 2029 // registers the usual way. 2030 SmallVector<EVT, 1> PtrValueVTs; 2031 ComputeValueVTs(TLI, DL, 2032 F->getReturnType()->getPointerTo( 2033 DAG.getDataLayout().getAllocaAddrSpace()), 2034 PtrValueVTs); 2035 2036 SDValue RetPtr = 2037 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]); 2038 SDValue RetOp = getValue(I.getOperand(0)); 2039 2040 SmallVector<EVT, 4> ValueVTs, MemVTs; 2041 SmallVector<uint64_t, 4> Offsets; 2042 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 2043 &Offsets, 0); 2044 unsigned NumValues = ValueVTs.size(); 2045 2046 SmallVector<SDValue, 4> Chains(NumValues); 2047 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 2048 for (unsigned i = 0; i != NumValues; ++i) { 2049 // An aggregate return value cannot wrap around the address space, so 2050 // offsets to its parts don't wrap either. 2051 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 2052 TypeSize::Fixed(Offsets[i])); 2053 2054 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 2055 if (MemVTs[i] != ValueVTs[i]) 2056 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 2057 Chains[i] = DAG.getStore( 2058 Chain, getCurSDLoc(), Val, 2059 // FIXME: better loc info would be nice. 2060 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 2061 commonAlignment(BaseAlign, Offsets[i])); 2062 } 2063 2064 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 2065 MVT::Other, Chains); 2066 } else if (I.getNumOperands() != 0) { 2067 SmallVector<EVT, 4> ValueVTs; 2068 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 2069 unsigned NumValues = ValueVTs.size(); 2070 if (NumValues) { 2071 SDValue RetOp = getValue(I.getOperand(0)); 2072 2073 const Function *F = I.getParent()->getParent(); 2074 2075 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 2076 I.getOperand(0)->getType(), F->getCallingConv(), 2077 /*IsVarArg*/ false, DL); 2078 2079 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 2080 if (F->getAttributes().hasRetAttr(Attribute::SExt)) 2081 ExtendKind = ISD::SIGN_EXTEND; 2082 else if (F->getAttributes().hasRetAttr(Attribute::ZExt)) 2083 ExtendKind = ISD::ZERO_EXTEND; 2084 2085 LLVMContext &Context = F->getContext(); 2086 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg); 2087 2088 for (unsigned j = 0; j != NumValues; ++j) { 2089 EVT VT = ValueVTs[j]; 2090 2091 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 2092 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 2093 2094 CallingConv::ID CC = F->getCallingConv(); 2095 2096 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 2097 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 2098 SmallVector<SDValue, 4> Parts(NumParts); 2099 getCopyToParts(DAG, getCurSDLoc(), 2100 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 2101 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 2102 2103 // 'inreg' on function refers to return value 2104 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2105 if (RetInReg) 2106 Flags.setInReg(); 2107 2108 if (I.getOperand(0)->getType()->isPointerTy()) { 2109 Flags.setPointer(); 2110 Flags.setPointerAddrSpace( 2111 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 2112 } 2113 2114 if (NeedsRegBlock) { 2115 Flags.setInConsecutiveRegs(); 2116 if (j == NumValues - 1) 2117 Flags.setInConsecutiveRegsLast(); 2118 } 2119 2120 // Propagate extension type if any 2121 if (ExtendKind == ISD::SIGN_EXTEND) 2122 Flags.setSExt(); 2123 else if (ExtendKind == ISD::ZERO_EXTEND) 2124 Flags.setZExt(); 2125 2126 for (unsigned i = 0; i < NumParts; ++i) { 2127 Outs.push_back(ISD::OutputArg(Flags, 2128 Parts[i].getValueType().getSimpleVT(), 2129 VT, /*isfixed=*/true, 0, 0)); 2130 OutVals.push_back(Parts[i]); 2131 } 2132 } 2133 } 2134 } 2135 2136 // Push in swifterror virtual register as the last element of Outs. This makes 2137 // sure swifterror virtual register will be returned in the swifterror 2138 // physical register. 2139 const Function *F = I.getParent()->getParent(); 2140 if (TLI.supportSwiftError() && 2141 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 2142 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 2143 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 2144 Flags.setSwiftError(); 2145 Outs.push_back(ISD::OutputArg( 2146 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)), 2147 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0)); 2148 // Create SDNode for the swifterror virtual register. 2149 OutVals.push_back( 2150 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 2151 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 2152 EVT(TLI.getPointerTy(DL)))); 2153 } 2154 2155 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 2156 CallingConv::ID CallConv = 2157 DAG.getMachineFunction().getFunction().getCallingConv(); 2158 Chain = DAG.getTargetLoweringInfo().LowerReturn( 2159 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 2160 2161 // Verify that the target's LowerReturn behaved as expected. 2162 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 2163 "LowerReturn didn't return a valid chain!"); 2164 2165 // Update the DAG with the new chain value resulting from return lowering. 2166 DAG.setRoot(Chain); 2167 } 2168 2169 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 2170 /// created for it, emit nodes to copy the value into the virtual 2171 /// registers. 2172 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 2173 // Skip empty types 2174 if (V->getType()->isEmptyTy()) 2175 return; 2176 2177 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 2178 if (VMI != FuncInfo.ValueMap.end()) { 2179 assert((!V->use_empty() || isa<CallBrInst>(V)) && 2180 "Unused value assigned virtual registers!"); 2181 CopyValueToVirtualRegister(V, VMI->second); 2182 } 2183 } 2184 2185 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2186 /// the current basic block, add it to ValueMap now so that we'll get a 2187 /// CopyTo/FromReg. 2188 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2189 // No need to export constants. 2190 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2191 2192 // Already exported? 2193 if (FuncInfo.isExportedInst(V)) return; 2194 2195 Register Reg = FuncInfo.InitializeRegForValue(V); 2196 CopyValueToVirtualRegister(V, Reg); 2197 } 2198 2199 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2200 const BasicBlock *FromBB) { 2201 // The operands of the setcc have to be in this block. We don't know 2202 // how to export them from some other block. 2203 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2204 // Can export from current BB. 2205 if (VI->getParent() == FromBB) 2206 return true; 2207 2208 // Is already exported, noop. 2209 return FuncInfo.isExportedInst(V); 2210 } 2211 2212 // If this is an argument, we can export it if the BB is the entry block or 2213 // if it is already exported. 2214 if (isa<Argument>(V)) { 2215 if (FromBB->isEntryBlock()) 2216 return true; 2217 2218 // Otherwise, can only export this if it is already exported. 2219 return FuncInfo.isExportedInst(V); 2220 } 2221 2222 // Otherwise, constants can always be exported. 2223 return true; 2224 } 2225 2226 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2227 BranchProbability 2228 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2229 const MachineBasicBlock *Dst) const { 2230 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2231 const BasicBlock *SrcBB = Src->getBasicBlock(); 2232 const BasicBlock *DstBB = Dst->getBasicBlock(); 2233 if (!BPI) { 2234 // If BPI is not available, set the default probability as 1 / N, where N is 2235 // the number of successors. 2236 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2237 return BranchProbability(1, SuccSize); 2238 } 2239 return BPI->getEdgeProbability(SrcBB, DstBB); 2240 } 2241 2242 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2243 MachineBasicBlock *Dst, 2244 BranchProbability Prob) { 2245 if (!FuncInfo.BPI) 2246 Src->addSuccessorWithoutProb(Dst); 2247 else { 2248 if (Prob.isUnknown()) 2249 Prob = getEdgeProbability(Src, Dst); 2250 Src->addSuccessor(Dst, Prob); 2251 } 2252 } 2253 2254 static bool InBlock(const Value *V, const BasicBlock *BB) { 2255 if (const Instruction *I = dyn_cast<Instruction>(V)) 2256 return I->getParent() == BB; 2257 return true; 2258 } 2259 2260 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2261 /// This function emits a branch and is used at the leaves of an OR or an 2262 /// AND operator tree. 2263 void 2264 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2265 MachineBasicBlock *TBB, 2266 MachineBasicBlock *FBB, 2267 MachineBasicBlock *CurBB, 2268 MachineBasicBlock *SwitchBB, 2269 BranchProbability TProb, 2270 BranchProbability FProb, 2271 bool InvertCond) { 2272 const BasicBlock *BB = CurBB->getBasicBlock(); 2273 2274 // If the leaf of the tree is a comparison, merge the condition into 2275 // the caseblock. 2276 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2277 // The operands of the cmp have to be in this block. We don't know 2278 // how to export them from some other block. If this is the first block 2279 // of the sequence, no exporting is needed. 2280 if (CurBB == SwitchBB || 2281 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2282 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2283 ISD::CondCode Condition; 2284 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2285 ICmpInst::Predicate Pred = 2286 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2287 Condition = getICmpCondCode(Pred); 2288 } else { 2289 const FCmpInst *FC = cast<FCmpInst>(Cond); 2290 FCmpInst::Predicate Pred = 2291 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2292 Condition = getFCmpCondCode(Pred); 2293 if (TM.Options.NoNaNsFPMath) 2294 Condition = getFCmpCodeWithoutNaN(Condition); 2295 } 2296 2297 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2298 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2299 SL->SwitchCases.push_back(CB); 2300 return; 2301 } 2302 } 2303 2304 // Create a CaseBlock record representing this branch. 2305 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2306 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2307 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2308 SL->SwitchCases.push_back(CB); 2309 } 2310 2311 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2312 MachineBasicBlock *TBB, 2313 MachineBasicBlock *FBB, 2314 MachineBasicBlock *CurBB, 2315 MachineBasicBlock *SwitchBB, 2316 Instruction::BinaryOps Opc, 2317 BranchProbability TProb, 2318 BranchProbability FProb, 2319 bool InvertCond) { 2320 // Skip over not part of the tree and remember to invert op and operands at 2321 // next level. 2322 Value *NotCond; 2323 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2324 InBlock(NotCond, CurBB->getBasicBlock())) { 2325 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2326 !InvertCond); 2327 return; 2328 } 2329 2330 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2331 const Value *BOpOp0, *BOpOp1; 2332 // Compute the effective opcode for Cond, taking into account whether it needs 2333 // to be inverted, e.g. 2334 // and (not (or A, B)), C 2335 // gets lowered as 2336 // and (and (not A, not B), C) 2337 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2338 if (BOp) { 2339 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2340 ? Instruction::And 2341 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2342 ? Instruction::Or 2343 : (Instruction::BinaryOps)0); 2344 if (InvertCond) { 2345 if (BOpc == Instruction::And) 2346 BOpc = Instruction::Or; 2347 else if (BOpc == Instruction::Or) 2348 BOpc = Instruction::And; 2349 } 2350 } 2351 2352 // If this node is not part of the or/and tree, emit it as a branch. 2353 // Note that all nodes in the tree should have same opcode. 2354 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2355 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2356 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2357 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2358 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2359 TProb, FProb, InvertCond); 2360 return; 2361 } 2362 2363 // Create TmpBB after CurBB. 2364 MachineFunction::iterator BBI(CurBB); 2365 MachineFunction &MF = DAG.getMachineFunction(); 2366 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2367 CurBB->getParent()->insert(++BBI, TmpBB); 2368 2369 if (Opc == Instruction::Or) { 2370 // Codegen X | Y as: 2371 // BB1: 2372 // jmp_if_X TBB 2373 // jmp TmpBB 2374 // TmpBB: 2375 // jmp_if_Y TBB 2376 // jmp FBB 2377 // 2378 2379 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2380 // The requirement is that 2381 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2382 // = TrueProb for original BB. 2383 // Assuming the original probabilities are A and B, one choice is to set 2384 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2385 // A/(1+B) and 2B/(1+B). This choice assumes that 2386 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2387 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2388 // TmpBB, but the math is more complicated. 2389 2390 auto NewTrueProb = TProb / 2; 2391 auto NewFalseProb = TProb / 2 + FProb; 2392 // Emit the LHS condition. 2393 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2394 NewFalseProb, InvertCond); 2395 2396 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2397 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2398 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2399 // Emit the RHS condition into TmpBB. 2400 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2401 Probs[1], InvertCond); 2402 } else { 2403 assert(Opc == Instruction::And && "Unknown merge op!"); 2404 // Codegen X & Y as: 2405 // BB1: 2406 // jmp_if_X TmpBB 2407 // jmp FBB 2408 // TmpBB: 2409 // jmp_if_Y TBB 2410 // jmp FBB 2411 // 2412 // This requires creation of TmpBB after CurBB. 2413 2414 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2415 // The requirement is that 2416 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2417 // = FalseProb for original BB. 2418 // Assuming the original probabilities are A and B, one choice is to set 2419 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2420 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2421 // TrueProb for BB1 * FalseProb for TmpBB. 2422 2423 auto NewTrueProb = TProb + FProb / 2; 2424 auto NewFalseProb = FProb / 2; 2425 // Emit the LHS condition. 2426 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2427 NewFalseProb, InvertCond); 2428 2429 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2430 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2431 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2432 // Emit the RHS condition into TmpBB. 2433 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2434 Probs[1], InvertCond); 2435 } 2436 } 2437 2438 /// If the set of cases should be emitted as a series of branches, return true. 2439 /// If we should emit this as a bunch of and/or'd together conditions, return 2440 /// false. 2441 bool 2442 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2443 if (Cases.size() != 2) return true; 2444 2445 // If this is two comparisons of the same values or'd or and'd together, they 2446 // will get folded into a single comparison, so don't emit two blocks. 2447 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2448 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2449 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2450 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2451 return false; 2452 } 2453 2454 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2455 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2456 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2457 Cases[0].CC == Cases[1].CC && 2458 isa<Constant>(Cases[0].CmpRHS) && 2459 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2460 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2461 return false; 2462 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2463 return false; 2464 } 2465 2466 return true; 2467 } 2468 2469 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2470 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2471 2472 // Update machine-CFG edges. 2473 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2474 2475 if (I.isUnconditional()) { 2476 // Update machine-CFG edges. 2477 BrMBB->addSuccessor(Succ0MBB); 2478 2479 // If this is not a fall-through branch or optimizations are switched off, 2480 // emit the branch. 2481 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2482 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2483 MVT::Other, getControlRoot(), 2484 DAG.getBasicBlock(Succ0MBB))); 2485 2486 return; 2487 } 2488 2489 // If this condition is one of the special cases we handle, do special stuff 2490 // now. 2491 const Value *CondVal = I.getCondition(); 2492 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2493 2494 // If this is a series of conditions that are or'd or and'd together, emit 2495 // this as a sequence of branches instead of setcc's with and/or operations. 2496 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2497 // unpredictable branches, and vector extracts because those jumps are likely 2498 // expensive for any target), this should improve performance. 2499 // For example, instead of something like: 2500 // cmp A, B 2501 // C = seteq 2502 // cmp D, E 2503 // F = setle 2504 // or C, F 2505 // jnz foo 2506 // Emit: 2507 // cmp A, B 2508 // je foo 2509 // cmp D, E 2510 // jle foo 2511 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2512 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2513 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2514 Value *Vec; 2515 const Value *BOp0, *BOp1; 2516 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2517 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2518 Opcode = Instruction::And; 2519 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2520 Opcode = Instruction::Or; 2521 2522 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2523 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2524 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2525 getEdgeProbability(BrMBB, Succ0MBB), 2526 getEdgeProbability(BrMBB, Succ1MBB), 2527 /*InvertCond=*/false); 2528 // If the compares in later blocks need to use values not currently 2529 // exported from this block, export them now. This block should always 2530 // be the first entry. 2531 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2532 2533 // Allow some cases to be rejected. 2534 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2535 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2536 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2537 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2538 } 2539 2540 // Emit the branch for this block. 2541 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2542 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2543 return; 2544 } 2545 2546 // Okay, we decided not to do this, remove any inserted MBB's and clear 2547 // SwitchCases. 2548 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2549 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2550 2551 SL->SwitchCases.clear(); 2552 } 2553 } 2554 2555 // Create a CaseBlock record representing this branch. 2556 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2557 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2558 2559 // Use visitSwitchCase to actually insert the fast branch sequence for this 2560 // cond branch. 2561 visitSwitchCase(CB, BrMBB); 2562 } 2563 2564 /// visitSwitchCase - Emits the necessary code to represent a single node in 2565 /// the binary search tree resulting from lowering a switch instruction. 2566 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2567 MachineBasicBlock *SwitchBB) { 2568 SDValue Cond; 2569 SDValue CondLHS = getValue(CB.CmpLHS); 2570 SDLoc dl = CB.DL; 2571 2572 if (CB.CC == ISD::SETTRUE) { 2573 // Branch or fall through to TrueBB. 2574 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2575 SwitchBB->normalizeSuccProbs(); 2576 if (CB.TrueBB != NextBlock(SwitchBB)) { 2577 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2578 DAG.getBasicBlock(CB.TrueBB))); 2579 } 2580 return; 2581 } 2582 2583 auto &TLI = DAG.getTargetLoweringInfo(); 2584 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2585 2586 // Build the setcc now. 2587 if (!CB.CmpMHS) { 2588 // Fold "(X == true)" to X and "(X == false)" to !X to 2589 // handle common cases produced by branch lowering. 2590 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2591 CB.CC == ISD::SETEQ) 2592 Cond = CondLHS; 2593 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2594 CB.CC == ISD::SETEQ) { 2595 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2596 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2597 } else { 2598 SDValue CondRHS = getValue(CB.CmpRHS); 2599 2600 // If a pointer's DAG type is larger than its memory type then the DAG 2601 // values are zero-extended. This breaks signed comparisons so truncate 2602 // back to the underlying type before doing the compare. 2603 if (CondLHS.getValueType() != MemVT) { 2604 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2605 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2606 } 2607 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2608 } 2609 } else { 2610 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2611 2612 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2613 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2614 2615 SDValue CmpOp = getValue(CB.CmpMHS); 2616 EVT VT = CmpOp.getValueType(); 2617 2618 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2619 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2620 ISD::SETLE); 2621 } else { 2622 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2623 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2624 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2625 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2626 } 2627 } 2628 2629 // Update successor info 2630 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2631 // TrueBB and FalseBB are always different unless the incoming IR is 2632 // degenerate. This only happens when running llc on weird IR. 2633 if (CB.TrueBB != CB.FalseBB) 2634 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2635 SwitchBB->normalizeSuccProbs(); 2636 2637 // If the lhs block is the next block, invert the condition so that we can 2638 // fall through to the lhs instead of the rhs block. 2639 if (CB.TrueBB == NextBlock(SwitchBB)) { 2640 std::swap(CB.TrueBB, CB.FalseBB); 2641 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2642 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2643 } 2644 2645 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2646 MVT::Other, getControlRoot(), Cond, 2647 DAG.getBasicBlock(CB.TrueBB)); 2648 2649 setValue(CurInst, BrCond); 2650 2651 // Insert the false branch. Do this even if it's a fall through branch, 2652 // this makes it easier to do DAG optimizations which require inverting 2653 // the branch condition. 2654 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2655 DAG.getBasicBlock(CB.FalseBB)); 2656 2657 DAG.setRoot(BrCond); 2658 } 2659 2660 /// visitJumpTable - Emit JumpTable node in the current MBB 2661 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2662 // Emit the code for the jump table 2663 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2664 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2665 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2666 JT.Reg, PTy); 2667 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2668 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2669 MVT::Other, Index.getValue(1), 2670 Table, Index); 2671 DAG.setRoot(BrJumpTable); 2672 } 2673 2674 /// visitJumpTableHeader - This function emits necessary code to produce index 2675 /// in the JumpTable from switch case. 2676 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2677 JumpTableHeader &JTH, 2678 MachineBasicBlock *SwitchBB) { 2679 SDLoc dl = getCurSDLoc(); 2680 2681 // Subtract the lowest switch case value from the value being switched on. 2682 SDValue SwitchOp = getValue(JTH.SValue); 2683 EVT VT = SwitchOp.getValueType(); 2684 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2685 DAG.getConstant(JTH.First, dl, VT)); 2686 2687 // The SDNode we just created, which holds the value being switched on minus 2688 // the smallest case value, needs to be copied to a virtual register so it 2689 // can be used as an index into the jump table in a subsequent basic block. 2690 // This value may be smaller or larger than the target's pointer type, and 2691 // therefore require extension or truncating. 2692 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2693 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2694 2695 unsigned JumpTableReg = 2696 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2697 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2698 JumpTableReg, SwitchOp); 2699 JT.Reg = JumpTableReg; 2700 2701 if (!JTH.FallthroughUnreachable) { 2702 // Emit the range check for the jump table, and branch to the default block 2703 // for the switch statement if the value being switched on exceeds the 2704 // largest case in the switch. 2705 SDValue CMP = DAG.getSetCC( 2706 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2707 Sub.getValueType()), 2708 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2709 2710 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2711 MVT::Other, CopyTo, CMP, 2712 DAG.getBasicBlock(JT.Default)); 2713 2714 // Avoid emitting unnecessary branches to the next block. 2715 if (JT.MBB != NextBlock(SwitchBB)) 2716 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2717 DAG.getBasicBlock(JT.MBB)); 2718 2719 DAG.setRoot(BrCond); 2720 } else { 2721 // Avoid emitting unnecessary branches to the next block. 2722 if (JT.MBB != NextBlock(SwitchBB)) 2723 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2724 DAG.getBasicBlock(JT.MBB))); 2725 else 2726 DAG.setRoot(CopyTo); 2727 } 2728 } 2729 2730 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2731 /// variable if there exists one. 2732 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2733 SDValue &Chain) { 2734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2735 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2736 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2737 MachineFunction &MF = DAG.getMachineFunction(); 2738 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2739 MachineSDNode *Node = 2740 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2741 if (Global) { 2742 MachinePointerInfo MPInfo(Global); 2743 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2744 MachineMemOperand::MODereferenceable; 2745 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2746 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2747 DAG.setNodeMemRefs(Node, {MemRef}); 2748 } 2749 if (PtrTy != PtrMemTy) 2750 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2751 return SDValue(Node, 0); 2752 } 2753 2754 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2755 /// tail spliced into a stack protector check success bb. 2756 /// 2757 /// For a high level explanation of how this fits into the stack protector 2758 /// generation see the comment on the declaration of class 2759 /// StackProtectorDescriptor. 2760 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2761 MachineBasicBlock *ParentBB) { 2762 2763 // First create the loads to the guard/stack slot for the comparison. 2764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2765 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2766 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2767 2768 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2769 int FI = MFI.getStackProtectorIndex(); 2770 2771 SDValue Guard; 2772 SDLoc dl = getCurSDLoc(); 2773 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2774 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2775 Align Align = 2776 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2777 2778 // Generate code to load the content of the guard slot. 2779 SDValue GuardVal = DAG.getLoad( 2780 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2781 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2782 MachineMemOperand::MOVolatile); 2783 2784 if (TLI.useStackGuardXorFP()) 2785 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2786 2787 // Retrieve guard check function, nullptr if instrumentation is inlined. 2788 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2789 // The target provides a guard check function to validate the guard value. 2790 // Generate a call to that function with the content of the guard slot as 2791 // argument. 2792 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2793 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2794 2795 TargetLowering::ArgListTy Args; 2796 TargetLowering::ArgListEntry Entry; 2797 Entry.Node = GuardVal; 2798 Entry.Ty = FnTy->getParamType(0); 2799 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg)) 2800 Entry.IsInReg = true; 2801 Args.push_back(Entry); 2802 2803 TargetLowering::CallLoweringInfo CLI(DAG); 2804 CLI.setDebugLoc(getCurSDLoc()) 2805 .setChain(DAG.getEntryNode()) 2806 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2807 getValue(GuardCheckFn), std::move(Args)); 2808 2809 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2810 DAG.setRoot(Result.second); 2811 return; 2812 } 2813 2814 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2815 // Otherwise, emit a volatile load to retrieve the stack guard value. 2816 SDValue Chain = DAG.getEntryNode(); 2817 if (TLI.useLoadStackGuardNode()) { 2818 Guard = getLoadStackGuard(DAG, dl, Chain); 2819 } else { 2820 const Value *IRGuard = TLI.getSDagStackGuard(M); 2821 SDValue GuardPtr = getValue(IRGuard); 2822 2823 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2824 MachinePointerInfo(IRGuard, 0), Align, 2825 MachineMemOperand::MOVolatile); 2826 } 2827 2828 // Perform the comparison via a getsetcc. 2829 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2830 *DAG.getContext(), 2831 Guard.getValueType()), 2832 Guard, GuardVal, ISD::SETNE); 2833 2834 // If the guard/stackslot do not equal, branch to failure MBB. 2835 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2836 MVT::Other, GuardVal.getOperand(0), 2837 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2838 // Otherwise branch to success MBB. 2839 SDValue Br = DAG.getNode(ISD::BR, dl, 2840 MVT::Other, BrCond, 2841 DAG.getBasicBlock(SPD.getSuccessMBB())); 2842 2843 DAG.setRoot(Br); 2844 } 2845 2846 /// Codegen the failure basic block for a stack protector check. 2847 /// 2848 /// A failure stack protector machine basic block consists simply of a call to 2849 /// __stack_chk_fail(). 2850 /// 2851 /// For a high level explanation of how this fits into the stack protector 2852 /// generation see the comment on the declaration of class 2853 /// StackProtectorDescriptor. 2854 void 2855 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2856 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2857 TargetLowering::MakeLibCallOptions CallOptions; 2858 CallOptions.setDiscardResult(true); 2859 SDValue Chain = 2860 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2861 std::nullopt, CallOptions, getCurSDLoc()) 2862 .second; 2863 // On PS4/PS5, the "return address" must still be within the calling 2864 // function, even if it's at the very end, so emit an explicit TRAP here. 2865 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2866 if (TM.getTargetTriple().isPS()) 2867 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2868 // WebAssembly needs an unreachable instruction after a non-returning call, 2869 // because the function return type can be different from __stack_chk_fail's 2870 // return type (void). 2871 if (TM.getTargetTriple().isWasm()) 2872 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2873 2874 DAG.setRoot(Chain); 2875 } 2876 2877 /// visitBitTestHeader - This function emits necessary code to produce value 2878 /// suitable for "bit tests" 2879 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2880 MachineBasicBlock *SwitchBB) { 2881 SDLoc dl = getCurSDLoc(); 2882 2883 // Subtract the minimum value. 2884 SDValue SwitchOp = getValue(B.SValue); 2885 EVT VT = SwitchOp.getValueType(); 2886 SDValue RangeSub = 2887 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2888 2889 // Determine the type of the test operands. 2890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2891 bool UsePtrType = false; 2892 if (!TLI.isTypeLegal(VT)) { 2893 UsePtrType = true; 2894 } else { 2895 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2896 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2897 // Switch table case range are encoded into series of masks. 2898 // Just use pointer type, it's guaranteed to fit. 2899 UsePtrType = true; 2900 break; 2901 } 2902 } 2903 SDValue Sub = RangeSub; 2904 if (UsePtrType) { 2905 VT = TLI.getPointerTy(DAG.getDataLayout()); 2906 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2907 } 2908 2909 B.RegVT = VT.getSimpleVT(); 2910 B.Reg = FuncInfo.CreateReg(B.RegVT); 2911 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2912 2913 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2914 2915 if (!B.FallthroughUnreachable) 2916 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2917 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2918 SwitchBB->normalizeSuccProbs(); 2919 2920 SDValue Root = CopyTo; 2921 if (!B.FallthroughUnreachable) { 2922 // Conditional branch to the default block. 2923 SDValue RangeCmp = DAG.getSetCC(dl, 2924 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2925 RangeSub.getValueType()), 2926 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2927 ISD::SETUGT); 2928 2929 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2930 DAG.getBasicBlock(B.Default)); 2931 } 2932 2933 // Avoid emitting unnecessary branches to the next block. 2934 if (MBB != NextBlock(SwitchBB)) 2935 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2936 2937 DAG.setRoot(Root); 2938 } 2939 2940 /// visitBitTestCase - this function produces one "bit test" 2941 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2942 MachineBasicBlock* NextMBB, 2943 BranchProbability BranchProbToNext, 2944 unsigned Reg, 2945 BitTestCase &B, 2946 MachineBasicBlock *SwitchBB) { 2947 SDLoc dl = getCurSDLoc(); 2948 MVT VT = BB.RegVT; 2949 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2950 SDValue Cmp; 2951 unsigned PopCount = llvm::popcount(B.Mask); 2952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2953 if (PopCount == 1) { 2954 // Testing for a single bit; just compare the shift count with what it 2955 // would need to be to shift a 1 bit in that position. 2956 Cmp = DAG.getSetCC( 2957 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2958 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT), 2959 ISD::SETEQ); 2960 } else if (PopCount == BB.Range) { 2961 // There is only one zero bit in the range, test for it directly. 2962 Cmp = DAG.getSetCC( 2963 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2964 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE); 2965 } else { 2966 // Make desired shift 2967 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2968 DAG.getConstant(1, dl, VT), ShiftOp); 2969 2970 // Emit bit tests and jumps 2971 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2972 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2973 Cmp = DAG.getSetCC( 2974 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2975 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2976 } 2977 2978 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2979 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2980 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2981 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2982 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2983 // one as they are relative probabilities (and thus work more like weights), 2984 // and hence we need to normalize them to let the sum of them become one. 2985 SwitchBB->normalizeSuccProbs(); 2986 2987 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2988 MVT::Other, getControlRoot(), 2989 Cmp, DAG.getBasicBlock(B.TargetBB)); 2990 2991 // Avoid emitting unnecessary branches to the next block. 2992 if (NextMBB != NextBlock(SwitchBB)) 2993 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2994 DAG.getBasicBlock(NextMBB)); 2995 2996 DAG.setRoot(BrAnd); 2997 } 2998 2999 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 3000 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 3001 3002 // Retrieve successors. Look through artificial IR level blocks like 3003 // catchswitch for successors. 3004 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 3005 const BasicBlock *EHPadBB = I.getSuccessor(1); 3006 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB]; 3007 3008 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3009 // have to do anything here to lower funclet bundles. 3010 assert(!I.hasOperandBundlesOtherThan( 3011 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, 3012 LLVMContext::OB_gc_live, LLVMContext::OB_funclet, 3013 LLVMContext::OB_cfguardtarget, 3014 LLVMContext::OB_clang_arc_attachedcall}) && 3015 "Cannot lower invokes with arbitrary operand bundles yet!"); 3016 3017 const Value *Callee(I.getCalledOperand()); 3018 const Function *Fn = dyn_cast<Function>(Callee); 3019 if (isa<InlineAsm>(Callee)) 3020 visitInlineAsm(I, EHPadBB); 3021 else if (Fn && Fn->isIntrinsic()) { 3022 switch (Fn->getIntrinsicID()) { 3023 default: 3024 llvm_unreachable("Cannot invoke this intrinsic"); 3025 case Intrinsic::donothing: 3026 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 3027 case Intrinsic::seh_try_begin: 3028 case Intrinsic::seh_scope_begin: 3029 case Intrinsic::seh_try_end: 3030 case Intrinsic::seh_scope_end: 3031 if (EHPadMBB) 3032 // a block referenced by EH table 3033 // so dtor-funclet not removed by opts 3034 EHPadMBB->setMachineBlockAddressTaken(); 3035 break; 3036 case Intrinsic::experimental_patchpoint_void: 3037 case Intrinsic::experimental_patchpoint_i64: 3038 visitPatchpoint(I, EHPadBB); 3039 break; 3040 case Intrinsic::experimental_gc_statepoint: 3041 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 3042 break; 3043 case Intrinsic::wasm_rethrow: { 3044 // This is usually done in visitTargetIntrinsic, but this intrinsic is 3045 // special because it can be invoked, so we manually lower it to a DAG 3046 // node here. 3047 SmallVector<SDValue, 8> Ops; 3048 Ops.push_back(getRoot()); // inchain 3049 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3050 Ops.push_back( 3051 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 3052 TLI.getPointerTy(DAG.getDataLayout()))); 3053 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 3054 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 3055 break; 3056 } 3057 } 3058 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 3059 // Currently we do not lower any intrinsic calls with deopt operand bundles. 3060 // Eventually we will support lowering the @llvm.experimental.deoptimize 3061 // intrinsic, and right now there are no plans to support other intrinsics 3062 // with deopt state. 3063 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 3064 } else { 3065 LowerCallTo(I, getValue(Callee), false, false, EHPadBB); 3066 } 3067 3068 // If the value of the invoke is used outside of its defining block, make it 3069 // available as a virtual register. 3070 // We already took care of the exported value for the statepoint instruction 3071 // during call to the LowerStatepoint. 3072 if (!isa<GCStatepointInst>(I)) { 3073 CopyToExportRegsIfNeeded(&I); 3074 } 3075 3076 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 3077 BranchProbabilityInfo *BPI = FuncInfo.BPI; 3078 BranchProbability EHPadBBProb = 3079 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 3080 : BranchProbability::getZero(); 3081 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 3082 3083 // Update successor info. 3084 addSuccessorWithProb(InvokeMBB, Return); 3085 for (auto &UnwindDest : UnwindDests) { 3086 UnwindDest.first->setIsEHPad(); 3087 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 3088 } 3089 InvokeMBB->normalizeSuccProbs(); 3090 3091 // Drop into normal successor. 3092 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 3093 DAG.getBasicBlock(Return))); 3094 } 3095 3096 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 3097 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 3098 3099 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 3100 // have to do anything here to lower funclet bundles. 3101 assert(!I.hasOperandBundlesOtherThan( 3102 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 3103 "Cannot lower callbrs with arbitrary operand bundles yet!"); 3104 3105 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 3106 visitInlineAsm(I); 3107 CopyToExportRegsIfNeeded(&I); 3108 3109 // Retrieve successors. 3110 SmallPtrSet<BasicBlock *, 8> Dests; 3111 Dests.insert(I.getDefaultDest()); 3112 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 3113 3114 // Update successor info. 3115 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 3116 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 3117 BasicBlock *Dest = I.getIndirectDest(i); 3118 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest]; 3119 Target->setIsInlineAsmBrIndirectTarget(); 3120 Target->setMachineBlockAddressTaken(); 3121 Target->setLabelMustBeEmitted(); 3122 // Don't add duplicate machine successors. 3123 if (Dests.insert(Dest).second) 3124 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 3125 } 3126 CallBrMBB->normalizeSuccProbs(); 3127 3128 // Drop into default successor. 3129 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 3130 MVT::Other, getControlRoot(), 3131 DAG.getBasicBlock(Return))); 3132 } 3133 3134 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 3135 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 3136 } 3137 3138 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 3139 assert(FuncInfo.MBB->isEHPad() && 3140 "Call to landingpad not in landing pad!"); 3141 3142 // If there aren't registers to copy the values into (e.g., during SjLj 3143 // exceptions), then don't bother to create these DAG nodes. 3144 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3145 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 3146 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 3147 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 3148 return; 3149 3150 // If landingpad's return type is token type, we don't create DAG nodes 3151 // for its exception pointer and selector value. The extraction of exception 3152 // pointer or selector value from token type landingpads is not currently 3153 // supported. 3154 if (LP.getType()->isTokenTy()) 3155 return; 3156 3157 SmallVector<EVT, 2> ValueVTs; 3158 SDLoc dl = getCurSDLoc(); 3159 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 3160 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 3161 3162 // Get the two live-in registers as SDValues. The physregs have already been 3163 // copied into virtual registers. 3164 SDValue Ops[2]; 3165 if (FuncInfo.ExceptionPointerVirtReg) { 3166 Ops[0] = DAG.getZExtOrTrunc( 3167 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3168 FuncInfo.ExceptionPointerVirtReg, 3169 TLI.getPointerTy(DAG.getDataLayout())), 3170 dl, ValueVTs[0]); 3171 } else { 3172 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 3173 } 3174 Ops[1] = DAG.getZExtOrTrunc( 3175 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 3176 FuncInfo.ExceptionSelectorVirtReg, 3177 TLI.getPointerTy(DAG.getDataLayout())), 3178 dl, ValueVTs[1]); 3179 3180 // Merge into one. 3181 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 3182 DAG.getVTList(ValueVTs), Ops); 3183 setValue(&LP, Res); 3184 } 3185 3186 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 3187 MachineBasicBlock *Last) { 3188 // Update JTCases. 3189 for (JumpTableBlock &JTB : SL->JTCases) 3190 if (JTB.first.HeaderBB == First) 3191 JTB.first.HeaderBB = Last; 3192 3193 // Update BitTestCases. 3194 for (BitTestBlock &BTB : SL->BitTestCases) 3195 if (BTB.Parent == First) 3196 BTB.Parent = Last; 3197 } 3198 3199 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 3200 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 3201 3202 // Update machine-CFG edges with unique successors. 3203 SmallSet<BasicBlock*, 32> Done; 3204 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 3205 BasicBlock *BB = I.getSuccessor(i); 3206 bool Inserted = Done.insert(BB).second; 3207 if (!Inserted) 3208 continue; 3209 3210 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 3211 addSuccessorWithProb(IndirectBrMBB, Succ); 3212 } 3213 IndirectBrMBB->normalizeSuccProbs(); 3214 3215 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 3216 MVT::Other, getControlRoot(), 3217 getValue(I.getAddress()))); 3218 } 3219 3220 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3221 if (!DAG.getTarget().Options.TrapUnreachable) 3222 return; 3223 3224 // We may be able to ignore unreachable behind a noreturn call. 3225 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3226 const BasicBlock &BB = *I.getParent(); 3227 if (&I != &BB.front()) { 3228 BasicBlock::const_iterator PredI = 3229 std::prev(BasicBlock::const_iterator(&I)); 3230 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3231 if (Call->doesNotReturn()) 3232 return; 3233 } 3234 } 3235 } 3236 3237 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3238 } 3239 3240 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3241 SDNodeFlags Flags; 3242 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3243 Flags.copyFMF(*FPOp); 3244 3245 SDValue Op = getValue(I.getOperand(0)); 3246 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3247 Op, Flags); 3248 setValue(&I, UnNodeValue); 3249 } 3250 3251 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3252 SDNodeFlags Flags; 3253 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3254 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3255 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3256 } 3257 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3258 Flags.setExact(ExactOp->isExact()); 3259 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3260 Flags.copyFMF(*FPOp); 3261 3262 SDValue Op1 = getValue(I.getOperand(0)); 3263 SDValue Op2 = getValue(I.getOperand(1)); 3264 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3265 Op1, Op2, Flags); 3266 setValue(&I, BinNodeValue); 3267 } 3268 3269 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3270 SDValue Op1 = getValue(I.getOperand(0)); 3271 SDValue Op2 = getValue(I.getOperand(1)); 3272 3273 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3274 Op1.getValueType(), DAG.getDataLayout()); 3275 3276 // Coerce the shift amount to the right type if we can. This exposes the 3277 // truncate or zext to optimization early. 3278 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3279 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && 3280 "Unexpected shift type"); 3281 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy); 3282 } 3283 3284 bool nuw = false; 3285 bool nsw = false; 3286 bool exact = false; 3287 3288 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3289 3290 if (const OverflowingBinaryOperator *OFBinOp = 3291 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3292 nuw = OFBinOp->hasNoUnsignedWrap(); 3293 nsw = OFBinOp->hasNoSignedWrap(); 3294 } 3295 if (const PossiblyExactOperator *ExactOp = 3296 dyn_cast<const PossiblyExactOperator>(&I)) 3297 exact = ExactOp->isExact(); 3298 } 3299 SDNodeFlags Flags; 3300 Flags.setExact(exact); 3301 Flags.setNoSignedWrap(nsw); 3302 Flags.setNoUnsignedWrap(nuw); 3303 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3304 Flags); 3305 setValue(&I, Res); 3306 } 3307 3308 void SelectionDAGBuilder::visitSDiv(const User &I) { 3309 SDValue Op1 = getValue(I.getOperand(0)); 3310 SDValue Op2 = getValue(I.getOperand(1)); 3311 3312 SDNodeFlags Flags; 3313 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3314 cast<PossiblyExactOperator>(&I)->isExact()); 3315 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3316 Op2, Flags)); 3317 } 3318 3319 void SelectionDAGBuilder::visitICmp(const User &I) { 3320 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3321 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3322 predicate = IC->getPredicate(); 3323 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3324 predicate = ICmpInst::Predicate(IC->getPredicate()); 3325 SDValue Op1 = getValue(I.getOperand(0)); 3326 SDValue Op2 = getValue(I.getOperand(1)); 3327 ISD::CondCode Opcode = getICmpCondCode(predicate); 3328 3329 auto &TLI = DAG.getTargetLoweringInfo(); 3330 EVT MemVT = 3331 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3332 3333 // If a pointer's DAG type is larger than its memory type then the DAG values 3334 // are zero-extended. This breaks signed comparisons so truncate back to the 3335 // underlying type before doing the compare. 3336 if (Op1.getValueType() != MemVT) { 3337 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3338 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3339 } 3340 3341 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3342 I.getType()); 3343 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3344 } 3345 3346 void SelectionDAGBuilder::visitFCmp(const User &I) { 3347 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3348 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3349 predicate = FC->getPredicate(); 3350 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3351 predicate = FCmpInst::Predicate(FC->getPredicate()); 3352 SDValue Op1 = getValue(I.getOperand(0)); 3353 SDValue Op2 = getValue(I.getOperand(1)); 3354 3355 ISD::CondCode Condition = getFCmpCondCode(predicate); 3356 auto *FPMO = cast<FPMathOperator>(&I); 3357 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3358 Condition = getFCmpCodeWithoutNaN(Condition); 3359 3360 SDNodeFlags Flags; 3361 Flags.copyFMF(*FPMO); 3362 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3363 3364 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3365 I.getType()); 3366 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3367 } 3368 3369 // Check if the condition of the select has one use or two users that are both 3370 // selects with the same condition. 3371 static bool hasOnlySelectUsers(const Value *Cond) { 3372 return llvm::all_of(Cond->users(), [](const Value *V) { 3373 return isa<SelectInst>(V); 3374 }); 3375 } 3376 3377 void SelectionDAGBuilder::visitSelect(const User &I) { 3378 SmallVector<EVT, 4> ValueVTs; 3379 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3380 ValueVTs); 3381 unsigned NumValues = ValueVTs.size(); 3382 if (NumValues == 0) return; 3383 3384 SmallVector<SDValue, 4> Values(NumValues); 3385 SDValue Cond = getValue(I.getOperand(0)); 3386 SDValue LHSVal = getValue(I.getOperand(1)); 3387 SDValue RHSVal = getValue(I.getOperand(2)); 3388 SmallVector<SDValue, 1> BaseOps(1, Cond); 3389 ISD::NodeType OpCode = 3390 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3391 3392 bool IsUnaryAbs = false; 3393 bool Negate = false; 3394 3395 SDNodeFlags Flags; 3396 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3397 Flags.copyFMF(*FPOp); 3398 3399 Flags.setUnpredictable( 3400 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable)); 3401 3402 // Min/max matching is only viable if all output VTs are the same. 3403 if (all_equal(ValueVTs)) { 3404 EVT VT = ValueVTs[0]; 3405 LLVMContext &Ctx = *DAG.getContext(); 3406 auto &TLI = DAG.getTargetLoweringInfo(); 3407 3408 // We care about the legality of the operation after it has been type 3409 // legalized. 3410 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3411 VT = TLI.getTypeToTransformTo(Ctx, VT); 3412 3413 // If the vselect is legal, assume we want to leave this as a vector setcc + 3414 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3415 // min/max is legal on the scalar type. 3416 bool UseScalarMinMax = VT.isVector() && 3417 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3418 3419 // ValueTracking's select pattern matching does not account for -0.0, 3420 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that 3421 // -0.0 is less than +0.0. 3422 Value *LHS, *RHS; 3423 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3424 ISD::NodeType Opc = ISD::DELETED_NODE; 3425 switch (SPR.Flavor) { 3426 case SPF_UMAX: Opc = ISD::UMAX; break; 3427 case SPF_UMIN: Opc = ISD::UMIN; break; 3428 case SPF_SMAX: Opc = ISD::SMAX; break; 3429 case SPF_SMIN: Opc = ISD::SMIN; break; 3430 case SPF_FMINNUM: 3431 switch (SPR.NaNBehavior) { 3432 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3433 case SPNB_RETURNS_NAN: break; 3434 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3435 case SPNB_RETURNS_ANY: 3436 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) || 3437 (UseScalarMinMax && 3438 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()))) 3439 Opc = ISD::FMINNUM; 3440 break; 3441 } 3442 break; 3443 case SPF_FMAXNUM: 3444 switch (SPR.NaNBehavior) { 3445 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3446 case SPNB_RETURNS_NAN: break; 3447 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3448 case SPNB_RETURNS_ANY: 3449 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) || 3450 (UseScalarMinMax && 3451 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()))) 3452 Opc = ISD::FMAXNUM; 3453 break; 3454 } 3455 break; 3456 case SPF_NABS: 3457 Negate = true; 3458 [[fallthrough]]; 3459 case SPF_ABS: 3460 IsUnaryAbs = true; 3461 Opc = ISD::ABS; 3462 break; 3463 default: break; 3464 } 3465 3466 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3467 (TLI.isOperationLegalOrCustom(Opc, VT) || 3468 (UseScalarMinMax && 3469 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3470 // If the underlying comparison instruction is used by any other 3471 // instruction, the consumed instructions won't be destroyed, so it is 3472 // not profitable to convert to a min/max. 3473 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3474 OpCode = Opc; 3475 LHSVal = getValue(LHS); 3476 RHSVal = getValue(RHS); 3477 BaseOps.clear(); 3478 } 3479 3480 if (IsUnaryAbs) { 3481 OpCode = Opc; 3482 LHSVal = getValue(LHS); 3483 BaseOps.clear(); 3484 } 3485 } 3486 3487 if (IsUnaryAbs) { 3488 for (unsigned i = 0; i != NumValues; ++i) { 3489 SDLoc dl = getCurSDLoc(); 3490 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3491 Values[i] = 3492 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3493 if (Negate) 3494 Values[i] = DAG.getNegative(Values[i], dl, VT); 3495 } 3496 } else { 3497 for (unsigned i = 0; i != NumValues; ++i) { 3498 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3499 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3500 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3501 Values[i] = DAG.getNode( 3502 OpCode, getCurSDLoc(), 3503 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3504 } 3505 } 3506 3507 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3508 DAG.getVTList(ValueVTs), Values)); 3509 } 3510 3511 void SelectionDAGBuilder::visitTrunc(const User &I) { 3512 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3513 SDValue N = getValue(I.getOperand(0)); 3514 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3515 I.getType()); 3516 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3517 } 3518 3519 void SelectionDAGBuilder::visitZExt(const User &I) { 3520 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3521 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3522 SDValue N = getValue(I.getOperand(0)); 3523 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3524 I.getType()); 3525 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3526 } 3527 3528 void SelectionDAGBuilder::visitSExt(const User &I) { 3529 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3530 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3531 SDValue N = getValue(I.getOperand(0)); 3532 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3533 I.getType()); 3534 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3535 } 3536 3537 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3538 // FPTrunc is never a no-op cast, no need to check 3539 SDValue N = getValue(I.getOperand(0)); 3540 SDLoc dl = getCurSDLoc(); 3541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3542 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3543 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3544 DAG.getTargetConstant( 3545 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3546 } 3547 3548 void SelectionDAGBuilder::visitFPExt(const User &I) { 3549 // FPExt is never a no-op cast, no need to check 3550 SDValue N = getValue(I.getOperand(0)); 3551 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3552 I.getType()); 3553 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3554 } 3555 3556 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3557 // FPToUI is never a no-op cast, no need to check 3558 SDValue N = getValue(I.getOperand(0)); 3559 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3560 I.getType()); 3561 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3562 } 3563 3564 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3565 // FPToSI is never a no-op cast, no need to check 3566 SDValue N = getValue(I.getOperand(0)); 3567 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3568 I.getType()); 3569 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3570 } 3571 3572 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3573 // UIToFP is never a no-op cast, no need to check 3574 SDValue N = getValue(I.getOperand(0)); 3575 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3576 I.getType()); 3577 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3578 } 3579 3580 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3581 // SIToFP is never a no-op cast, no need to check 3582 SDValue N = getValue(I.getOperand(0)); 3583 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3584 I.getType()); 3585 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3586 } 3587 3588 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3589 // What to do depends on the size of the integer and the size of the pointer. 3590 // We can either truncate, zero extend, or no-op, accordingly. 3591 SDValue N = getValue(I.getOperand(0)); 3592 auto &TLI = DAG.getTargetLoweringInfo(); 3593 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3594 I.getType()); 3595 EVT PtrMemVT = 3596 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3597 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3598 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3599 setValue(&I, N); 3600 } 3601 3602 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3603 // What to do depends on the size of the integer and the size of the pointer. 3604 // We can either truncate, zero extend, or no-op, accordingly. 3605 SDValue N = getValue(I.getOperand(0)); 3606 auto &TLI = DAG.getTargetLoweringInfo(); 3607 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3608 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3609 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3610 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3611 setValue(&I, N); 3612 } 3613 3614 void SelectionDAGBuilder::visitBitCast(const User &I) { 3615 SDValue N = getValue(I.getOperand(0)); 3616 SDLoc dl = getCurSDLoc(); 3617 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3618 I.getType()); 3619 3620 // BitCast assures us that source and destination are the same size so this is 3621 // either a BITCAST or a no-op. 3622 if (DestVT != N.getValueType()) 3623 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3624 DestVT, N)); // convert types. 3625 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3626 // might fold any kind of constant expression to an integer constant and that 3627 // is not what we are looking for. Only recognize a bitcast of a genuine 3628 // constant integer as an opaque constant. 3629 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3630 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3631 /*isOpaque*/true)); 3632 else 3633 setValue(&I, N); // noop cast. 3634 } 3635 3636 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3638 const Value *SV = I.getOperand(0); 3639 SDValue N = getValue(SV); 3640 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3641 3642 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3643 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3644 3645 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3646 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3647 3648 setValue(&I, N); 3649 } 3650 3651 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3653 SDValue InVec = getValue(I.getOperand(0)); 3654 SDValue InVal = getValue(I.getOperand(1)); 3655 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3656 TLI.getVectorIdxTy(DAG.getDataLayout())); 3657 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3658 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3659 InVec, InVal, InIdx)); 3660 } 3661 3662 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3664 SDValue InVec = getValue(I.getOperand(0)); 3665 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3666 TLI.getVectorIdxTy(DAG.getDataLayout())); 3667 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3668 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3669 InVec, InIdx)); 3670 } 3671 3672 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3673 SDValue Src1 = getValue(I.getOperand(0)); 3674 SDValue Src2 = getValue(I.getOperand(1)); 3675 ArrayRef<int> Mask; 3676 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3677 Mask = SVI->getShuffleMask(); 3678 else 3679 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3680 SDLoc DL = getCurSDLoc(); 3681 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3682 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3683 EVT SrcVT = Src1.getValueType(); 3684 3685 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3686 VT.isScalableVector()) { 3687 // Canonical splat form of first element of first input vector. 3688 SDValue FirstElt = 3689 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3690 DAG.getVectorIdxConstant(0, DL)); 3691 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3692 return; 3693 } 3694 3695 // For now, we only handle splats for scalable vectors. 3696 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3697 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3698 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3699 3700 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3701 unsigned MaskNumElts = Mask.size(); 3702 3703 if (SrcNumElts == MaskNumElts) { 3704 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3705 return; 3706 } 3707 3708 // Normalize the shuffle vector since mask and vector length don't match. 3709 if (SrcNumElts < MaskNumElts) { 3710 // Mask is longer than the source vectors. We can use concatenate vector to 3711 // make the mask and vectors lengths match. 3712 3713 if (MaskNumElts % SrcNumElts == 0) { 3714 // Mask length is a multiple of the source vector length. 3715 // Check if the shuffle is some kind of concatenation of the input 3716 // vectors. 3717 unsigned NumConcat = MaskNumElts / SrcNumElts; 3718 bool IsConcat = true; 3719 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3720 for (unsigned i = 0; i != MaskNumElts; ++i) { 3721 int Idx = Mask[i]; 3722 if (Idx < 0) 3723 continue; 3724 // Ensure the indices in each SrcVT sized piece are sequential and that 3725 // the same source is used for the whole piece. 3726 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3727 (ConcatSrcs[i / SrcNumElts] >= 0 && 3728 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3729 IsConcat = false; 3730 break; 3731 } 3732 // Remember which source this index came from. 3733 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3734 } 3735 3736 // The shuffle is concatenating multiple vectors together. Just emit 3737 // a CONCAT_VECTORS operation. 3738 if (IsConcat) { 3739 SmallVector<SDValue, 8> ConcatOps; 3740 for (auto Src : ConcatSrcs) { 3741 if (Src < 0) 3742 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3743 else if (Src == 0) 3744 ConcatOps.push_back(Src1); 3745 else 3746 ConcatOps.push_back(Src2); 3747 } 3748 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3749 return; 3750 } 3751 } 3752 3753 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3754 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3755 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3756 PaddedMaskNumElts); 3757 3758 // Pad both vectors with undefs to make them the same length as the mask. 3759 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3760 3761 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3762 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3763 MOps1[0] = Src1; 3764 MOps2[0] = Src2; 3765 3766 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3767 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3768 3769 // Readjust mask for new input vector length. 3770 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3771 for (unsigned i = 0; i != MaskNumElts; ++i) { 3772 int Idx = Mask[i]; 3773 if (Idx >= (int)SrcNumElts) 3774 Idx -= SrcNumElts - PaddedMaskNumElts; 3775 MappedOps[i] = Idx; 3776 } 3777 3778 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3779 3780 // If the concatenated vector was padded, extract a subvector with the 3781 // correct number of elements. 3782 if (MaskNumElts != PaddedMaskNumElts) 3783 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3784 DAG.getVectorIdxConstant(0, DL)); 3785 3786 setValue(&I, Result); 3787 return; 3788 } 3789 3790 if (SrcNumElts > MaskNumElts) { 3791 // Analyze the access pattern of the vector to see if we can extract 3792 // two subvectors and do the shuffle. 3793 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3794 bool CanExtract = true; 3795 for (int Idx : Mask) { 3796 unsigned Input = 0; 3797 if (Idx < 0) 3798 continue; 3799 3800 if (Idx >= (int)SrcNumElts) { 3801 Input = 1; 3802 Idx -= SrcNumElts; 3803 } 3804 3805 // If all the indices come from the same MaskNumElts sized portion of 3806 // the sources we can use extract. Also make sure the extract wouldn't 3807 // extract past the end of the source. 3808 int NewStartIdx = alignDown(Idx, MaskNumElts); 3809 if (NewStartIdx + MaskNumElts > SrcNumElts || 3810 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3811 CanExtract = false; 3812 // Make sure we always update StartIdx as we use it to track if all 3813 // elements are undef. 3814 StartIdx[Input] = NewStartIdx; 3815 } 3816 3817 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3818 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3819 return; 3820 } 3821 if (CanExtract) { 3822 // Extract appropriate subvector and generate a vector shuffle 3823 for (unsigned Input = 0; Input < 2; ++Input) { 3824 SDValue &Src = Input == 0 ? Src1 : Src2; 3825 if (StartIdx[Input] < 0) 3826 Src = DAG.getUNDEF(VT); 3827 else { 3828 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3829 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3830 } 3831 } 3832 3833 // Calculate new mask. 3834 SmallVector<int, 8> MappedOps(Mask); 3835 for (int &Idx : MappedOps) { 3836 if (Idx >= (int)SrcNumElts) 3837 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3838 else if (Idx >= 0) 3839 Idx -= StartIdx[0]; 3840 } 3841 3842 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3843 return; 3844 } 3845 } 3846 3847 // We can't use either concat vectors or extract subvectors so fall back to 3848 // replacing the shuffle with extract and build vector. 3849 // to insert and build vector. 3850 EVT EltVT = VT.getVectorElementType(); 3851 SmallVector<SDValue,8> Ops; 3852 for (int Idx : Mask) { 3853 SDValue Res; 3854 3855 if (Idx < 0) { 3856 Res = DAG.getUNDEF(EltVT); 3857 } else { 3858 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3859 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3860 3861 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3862 DAG.getVectorIdxConstant(Idx, DL)); 3863 } 3864 3865 Ops.push_back(Res); 3866 } 3867 3868 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3869 } 3870 3871 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3872 ArrayRef<unsigned> Indices = I.getIndices(); 3873 const Value *Op0 = I.getOperand(0); 3874 const Value *Op1 = I.getOperand(1); 3875 Type *AggTy = I.getType(); 3876 Type *ValTy = Op1->getType(); 3877 bool IntoUndef = isa<UndefValue>(Op0); 3878 bool FromUndef = isa<UndefValue>(Op1); 3879 3880 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3881 3882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3883 SmallVector<EVT, 4> AggValueVTs; 3884 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3885 SmallVector<EVT, 4> ValValueVTs; 3886 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3887 3888 unsigned NumAggValues = AggValueVTs.size(); 3889 unsigned NumValValues = ValValueVTs.size(); 3890 SmallVector<SDValue, 4> Values(NumAggValues); 3891 3892 // Ignore an insertvalue that produces an empty object 3893 if (!NumAggValues) { 3894 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3895 return; 3896 } 3897 3898 SDValue Agg = getValue(Op0); 3899 unsigned i = 0; 3900 // Copy the beginning value(s) from the original aggregate. 3901 for (; i != LinearIndex; ++i) 3902 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3903 SDValue(Agg.getNode(), Agg.getResNo() + i); 3904 // Copy values from the inserted value(s). 3905 if (NumValValues) { 3906 SDValue Val = getValue(Op1); 3907 for (; i != LinearIndex + NumValValues; ++i) 3908 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3909 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3910 } 3911 // Copy remaining value(s) from the original aggregate. 3912 for (; i != NumAggValues; ++i) 3913 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3914 SDValue(Agg.getNode(), Agg.getResNo() + i); 3915 3916 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3917 DAG.getVTList(AggValueVTs), Values)); 3918 } 3919 3920 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3921 ArrayRef<unsigned> Indices = I.getIndices(); 3922 const Value *Op0 = I.getOperand(0); 3923 Type *AggTy = Op0->getType(); 3924 Type *ValTy = I.getType(); 3925 bool OutOfUndef = isa<UndefValue>(Op0); 3926 3927 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3928 3929 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3930 SmallVector<EVT, 4> ValValueVTs; 3931 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3932 3933 unsigned NumValValues = ValValueVTs.size(); 3934 3935 // Ignore a extractvalue that produces an empty object 3936 if (!NumValValues) { 3937 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3938 return; 3939 } 3940 3941 SmallVector<SDValue, 4> Values(NumValValues); 3942 3943 SDValue Agg = getValue(Op0); 3944 // Copy out the selected value(s). 3945 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3946 Values[i - LinearIndex] = 3947 OutOfUndef ? 3948 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3949 SDValue(Agg.getNode(), Agg.getResNo() + i); 3950 3951 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3952 DAG.getVTList(ValValueVTs), Values)); 3953 } 3954 3955 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3956 Value *Op0 = I.getOperand(0); 3957 // Note that the pointer operand may be a vector of pointers. Take the scalar 3958 // element which holds a pointer. 3959 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3960 SDValue N = getValue(Op0); 3961 SDLoc dl = getCurSDLoc(); 3962 auto &TLI = DAG.getTargetLoweringInfo(); 3963 3964 // Normalize Vector GEP - all scalar operands should be converted to the 3965 // splat vector. 3966 bool IsVectorGEP = I.getType()->isVectorTy(); 3967 ElementCount VectorElementCount = 3968 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3969 : ElementCount::getFixed(0); 3970 3971 if (IsVectorGEP && !N.getValueType().isVector()) { 3972 LLVMContext &Context = *DAG.getContext(); 3973 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3974 N = DAG.getSplat(VT, dl, N); 3975 } 3976 3977 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3978 GTI != E; ++GTI) { 3979 const Value *Idx = GTI.getOperand(); 3980 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3981 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3982 if (Field) { 3983 // N = N + Offset 3984 uint64_t Offset = 3985 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field); 3986 3987 // In an inbounds GEP with an offset that is nonnegative even when 3988 // interpreted as signed, assume there is no unsigned overflow. 3989 SDNodeFlags Flags; 3990 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3991 Flags.setNoUnsignedWrap(true); 3992 3993 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3994 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3995 } 3996 } else { 3997 // IdxSize is the width of the arithmetic according to IR semantics. 3998 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3999 // (and fix up the result later). 4000 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 4001 MVT IdxTy = MVT::getIntegerVT(IdxSize); 4002 TypeSize ElementSize = 4003 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType()); 4004 // We intentionally mask away the high bits here; ElementSize may not 4005 // fit in IdxTy. 4006 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue()); 4007 bool ElementScalable = ElementSize.isScalable(); 4008 4009 // If this is a scalar constant or a splat vector of constants, 4010 // handle it quickly. 4011 const auto *C = dyn_cast<Constant>(Idx); 4012 if (C && isa<VectorType>(C->getType())) 4013 C = C->getSplatValue(); 4014 4015 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 4016 if (CI && CI->isZero()) 4017 continue; 4018 if (CI && !ElementScalable) { 4019 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 4020 LLVMContext &Context = *DAG.getContext(); 4021 SDValue OffsVal; 4022 if (IsVectorGEP) 4023 OffsVal = DAG.getConstant( 4024 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 4025 else 4026 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 4027 4028 // In an inbounds GEP with an offset that is nonnegative even when 4029 // interpreted as signed, assume there is no unsigned overflow. 4030 SDNodeFlags Flags; 4031 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 4032 Flags.setNoUnsignedWrap(true); 4033 4034 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 4035 4036 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 4037 continue; 4038 } 4039 4040 // N = N + Idx * ElementMul; 4041 SDValue IdxN = getValue(Idx); 4042 4043 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 4044 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 4045 VectorElementCount); 4046 IdxN = DAG.getSplat(VT, dl, IdxN); 4047 } 4048 4049 // If the index is smaller or larger than intptr_t, truncate or extend 4050 // it. 4051 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 4052 4053 if (ElementScalable) { 4054 EVT VScaleTy = N.getValueType().getScalarType(); 4055 SDValue VScale = DAG.getNode( 4056 ISD::VSCALE, dl, VScaleTy, 4057 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 4058 if (IsVectorGEP) 4059 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 4060 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 4061 } else { 4062 // If this is a multiply by a power of two, turn it into a shl 4063 // immediately. This is a very common case. 4064 if (ElementMul != 1) { 4065 if (ElementMul.isPowerOf2()) { 4066 unsigned Amt = ElementMul.logBase2(); 4067 IdxN = DAG.getNode(ISD::SHL, dl, 4068 N.getValueType(), IdxN, 4069 DAG.getConstant(Amt, dl, IdxN.getValueType())); 4070 } else { 4071 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 4072 IdxN.getValueType()); 4073 IdxN = DAG.getNode(ISD::MUL, dl, 4074 N.getValueType(), IdxN, Scale); 4075 } 4076 } 4077 } 4078 4079 N = DAG.getNode(ISD::ADD, dl, 4080 N.getValueType(), N, IdxN); 4081 } 4082 } 4083 4084 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 4085 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 4086 if (IsVectorGEP) { 4087 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 4088 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 4089 } 4090 4091 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 4092 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 4093 4094 setValue(&I, N); 4095 } 4096 4097 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 4098 // If this is a fixed sized alloca in the entry block of the function, 4099 // allocate it statically on the stack. 4100 if (FuncInfo.StaticAllocaMap.count(&I)) 4101 return; // getValue will auto-populate this. 4102 4103 SDLoc dl = getCurSDLoc(); 4104 Type *Ty = I.getAllocatedType(); 4105 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4106 auto &DL = DAG.getDataLayout(); 4107 TypeSize TySize = DL.getTypeAllocSize(Ty); 4108 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 4109 4110 SDValue AllocSize = getValue(I.getArraySize()); 4111 4112 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace()); 4113 if (AllocSize.getValueType() != IntPtr) 4114 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 4115 4116 if (TySize.isScalable()) 4117 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4118 DAG.getVScale(dl, IntPtr, 4119 APInt(IntPtr.getScalarSizeInBits(), 4120 TySize.getKnownMinValue()))); 4121 else 4122 AllocSize = 4123 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize, 4124 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr)); 4125 4126 // Handle alignment. If the requested alignment is less than or equal to 4127 // the stack alignment, ignore it. If the size is greater than or equal to 4128 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 4129 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 4130 if (*Alignment <= StackAlign) 4131 Alignment = std::nullopt; 4132 4133 const uint64_t StackAlignMask = StackAlign.value() - 1U; 4134 // Round the size of the allocation up to the stack alignment size 4135 // by add SA-1 to the size. This doesn't overflow because we're computing 4136 // an address inside an alloca. 4137 SDNodeFlags Flags; 4138 Flags.setNoUnsignedWrap(true); 4139 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4140 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 4141 4142 // Mask out the low bits for alignment purposes. 4143 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4144 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 4145 4146 SDValue Ops[] = { 4147 getRoot(), AllocSize, 4148 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 4149 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4150 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4151 setValue(&I, DSA); 4152 DAG.setRoot(DSA.getValue(1)); 4153 4154 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4155 } 4156 4157 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4158 if (I.isAtomic()) 4159 return visitAtomicLoad(I); 4160 4161 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4162 const Value *SV = I.getOperand(0); 4163 if (TLI.supportSwiftError()) { 4164 // Swifterror values can come from either a function parameter with 4165 // swifterror attribute or an alloca with swifterror attribute. 4166 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4167 if (Arg->hasSwiftErrorAttr()) 4168 return visitLoadFromSwiftError(I); 4169 } 4170 4171 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4172 if (Alloca->isSwiftError()) 4173 return visitLoadFromSwiftError(I); 4174 } 4175 } 4176 4177 SDValue Ptr = getValue(SV); 4178 4179 Type *Ty = I.getType(); 4180 SmallVector<EVT, 4> ValueVTs, MemVTs; 4181 SmallVector<uint64_t, 4> Offsets; 4182 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets, 0); 4183 unsigned NumValues = ValueVTs.size(); 4184 if (NumValues == 0) 4185 return; 4186 4187 Align Alignment = I.getAlign(); 4188 AAMDNodes AAInfo = I.getAAMetadata(); 4189 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4190 bool isVolatile = I.isVolatile(); 4191 MachineMemOperand::Flags MMOFlags = 4192 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4193 4194 SDValue Root; 4195 bool ConstantMemory = false; 4196 if (isVolatile) 4197 // Serialize volatile loads with other side effects. 4198 Root = getRoot(); 4199 else if (NumValues > MaxParallelChains) 4200 Root = getMemoryRoot(); 4201 else if (AA && 4202 AA->pointsToConstantMemory(MemoryLocation( 4203 SV, 4204 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4205 AAInfo))) { 4206 // Do not serialize (non-volatile) loads of constant memory with anything. 4207 Root = DAG.getEntryNode(); 4208 ConstantMemory = true; 4209 MMOFlags |= MachineMemOperand::MOInvariant; 4210 } else { 4211 // Do not serialize non-volatile loads against each other. 4212 Root = DAG.getRoot(); 4213 } 4214 4215 SDLoc dl = getCurSDLoc(); 4216 4217 if (isVolatile) 4218 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4219 4220 // An aggregate load cannot wrap around the address space, so offsets to its 4221 // parts don't wrap either. 4222 SDNodeFlags Flags; 4223 Flags.setNoUnsignedWrap(true); 4224 4225 SmallVector<SDValue, 4> Values(NumValues); 4226 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4227 EVT PtrVT = Ptr.getValueType(); 4228 4229 unsigned ChainI = 0; 4230 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4231 // Serializing loads here may result in excessive register pressure, and 4232 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4233 // could recover a bit by hoisting nodes upward in the chain by recognizing 4234 // they are side-effect free or do not alias. The optimizer should really 4235 // avoid this case by converting large object/array copies to llvm.memcpy 4236 // (MaxParallelChains should always remain as failsafe). 4237 if (ChainI == MaxParallelChains) { 4238 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4239 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4240 ArrayRef(Chains.data(), ChainI)); 4241 Root = Chain; 4242 ChainI = 0; 4243 } 4244 SDValue A = DAG.getNode(ISD::ADD, dl, 4245 PtrVT, Ptr, 4246 DAG.getConstant(Offsets[i], dl, PtrVT), 4247 Flags); 4248 4249 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4250 MachinePointerInfo(SV, Offsets[i]), Alignment, 4251 MMOFlags, AAInfo, Ranges); 4252 Chains[ChainI] = L.getValue(1); 4253 4254 if (MemVTs[i] != ValueVTs[i]) 4255 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]); 4256 4257 Values[i] = L; 4258 } 4259 4260 if (!ConstantMemory) { 4261 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4262 ArrayRef(Chains.data(), ChainI)); 4263 if (isVolatile) 4264 DAG.setRoot(Chain); 4265 else 4266 PendingLoads.push_back(Chain); 4267 } 4268 4269 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4270 DAG.getVTList(ValueVTs), Values)); 4271 } 4272 4273 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4274 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4275 "call visitStoreToSwiftError when backend supports swifterror"); 4276 4277 SmallVector<EVT, 4> ValueVTs; 4278 SmallVector<uint64_t, 4> Offsets; 4279 const Value *SrcV = I.getOperand(0); 4280 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4281 SrcV->getType(), ValueVTs, &Offsets, 0); 4282 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4283 "expect a single EVT for swifterror"); 4284 4285 SDValue Src = getValue(SrcV); 4286 // Create a virtual register, then update the virtual register. 4287 Register VReg = 4288 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4289 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4290 // Chain can be getRoot or getControlRoot. 4291 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4292 SDValue(Src.getNode(), Src.getResNo())); 4293 DAG.setRoot(CopyNode); 4294 } 4295 4296 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4297 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4298 "call visitLoadFromSwiftError when backend supports swifterror"); 4299 4300 assert(!I.isVolatile() && 4301 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4302 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4303 "Support volatile, non temporal, invariant for load_from_swift_error"); 4304 4305 const Value *SV = I.getOperand(0); 4306 Type *Ty = I.getType(); 4307 assert( 4308 (!AA || 4309 !AA->pointsToConstantMemory(MemoryLocation( 4310 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4311 I.getAAMetadata()))) && 4312 "load_from_swift_error should not be constant memory"); 4313 4314 SmallVector<EVT, 4> ValueVTs; 4315 SmallVector<uint64_t, 4> Offsets; 4316 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4317 ValueVTs, &Offsets, 0); 4318 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4319 "expect a single EVT for swifterror"); 4320 4321 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4322 SDValue L = DAG.getCopyFromReg( 4323 getRoot(), getCurSDLoc(), 4324 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4325 4326 setValue(&I, L); 4327 } 4328 4329 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4330 if (I.isAtomic()) 4331 return visitAtomicStore(I); 4332 4333 const Value *SrcV = I.getOperand(0); 4334 const Value *PtrV = I.getOperand(1); 4335 4336 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4337 if (TLI.supportSwiftError()) { 4338 // Swifterror values can come from either a function parameter with 4339 // swifterror attribute or an alloca with swifterror attribute. 4340 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4341 if (Arg->hasSwiftErrorAttr()) 4342 return visitStoreToSwiftError(I); 4343 } 4344 4345 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4346 if (Alloca->isSwiftError()) 4347 return visitStoreToSwiftError(I); 4348 } 4349 } 4350 4351 SmallVector<EVT, 4> ValueVTs, MemVTs; 4352 SmallVector<uint64_t, 4> Offsets; 4353 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4354 SrcV->getType(), ValueVTs, &MemVTs, &Offsets, 0); 4355 unsigned NumValues = ValueVTs.size(); 4356 if (NumValues == 0) 4357 return; 4358 4359 // Get the lowered operands. Note that we do this after 4360 // checking if NumResults is zero, because with zero results 4361 // the operands won't have values in the map. 4362 SDValue Src = getValue(SrcV); 4363 SDValue Ptr = getValue(PtrV); 4364 4365 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4366 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4367 SDLoc dl = getCurSDLoc(); 4368 Align Alignment = I.getAlign(); 4369 AAMDNodes AAInfo = I.getAAMetadata(); 4370 4371 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4372 4373 // An aggregate load cannot wrap around the address space, so offsets to its 4374 // parts don't wrap either. 4375 SDNodeFlags Flags; 4376 Flags.setNoUnsignedWrap(true); 4377 4378 unsigned ChainI = 0; 4379 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4380 // See visitLoad comments. 4381 if (ChainI == MaxParallelChains) { 4382 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4383 ArrayRef(Chains.data(), ChainI)); 4384 Root = Chain; 4385 ChainI = 0; 4386 } 4387 SDValue Add = 4388 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4389 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4390 if (MemVTs[i] != ValueVTs[i]) 4391 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4392 SDValue St = 4393 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4394 Alignment, MMOFlags, AAInfo); 4395 Chains[ChainI] = St; 4396 } 4397 4398 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4399 ArrayRef(Chains.data(), ChainI)); 4400 setValue(&I, StoreNode); 4401 DAG.setRoot(StoreNode); 4402 } 4403 4404 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4405 bool IsCompressing) { 4406 SDLoc sdl = getCurSDLoc(); 4407 4408 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4409 MaybeAlign &Alignment) { 4410 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4411 Src0 = I.getArgOperand(0); 4412 Ptr = I.getArgOperand(1); 4413 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4414 Mask = I.getArgOperand(3); 4415 }; 4416 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4417 MaybeAlign &Alignment) { 4418 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4419 Src0 = I.getArgOperand(0); 4420 Ptr = I.getArgOperand(1); 4421 Mask = I.getArgOperand(2); 4422 Alignment = std::nullopt; 4423 }; 4424 4425 Value *PtrOperand, *MaskOperand, *Src0Operand; 4426 MaybeAlign Alignment; 4427 if (IsCompressing) 4428 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4429 else 4430 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4431 4432 SDValue Ptr = getValue(PtrOperand); 4433 SDValue Src0 = getValue(Src0Operand); 4434 SDValue Mask = getValue(MaskOperand); 4435 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4436 4437 EVT VT = Src0.getValueType(); 4438 if (!Alignment) 4439 Alignment = DAG.getEVTAlign(VT); 4440 4441 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4442 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4443 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata()); 4444 SDValue StoreNode = 4445 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4446 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4447 DAG.setRoot(StoreNode); 4448 setValue(&I, StoreNode); 4449 } 4450 4451 // Get a uniform base for the Gather/Scatter intrinsic. 4452 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4453 // We try to represent it as a base pointer + vector of indices. 4454 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4455 // The first operand of the GEP may be a single pointer or a vector of pointers 4456 // Example: 4457 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4458 // or 4459 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4460 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4461 // 4462 // When the first GEP operand is a single pointer - it is the uniform base we 4463 // are looking for. If first operand of the GEP is a splat vector - we 4464 // extract the splat value and use it as a uniform base. 4465 // In all other cases the function returns 'false'. 4466 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4467 ISD::MemIndexType &IndexType, SDValue &Scale, 4468 SelectionDAGBuilder *SDB, const BasicBlock *CurBB, 4469 uint64_t ElemSize) { 4470 SelectionDAG& DAG = SDB->DAG; 4471 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4472 const DataLayout &DL = DAG.getDataLayout(); 4473 4474 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type"); 4475 4476 // Handle splat constant pointer. 4477 if (auto *C = dyn_cast<Constant>(Ptr)) { 4478 C = C->getSplatValue(); 4479 if (!C) 4480 return false; 4481 4482 Base = SDB->getValue(C); 4483 4484 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount(); 4485 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4486 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4487 IndexType = ISD::SIGNED_SCALED; 4488 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4489 return true; 4490 } 4491 4492 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4493 if (!GEP || GEP->getParent() != CurBB) 4494 return false; 4495 4496 if (GEP->getNumOperands() != 2) 4497 return false; 4498 4499 const Value *BasePtr = GEP->getPointerOperand(); 4500 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4501 4502 // Make sure the base is scalar and the index is a vector. 4503 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4504 return false; 4505 4506 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType()); 4507 4508 // Target may not support the required addressing mode. 4509 if (ScaleVal != 1 && 4510 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize)) 4511 return false; 4512 4513 Base = SDB->getValue(BasePtr); 4514 Index = SDB->getValue(IndexVal); 4515 IndexType = ISD::SIGNED_SCALED; 4516 4517 Scale = 4518 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4519 return true; 4520 } 4521 4522 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4523 SDLoc sdl = getCurSDLoc(); 4524 4525 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4526 const Value *Ptr = I.getArgOperand(1); 4527 SDValue Src0 = getValue(I.getArgOperand(0)); 4528 SDValue Mask = getValue(I.getArgOperand(3)); 4529 EVT VT = Src0.getValueType(); 4530 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4531 ->getMaybeAlignValue() 4532 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4534 4535 SDValue Base; 4536 SDValue Index; 4537 ISD::MemIndexType IndexType; 4538 SDValue Scale; 4539 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4540 I.getParent(), VT.getScalarStoreSize()); 4541 4542 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4543 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4544 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4545 // TODO: Make MachineMemOperands aware of scalable 4546 // vectors. 4547 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata()); 4548 if (!UniformBase) { 4549 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4550 Index = getValue(Ptr); 4551 IndexType = ISD::SIGNED_SCALED; 4552 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4553 } 4554 4555 EVT IdxVT = Index.getValueType(); 4556 EVT EltTy = IdxVT.getVectorElementType(); 4557 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4558 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4559 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4560 } 4561 4562 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4563 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4564 Ops, MMO, IndexType, false); 4565 DAG.setRoot(Scatter); 4566 setValue(&I, Scatter); 4567 } 4568 4569 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4570 SDLoc sdl = getCurSDLoc(); 4571 4572 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4573 MaybeAlign &Alignment) { 4574 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4575 Ptr = I.getArgOperand(0); 4576 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4577 Mask = I.getArgOperand(2); 4578 Src0 = I.getArgOperand(3); 4579 }; 4580 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4581 MaybeAlign &Alignment) { 4582 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4583 Ptr = I.getArgOperand(0); 4584 Alignment = std::nullopt; 4585 Mask = I.getArgOperand(1); 4586 Src0 = I.getArgOperand(2); 4587 }; 4588 4589 Value *PtrOperand, *MaskOperand, *Src0Operand; 4590 MaybeAlign Alignment; 4591 if (IsExpanding) 4592 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4593 else 4594 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4595 4596 SDValue Ptr = getValue(PtrOperand); 4597 SDValue Src0 = getValue(Src0Operand); 4598 SDValue Mask = getValue(MaskOperand); 4599 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4600 4601 EVT VT = Src0.getValueType(); 4602 if (!Alignment) 4603 Alignment = DAG.getEVTAlign(VT); 4604 4605 AAMDNodes AAInfo = I.getAAMetadata(); 4606 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4607 4608 // Do not serialize masked loads of constant memory with anything. 4609 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 4610 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4611 4612 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4613 4614 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4615 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4616 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4617 4618 SDValue Load = 4619 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4620 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4621 if (AddToChain) 4622 PendingLoads.push_back(Load.getValue(1)); 4623 setValue(&I, Load); 4624 } 4625 4626 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4627 SDLoc sdl = getCurSDLoc(); 4628 4629 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4630 const Value *Ptr = I.getArgOperand(0); 4631 SDValue Src0 = getValue(I.getArgOperand(3)); 4632 SDValue Mask = getValue(I.getArgOperand(2)); 4633 4634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4635 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4636 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4637 ->getMaybeAlignValue() 4638 .value_or(DAG.getEVTAlign(VT.getScalarType())); 4639 4640 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4641 4642 SDValue Root = DAG.getRoot(); 4643 SDValue Base; 4644 SDValue Index; 4645 ISD::MemIndexType IndexType; 4646 SDValue Scale; 4647 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4648 I.getParent(), VT.getScalarStoreSize()); 4649 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4650 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4651 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4652 // TODO: Make MachineMemOperands aware of scalable 4653 // vectors. 4654 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges); 4655 4656 if (!UniformBase) { 4657 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4658 Index = getValue(Ptr); 4659 IndexType = ISD::SIGNED_SCALED; 4660 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4661 } 4662 4663 EVT IdxVT = Index.getValueType(); 4664 EVT EltTy = IdxVT.getVectorElementType(); 4665 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4666 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4667 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4668 } 4669 4670 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4671 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4672 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4673 4674 PendingLoads.push_back(Gather.getValue(1)); 4675 setValue(&I, Gather); 4676 } 4677 4678 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4679 SDLoc dl = getCurSDLoc(); 4680 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4681 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4682 SyncScope::ID SSID = I.getSyncScopeID(); 4683 4684 SDValue InChain = getRoot(); 4685 4686 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4687 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4688 4689 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4690 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4691 4692 MachineFunction &MF = DAG.getMachineFunction(); 4693 MachineMemOperand *MMO = MF.getMachineMemOperand( 4694 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4695 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4696 FailureOrdering); 4697 4698 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4699 dl, MemVT, VTs, InChain, 4700 getValue(I.getPointerOperand()), 4701 getValue(I.getCompareOperand()), 4702 getValue(I.getNewValOperand()), MMO); 4703 4704 SDValue OutChain = L.getValue(2); 4705 4706 setValue(&I, L); 4707 DAG.setRoot(OutChain); 4708 } 4709 4710 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4711 SDLoc dl = getCurSDLoc(); 4712 ISD::NodeType NT; 4713 switch (I.getOperation()) { 4714 default: llvm_unreachable("Unknown atomicrmw operation"); 4715 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4716 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4717 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4718 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4719 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4720 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4721 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4722 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4723 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4724 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4725 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4726 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4727 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4728 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break; 4729 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break; 4730 case AtomicRMWInst::UIncWrap: 4731 NT = ISD::ATOMIC_LOAD_UINC_WRAP; 4732 break; 4733 case AtomicRMWInst::UDecWrap: 4734 NT = ISD::ATOMIC_LOAD_UDEC_WRAP; 4735 break; 4736 } 4737 AtomicOrdering Ordering = I.getOrdering(); 4738 SyncScope::ID SSID = I.getSyncScopeID(); 4739 4740 SDValue InChain = getRoot(); 4741 4742 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4743 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4744 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4745 4746 MachineFunction &MF = DAG.getMachineFunction(); 4747 MachineMemOperand *MMO = MF.getMachineMemOperand( 4748 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4749 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4750 4751 SDValue L = 4752 DAG.getAtomic(NT, dl, MemVT, InChain, 4753 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4754 MMO); 4755 4756 SDValue OutChain = L.getValue(1); 4757 4758 setValue(&I, L); 4759 DAG.setRoot(OutChain); 4760 } 4761 4762 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4763 SDLoc dl = getCurSDLoc(); 4764 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4765 SDValue Ops[3]; 4766 Ops[0] = getRoot(); 4767 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4768 TLI.getFenceOperandTy(DAG.getDataLayout())); 4769 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4770 TLI.getFenceOperandTy(DAG.getDataLayout())); 4771 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops); 4772 setValue(&I, N); 4773 DAG.setRoot(N); 4774 } 4775 4776 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4777 SDLoc dl = getCurSDLoc(); 4778 AtomicOrdering Order = I.getOrdering(); 4779 SyncScope::ID SSID = I.getSyncScopeID(); 4780 4781 SDValue InChain = getRoot(); 4782 4783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4784 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4785 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4786 4787 if (!TLI.supportsUnalignedAtomics() && 4788 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4789 report_fatal_error("Cannot generate unaligned atomic load"); 4790 4791 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo); 4792 4793 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4794 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4795 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4796 4797 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4798 4799 SDValue Ptr = getValue(I.getPointerOperand()); 4800 4801 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4802 // TODO: Once this is better exercised by tests, it should be merged with 4803 // the normal path for loads to prevent future divergence. 4804 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4805 if (MemVT != VT) 4806 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4807 4808 setValue(&I, L); 4809 SDValue OutChain = L.getValue(1); 4810 if (!I.isUnordered()) 4811 DAG.setRoot(OutChain); 4812 else 4813 PendingLoads.push_back(OutChain); 4814 return; 4815 } 4816 4817 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4818 Ptr, MMO); 4819 4820 SDValue OutChain = L.getValue(1); 4821 if (MemVT != VT) 4822 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4823 4824 setValue(&I, L); 4825 DAG.setRoot(OutChain); 4826 } 4827 4828 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4829 SDLoc dl = getCurSDLoc(); 4830 4831 AtomicOrdering Ordering = I.getOrdering(); 4832 SyncScope::ID SSID = I.getSyncScopeID(); 4833 4834 SDValue InChain = getRoot(); 4835 4836 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4837 EVT MemVT = 4838 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4839 4840 if (!TLI.supportsUnalignedAtomics() && 4841 I.getAlign().value() < MemVT.getSizeInBits() / 8) 4842 report_fatal_error("Cannot generate unaligned atomic store"); 4843 4844 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4845 4846 MachineFunction &MF = DAG.getMachineFunction(); 4847 MachineMemOperand *MMO = MF.getMachineMemOperand( 4848 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4849 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4850 4851 SDValue Val = getValue(I.getValueOperand()); 4852 if (Val.getValueType() != MemVT) 4853 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4854 SDValue Ptr = getValue(I.getPointerOperand()); 4855 4856 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4857 // TODO: Once this is better exercised by tests, it should be merged with 4858 // the normal path for stores to prevent future divergence. 4859 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4860 setValue(&I, S); 4861 DAG.setRoot(S); 4862 return; 4863 } 4864 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4865 Ptr, Val, MMO); 4866 4867 setValue(&I, OutChain); 4868 DAG.setRoot(OutChain); 4869 } 4870 4871 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4872 /// node. 4873 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4874 unsigned Intrinsic) { 4875 // Ignore the callsite's attributes. A specific call site may be marked with 4876 // readnone, but the lowering code will expect the chain based on the 4877 // definition. 4878 const Function *F = I.getCalledFunction(); 4879 bool HasChain = !F->doesNotAccessMemory(); 4880 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4881 4882 // Build the operand list. 4883 SmallVector<SDValue, 8> Ops; 4884 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4885 if (OnlyLoad) { 4886 // We don't need to serialize loads against other loads. 4887 Ops.push_back(DAG.getRoot()); 4888 } else { 4889 Ops.push_back(getRoot()); 4890 } 4891 } 4892 4893 // Info is set by getTgtMemIntrinsic 4894 TargetLowering::IntrinsicInfo Info; 4895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4896 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4897 DAG.getMachineFunction(), 4898 Intrinsic); 4899 4900 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4901 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4902 Info.opc == ISD::INTRINSIC_W_CHAIN) 4903 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4904 TLI.getPointerTy(DAG.getDataLayout()))); 4905 4906 // Add all operands of the call to the operand list. 4907 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) { 4908 const Value *Arg = I.getArgOperand(i); 4909 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4910 Ops.push_back(getValue(Arg)); 4911 continue; 4912 } 4913 4914 // Use TargetConstant instead of a regular constant for immarg. 4915 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true); 4916 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4917 assert(CI->getBitWidth() <= 64 && 4918 "large intrinsic immediates not handled"); 4919 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4920 } else { 4921 Ops.push_back( 4922 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4923 } 4924 } 4925 4926 SmallVector<EVT, 4> ValueVTs; 4927 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4928 4929 if (HasChain) 4930 ValueVTs.push_back(MVT::Other); 4931 4932 SDVTList VTs = DAG.getVTList(ValueVTs); 4933 4934 // Propagate fast-math-flags from IR to node(s). 4935 SDNodeFlags Flags; 4936 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 4937 Flags.copyFMF(*FPMO); 4938 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 4939 4940 // Create the node. 4941 SDValue Result; 4942 // In some cases, custom collection of operands from CallInst I may be needed. 4943 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG); 4944 if (IsTgtIntrinsic) { 4945 // This is target intrinsic that touches memory 4946 // 4947 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic 4948 // didn't yield anything useful. 4949 MachinePointerInfo MPI; 4950 if (Info.ptrVal) 4951 MPI = MachinePointerInfo(Info.ptrVal, Info.offset); 4952 else if (Info.fallbackAddressSpace) 4953 MPI = MachinePointerInfo(*Info.fallbackAddressSpace); 4954 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, 4955 Info.memVT, MPI, Info.align, Info.flags, 4956 Info.size, I.getAAMetadata()); 4957 } else if (!HasChain) { 4958 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4959 } else if (!I.getType()->isVoidTy()) { 4960 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4961 } else { 4962 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4963 } 4964 4965 if (HasChain) { 4966 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4967 if (OnlyLoad) 4968 PendingLoads.push_back(Chain); 4969 else 4970 DAG.setRoot(Chain); 4971 } 4972 4973 if (!I.getType()->isVoidTy()) { 4974 if (!isa<VectorType>(I.getType())) 4975 Result = lowerRangeToAssertZExt(DAG, I, Result); 4976 4977 MaybeAlign Alignment = I.getRetAlign(); 4978 4979 // Insert `assertalign` node if there's an alignment. 4980 if (InsertAssertAlign && Alignment) { 4981 Result = 4982 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4983 } 4984 4985 setValue(&I, Result); 4986 } 4987 } 4988 4989 /// GetSignificand - Get the significand and build it into a floating-point 4990 /// number with exponent of 1: 4991 /// 4992 /// Op = (Op & 0x007fffff) | 0x3f800000; 4993 /// 4994 /// where Op is the hexadecimal representation of floating point value. 4995 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4996 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4997 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4998 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4999 DAG.getConstant(0x3f800000, dl, MVT::i32)); 5000 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 5001 } 5002 5003 /// GetExponent - Get the exponent: 5004 /// 5005 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 5006 /// 5007 /// where Op is the hexadecimal representation of floating point value. 5008 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 5009 const TargetLowering &TLI, const SDLoc &dl) { 5010 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 5011 DAG.getConstant(0x7f800000, dl, MVT::i32)); 5012 SDValue t1 = DAG.getNode( 5013 ISD::SRL, dl, MVT::i32, t0, 5014 DAG.getConstant(23, dl, 5015 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout()))); 5016 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 5017 DAG.getConstant(127, dl, MVT::i32)); 5018 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 5019 } 5020 5021 /// getF32Constant - Get 32-bit floating point constant. 5022 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 5023 const SDLoc &dl) { 5024 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 5025 MVT::f32); 5026 } 5027 5028 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 5029 SelectionDAG &DAG) { 5030 // TODO: What fast-math-flags should be set on the floating-point nodes? 5031 5032 // IntegerPartOfX = ((int32_t)(t0); 5033 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 5034 5035 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 5036 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 5037 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 5038 5039 // IntegerPartOfX <<= 23; 5040 IntegerPartOfX = 5041 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 5042 DAG.getConstant(23, dl, 5043 DAG.getTargetLoweringInfo().getShiftAmountTy( 5044 MVT::i32, DAG.getDataLayout()))); 5045 5046 SDValue TwoToFractionalPartOfX; 5047 if (LimitFloatPrecision <= 6) { 5048 // For floating-point precision of 6: 5049 // 5050 // TwoToFractionalPartOfX = 5051 // 0.997535578f + 5052 // (0.735607626f + 0.252464424f * x) * x; 5053 // 5054 // error 0.0144103317, which is 6 bits 5055 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5056 getF32Constant(DAG, 0x3e814304, dl)); 5057 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5058 getF32Constant(DAG, 0x3f3c50c8, dl)); 5059 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5060 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5061 getF32Constant(DAG, 0x3f7f5e7e, dl)); 5062 } else if (LimitFloatPrecision <= 12) { 5063 // For floating-point precision of 12: 5064 // 5065 // TwoToFractionalPartOfX = 5066 // 0.999892986f + 5067 // (0.696457318f + 5068 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 5069 // 5070 // error 0.000107046256, which is 13 to 14 bits 5071 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5072 getF32Constant(DAG, 0x3da235e3, dl)); 5073 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5074 getF32Constant(DAG, 0x3e65b8f3, dl)); 5075 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5076 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5077 getF32Constant(DAG, 0x3f324b07, dl)); 5078 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5079 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5080 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5081 } else { // LimitFloatPrecision <= 18 5082 // For floating-point precision of 18: 5083 // 5084 // TwoToFractionalPartOfX = 5085 // 0.999999982f + 5086 // (0.693148872f + 5087 // (0.240227044f + 5088 // (0.554906021e-1f + 5089 // (0.961591928e-2f + 5090 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5091 // error 2.47208000*10^(-7), which is better than 18 bits 5092 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5093 getF32Constant(DAG, 0x3924b03e, dl)); 5094 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5095 getF32Constant(DAG, 0x3ab24b87, dl)); 5096 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5097 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5098 getF32Constant(DAG, 0x3c1d8c17, dl)); 5099 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5100 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5101 getF32Constant(DAG, 0x3d634a1d, dl)); 5102 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5103 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5104 getF32Constant(DAG, 0x3e75fe14, dl)); 5105 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5106 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5107 getF32Constant(DAG, 0x3f317234, dl)); 5108 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5109 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5110 getF32Constant(DAG, 0x3f800000, dl)); 5111 } 5112 5113 // Add the exponent into the result in integer domain. 5114 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5115 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5116 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5117 } 5118 5119 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5120 /// limited-precision mode. 5121 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5122 const TargetLowering &TLI, SDNodeFlags Flags) { 5123 if (Op.getValueType() == MVT::f32 && 5124 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5125 5126 // Put the exponent in the right bit position for later addition to the 5127 // final result: 5128 // 5129 // t0 = Op * log2(e) 5130 5131 // TODO: What fast-math-flags should be set here? 5132 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5133 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5134 return getLimitedPrecisionExp2(t0, dl, DAG); 5135 } 5136 5137 // No special expansion. 5138 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 5139 } 5140 5141 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5142 /// limited-precision mode. 5143 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5144 const TargetLowering &TLI, SDNodeFlags Flags) { 5145 // TODO: What fast-math-flags should be set on the floating-point nodes? 5146 5147 if (Op.getValueType() == MVT::f32 && 5148 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5149 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5150 5151 // Scale the exponent by log(2). 5152 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5153 SDValue LogOfExponent = 5154 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5155 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5156 5157 // Get the significand and build it into a floating-point number with 5158 // exponent of 1. 5159 SDValue X = GetSignificand(DAG, Op1, dl); 5160 5161 SDValue LogOfMantissa; 5162 if (LimitFloatPrecision <= 6) { 5163 // For floating-point precision of 6: 5164 // 5165 // LogofMantissa = 5166 // -1.1609546f + 5167 // (1.4034025f - 0.23903021f * x) * x; 5168 // 5169 // error 0.0034276066, which is better than 8 bits 5170 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5171 getF32Constant(DAG, 0xbe74c456, dl)); 5172 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5173 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5174 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5175 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5176 getF32Constant(DAG, 0x3f949a29, dl)); 5177 } else if (LimitFloatPrecision <= 12) { 5178 // For floating-point precision of 12: 5179 // 5180 // LogOfMantissa = 5181 // -1.7417939f + 5182 // (2.8212026f + 5183 // (-1.4699568f + 5184 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5185 // 5186 // error 0.000061011436, which is 14 bits 5187 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5188 getF32Constant(DAG, 0xbd67b6d6, dl)); 5189 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5190 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5191 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5192 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5193 getF32Constant(DAG, 0x3fbc278b, dl)); 5194 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5195 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5196 getF32Constant(DAG, 0x40348e95, dl)); 5197 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5198 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5199 getF32Constant(DAG, 0x3fdef31a, dl)); 5200 } else { // LimitFloatPrecision <= 18 5201 // For floating-point precision of 18: 5202 // 5203 // LogOfMantissa = 5204 // -2.1072184f + 5205 // (4.2372794f + 5206 // (-3.7029485f + 5207 // (2.2781945f + 5208 // (-0.87823314f + 5209 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5210 // 5211 // error 0.0000023660568, which is better than 18 bits 5212 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5213 getF32Constant(DAG, 0xbc91e5ac, dl)); 5214 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5215 getF32Constant(DAG, 0x3e4350aa, dl)); 5216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5217 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5218 getF32Constant(DAG, 0x3f60d3e3, dl)); 5219 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5220 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5221 getF32Constant(DAG, 0x4011cdf0, dl)); 5222 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5223 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5224 getF32Constant(DAG, 0x406cfd1c, dl)); 5225 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5226 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5227 getF32Constant(DAG, 0x408797cb, dl)); 5228 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5229 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5230 getF32Constant(DAG, 0x4006dcab, dl)); 5231 } 5232 5233 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5234 } 5235 5236 // No special expansion. 5237 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5238 } 5239 5240 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5241 /// limited-precision mode. 5242 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5243 const TargetLowering &TLI, SDNodeFlags Flags) { 5244 // TODO: What fast-math-flags should be set on the floating-point nodes? 5245 5246 if (Op.getValueType() == MVT::f32 && 5247 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5248 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5249 5250 // Get the exponent. 5251 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5252 5253 // Get the significand and build it into a floating-point number with 5254 // exponent of 1. 5255 SDValue X = GetSignificand(DAG, Op1, dl); 5256 5257 // Different possible minimax approximations of significand in 5258 // floating-point for various degrees of accuracy over [1,2]. 5259 SDValue Log2ofMantissa; 5260 if (LimitFloatPrecision <= 6) { 5261 // For floating-point precision of 6: 5262 // 5263 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5264 // 5265 // error 0.0049451742, which is more than 7 bits 5266 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5267 getF32Constant(DAG, 0xbeb08fe0, dl)); 5268 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5269 getF32Constant(DAG, 0x40019463, dl)); 5270 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5271 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5272 getF32Constant(DAG, 0x3fd6633d, dl)); 5273 } else if (LimitFloatPrecision <= 12) { 5274 // For floating-point precision of 12: 5275 // 5276 // Log2ofMantissa = 5277 // -2.51285454f + 5278 // (4.07009056f + 5279 // (-2.12067489f + 5280 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5281 // 5282 // error 0.0000876136000, which is better than 13 bits 5283 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5284 getF32Constant(DAG, 0xbda7262e, dl)); 5285 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5286 getF32Constant(DAG, 0x3f25280b, dl)); 5287 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5288 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5289 getF32Constant(DAG, 0x4007b923, dl)); 5290 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5291 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5292 getF32Constant(DAG, 0x40823e2f, dl)); 5293 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5294 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5295 getF32Constant(DAG, 0x4020d29c, dl)); 5296 } else { // LimitFloatPrecision <= 18 5297 // For floating-point precision of 18: 5298 // 5299 // Log2ofMantissa = 5300 // -3.0400495f + 5301 // (6.1129976f + 5302 // (-5.3420409f + 5303 // (3.2865683f + 5304 // (-1.2669343f + 5305 // (0.27515199f - 5306 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5307 // 5308 // error 0.0000018516, which is better than 18 bits 5309 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5310 getF32Constant(DAG, 0xbcd2769e, dl)); 5311 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5312 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5313 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5314 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5315 getF32Constant(DAG, 0x3fa22ae7, dl)); 5316 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5317 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5318 getF32Constant(DAG, 0x40525723, dl)); 5319 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5320 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5321 getF32Constant(DAG, 0x40aaf200, dl)); 5322 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5323 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5324 getF32Constant(DAG, 0x40c39dad, dl)); 5325 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5326 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5327 getF32Constant(DAG, 0x4042902c, dl)); 5328 } 5329 5330 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5331 } 5332 5333 // No special expansion. 5334 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5335 } 5336 5337 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5338 /// limited-precision mode. 5339 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5340 const TargetLowering &TLI, SDNodeFlags Flags) { 5341 // TODO: What fast-math-flags should be set on the floating-point nodes? 5342 5343 if (Op.getValueType() == MVT::f32 && 5344 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5345 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5346 5347 // Scale the exponent by log10(2) [0.30102999f]. 5348 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5349 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5350 getF32Constant(DAG, 0x3e9a209a, dl)); 5351 5352 // Get the significand and build it into a floating-point number with 5353 // exponent of 1. 5354 SDValue X = GetSignificand(DAG, Op1, dl); 5355 5356 SDValue Log10ofMantissa; 5357 if (LimitFloatPrecision <= 6) { 5358 // For floating-point precision of 6: 5359 // 5360 // Log10ofMantissa = 5361 // -0.50419619f + 5362 // (0.60948995f - 0.10380950f * x) * x; 5363 // 5364 // error 0.0014886165, which is 6 bits 5365 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5366 getF32Constant(DAG, 0xbdd49a13, dl)); 5367 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5368 getF32Constant(DAG, 0x3f1c0789, dl)); 5369 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5370 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5371 getF32Constant(DAG, 0x3f011300, dl)); 5372 } else if (LimitFloatPrecision <= 12) { 5373 // For floating-point precision of 12: 5374 // 5375 // Log10ofMantissa = 5376 // -0.64831180f + 5377 // (0.91751397f + 5378 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5379 // 5380 // error 0.00019228036, which is better than 12 bits 5381 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5382 getF32Constant(DAG, 0x3d431f31, dl)); 5383 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5384 getF32Constant(DAG, 0x3ea21fb2, dl)); 5385 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5386 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5387 getF32Constant(DAG, 0x3f6ae232, dl)); 5388 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5389 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5390 getF32Constant(DAG, 0x3f25f7c3, dl)); 5391 } else { // LimitFloatPrecision <= 18 5392 // For floating-point precision of 18: 5393 // 5394 // Log10ofMantissa = 5395 // -0.84299375f + 5396 // (1.5327582f + 5397 // (-1.0688956f + 5398 // (0.49102474f + 5399 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5400 // 5401 // error 0.0000037995730, which is better than 18 bits 5402 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5403 getF32Constant(DAG, 0x3c5d51ce, dl)); 5404 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5405 getF32Constant(DAG, 0x3e00685a, dl)); 5406 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5407 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5408 getF32Constant(DAG, 0x3efb6798, dl)); 5409 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5410 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5411 getF32Constant(DAG, 0x3f88d192, dl)); 5412 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5413 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5414 getF32Constant(DAG, 0x3fc4316c, dl)); 5415 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5416 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5417 getF32Constant(DAG, 0x3f57ce70, dl)); 5418 } 5419 5420 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5421 } 5422 5423 // No special expansion. 5424 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5425 } 5426 5427 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5428 /// limited-precision mode. 5429 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5430 const TargetLowering &TLI, SDNodeFlags Flags) { 5431 if (Op.getValueType() == MVT::f32 && 5432 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5433 return getLimitedPrecisionExp2(Op, dl, DAG); 5434 5435 // No special expansion. 5436 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5437 } 5438 5439 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5440 /// limited-precision mode with x == 10.0f. 5441 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5442 SelectionDAG &DAG, const TargetLowering &TLI, 5443 SDNodeFlags Flags) { 5444 bool IsExp10 = false; 5445 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5446 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5447 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5448 APFloat Ten(10.0f); 5449 IsExp10 = LHSC->isExactlyValue(Ten); 5450 } 5451 } 5452 5453 // TODO: What fast-math-flags should be set on the FMUL node? 5454 if (IsExp10) { 5455 // Put the exponent in the right bit position for later addition to the 5456 // final result: 5457 // 5458 // #define LOG2OF10 3.3219281f 5459 // t0 = Op * LOG2OF10; 5460 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5461 getF32Constant(DAG, 0x40549a78, dl)); 5462 return getLimitedPrecisionExp2(t0, dl, DAG); 5463 } 5464 5465 // No special expansion. 5466 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5467 } 5468 5469 /// ExpandPowI - Expand a llvm.powi intrinsic. 5470 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5471 SelectionDAG &DAG) { 5472 // If RHS is a constant, we can expand this out to a multiplication tree if 5473 // it's beneficial on the target, otherwise we end up lowering to a call to 5474 // __powidf2 (for example). 5475 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5476 unsigned Val = RHSC->getSExtValue(); 5477 5478 // powi(x, 0) -> 1.0 5479 if (Val == 0) 5480 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5481 5482 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI( 5483 Val, DAG.shouldOptForSize())) { 5484 // Get the exponent as a positive value. 5485 if ((int)Val < 0) 5486 Val = -Val; 5487 // We use the simple binary decomposition method to generate the multiply 5488 // sequence. There are more optimal ways to do this (for example, 5489 // powi(x,15) generates one more multiply than it should), but this has 5490 // the benefit of being both really simple and much better than a libcall. 5491 SDValue Res; // Logically starts equal to 1.0 5492 SDValue CurSquare = LHS; 5493 // TODO: Intrinsics should have fast-math-flags that propagate to these 5494 // nodes. 5495 while (Val) { 5496 if (Val & 1) { 5497 if (Res.getNode()) 5498 Res = 5499 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare); 5500 else 5501 Res = CurSquare; // 1.0*CurSquare. 5502 } 5503 5504 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5505 CurSquare, CurSquare); 5506 Val >>= 1; 5507 } 5508 5509 // If the original was negative, invert the result, producing 1/(x*x*x). 5510 if (RHSC->getSExtValue() < 0) 5511 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5512 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5513 return Res; 5514 } 5515 } 5516 5517 // Otherwise, expand to a libcall. 5518 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5519 } 5520 5521 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5522 SDValue LHS, SDValue RHS, SDValue Scale, 5523 SelectionDAG &DAG, const TargetLowering &TLI) { 5524 EVT VT = LHS.getValueType(); 5525 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5526 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5527 LLVMContext &Ctx = *DAG.getContext(); 5528 5529 // If the type is legal but the operation isn't, this node might survive all 5530 // the way to operation legalization. If we end up there and we do not have 5531 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5532 // node. 5533 5534 // Coax the legalizer into expanding the node during type legalization instead 5535 // by bumping the size by one bit. This will force it to Promote, enabling the 5536 // early expansion and avoiding the need to expand later. 5537 5538 // We don't have to do this if Scale is 0; that can always be expanded, unless 5539 // it's a saturating signed operation. Those can experience true integer 5540 // division overflow, a case which we must avoid. 5541 5542 // FIXME: We wouldn't have to do this (or any of the early 5543 // expansion/promotion) if it was possible to expand a libcall of an 5544 // illegal type during operation legalization. But it's not, so things 5545 // get a bit hacky. 5546 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5547 if ((ScaleInt > 0 || (Saturating && Signed)) && 5548 (TLI.isTypeLegal(VT) || 5549 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5550 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5551 Opcode, VT, ScaleInt); 5552 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5553 EVT PromVT; 5554 if (VT.isScalarInteger()) 5555 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5556 else if (VT.isVector()) { 5557 PromVT = VT.getVectorElementType(); 5558 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5559 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5560 } else 5561 llvm_unreachable("Wrong VT for DIVFIX?"); 5562 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT); 5563 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT); 5564 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5565 // For saturating operations, we need to shift up the LHS to get the 5566 // proper saturation width, and then shift down again afterwards. 5567 if (Saturating) 5568 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5569 DAG.getConstant(1, DL, ShiftTy)); 5570 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5571 if (Saturating) 5572 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5573 DAG.getConstant(1, DL, ShiftTy)); 5574 return DAG.getZExtOrTrunc(Res, DL, VT); 5575 } 5576 } 5577 5578 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5579 } 5580 5581 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5582 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5583 static void 5584 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5585 const SDValue &N) { 5586 switch (N.getOpcode()) { 5587 case ISD::CopyFromReg: { 5588 SDValue Op = N.getOperand(1); 5589 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5590 Op.getValueType().getSizeInBits()); 5591 return; 5592 } 5593 case ISD::BITCAST: 5594 case ISD::AssertZext: 5595 case ISD::AssertSext: 5596 case ISD::TRUNCATE: 5597 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5598 return; 5599 case ISD::BUILD_PAIR: 5600 case ISD::BUILD_VECTOR: 5601 case ISD::CONCAT_VECTORS: 5602 for (SDValue Op : N->op_values()) 5603 getUnderlyingArgRegs(Regs, Op); 5604 return; 5605 default: 5606 return; 5607 } 5608 } 5609 5610 /// If the DbgValueInst is a dbg_value of a function argument, create the 5611 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5612 /// instruction selection, they will be inserted to the entry BB. 5613 /// We don't currently support this for variadic dbg_values, as they shouldn't 5614 /// appear for function arguments or in the prologue. 5615 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5616 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5617 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) { 5618 const Argument *Arg = dyn_cast<Argument>(V); 5619 if (!Arg) 5620 return false; 5621 5622 MachineFunction &MF = DAG.getMachineFunction(); 5623 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5624 5625 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind 5626 // we've been asked to pursue. 5627 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr, 5628 bool Indirect) { 5629 if (Reg.isVirtual() && MF.useDebugInstrRef()) { 5630 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF 5631 // pointing at the VReg, which will be patched up later. 5632 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF); 5633 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg( 5634 /* Reg */ Reg, /* isDef */ false, /* isImp */ false, 5635 /* isKill */ false, /* isDead */ false, 5636 /* isUndef */ false, /* isEarlyClobber */ false, 5637 /* SubReg */ 0, /* isDebug */ true)}); 5638 5639 auto *NewDIExpr = FragExpr; 5640 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into 5641 // the DIExpression. 5642 if (Indirect) 5643 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore); 5644 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0}); 5645 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops); 5646 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr); 5647 } else { 5648 // Create a completely standard DBG_VALUE. 5649 auto &Inst = TII->get(TargetOpcode::DBG_VALUE); 5650 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr); 5651 } 5652 }; 5653 5654 if (Kind == FuncArgumentDbgValueKind::Value) { 5655 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5656 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5657 // the entry block. 5658 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5659 if (!IsInEntryBlock) 5660 return false; 5661 5662 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5663 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5664 // variable that also is a param. 5665 // 5666 // Although, if we are at the top of the entry block already, we can still 5667 // emit using ArgDbgValue. This might catch some situations when the 5668 // dbg.value refers to an argument that isn't used in the entry block, so 5669 // any CopyToReg node would be optimized out and the only way to express 5670 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5671 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5672 // we should only emit as ArgDbgValue if the Variable is an argument to the 5673 // current function, and the dbg.value intrinsic is found in the entry 5674 // block. 5675 bool VariableIsFunctionInputArg = Variable->isParameter() && 5676 !DL->getInlinedAt(); 5677 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5678 if (!IsInPrologue && !VariableIsFunctionInputArg) 5679 return false; 5680 5681 // Here we assume that a function argument on IR level only can be used to 5682 // describe one input parameter on source level. If we for example have 5683 // source code like this 5684 // 5685 // struct A { long x, y; }; 5686 // void foo(struct A a, long b) { 5687 // ... 5688 // b = a.x; 5689 // ... 5690 // } 5691 // 5692 // and IR like this 5693 // 5694 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5695 // entry: 5696 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5697 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5698 // call void @llvm.dbg.value(metadata i32 %b, "b", 5699 // ... 5700 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5701 // ... 5702 // 5703 // then the last dbg.value is describing a parameter "b" using a value that 5704 // is an argument. But since we already has used %a1 to describe a parameter 5705 // we should not handle that last dbg.value here (that would result in an 5706 // incorrect hoisting of the DBG_VALUE to the function entry). 5707 // Notice that we allow one dbg.value per IR level argument, to accommodate 5708 // for the situation with fragments above. 5709 if (VariableIsFunctionInputArg) { 5710 unsigned ArgNo = Arg->getArgNo(); 5711 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5712 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5713 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5714 return false; 5715 FuncInfo.DescribedArgs.set(ArgNo); 5716 } 5717 } 5718 5719 bool IsIndirect = false; 5720 std::optional<MachineOperand> Op; 5721 // Some arguments' frame index is recorded during argument lowering. 5722 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5723 if (FI != std::numeric_limits<int>::max()) 5724 Op = MachineOperand::CreateFI(FI); 5725 5726 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5727 if (!Op && N.getNode()) { 5728 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5729 Register Reg; 5730 if (ArgRegsAndSizes.size() == 1) 5731 Reg = ArgRegsAndSizes.front().first; 5732 5733 if (Reg && Reg.isVirtual()) { 5734 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5735 Register PR = RegInfo.getLiveInPhysReg(Reg); 5736 if (PR) 5737 Reg = PR; 5738 } 5739 if (Reg) { 5740 Op = MachineOperand::CreateReg(Reg, false); 5741 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5742 } 5743 } 5744 5745 if (!Op && N.getNode()) { 5746 // Check if frame index is available. 5747 SDValue LCandidate = peekThroughBitcasts(N); 5748 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5749 if (FrameIndexSDNode *FINode = 5750 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5751 Op = MachineOperand::CreateFI(FINode->getIndex()); 5752 } 5753 5754 if (!Op) { 5755 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5756 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5757 SplitRegs) { 5758 unsigned Offset = 0; 5759 for (const auto &RegAndSize : SplitRegs) { 5760 // If the expression is already a fragment, the current register 5761 // offset+size might extend beyond the fragment. In this case, only 5762 // the register bits that are inside the fragment are relevant. 5763 int RegFragmentSizeInBits = RegAndSize.second; 5764 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5765 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5766 // The register is entirely outside the expression fragment, 5767 // so is irrelevant for debug info. 5768 if (Offset >= ExprFragmentSizeInBits) 5769 break; 5770 // The register is partially outside the expression fragment, only 5771 // the low bits within the fragment are relevant for debug info. 5772 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5773 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5774 } 5775 } 5776 5777 auto FragmentExpr = DIExpression::createFragmentExpression( 5778 Expr, Offset, RegFragmentSizeInBits); 5779 Offset += RegAndSize.second; 5780 // If a valid fragment expression cannot be created, the variable's 5781 // correct value cannot be determined and so it is set as Undef. 5782 if (!FragmentExpr) { 5783 SDDbgValue *SDV = DAG.getConstantDbgValue( 5784 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5785 DAG.AddDbgValue(SDV, false); 5786 continue; 5787 } 5788 MachineInstr *NewMI = 5789 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, 5790 Kind != FuncArgumentDbgValueKind::Value); 5791 FuncInfo.ArgDbgValues.push_back(NewMI); 5792 } 5793 }; 5794 5795 // Check if ValueMap has reg number. 5796 DenseMap<const Value *, Register>::const_iterator 5797 VMI = FuncInfo.ValueMap.find(V); 5798 if (VMI != FuncInfo.ValueMap.end()) { 5799 const auto &TLI = DAG.getTargetLoweringInfo(); 5800 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5801 V->getType(), std::nullopt); 5802 if (RFV.occupiesMultipleRegs()) { 5803 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5804 return true; 5805 } 5806 5807 Op = MachineOperand::CreateReg(VMI->second, false); 5808 IsIndirect = Kind != FuncArgumentDbgValueKind::Value; 5809 } else if (ArgRegsAndSizes.size() > 1) { 5810 // This was split due to the calling convention, and no virtual register 5811 // mapping exists for the value. 5812 splitMultiRegDbgValue(ArgRegsAndSizes); 5813 return true; 5814 } 5815 } 5816 5817 if (!Op) 5818 return false; 5819 5820 // If the expression refers to the entry value of an Argument, use the 5821 // corresponding livein physical register. As per the Verifier, this is only 5822 // allowed for swiftasync Arguments. 5823 if (Op->isReg() && Expr->isEntryValue()) { 5824 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync)); 5825 auto OpReg = Op->getReg(); 5826 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins()) 5827 if (OpReg == VirtReg || OpReg == PhysReg) { 5828 SDDbgValue *SDV = DAG.getVRegDbgValue( 5829 Variable, Expr, PhysReg, 5830 Kind != FuncArgumentDbgValueKind::Value /*is indirect*/, DL, 5831 SDNodeOrder); 5832 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/); 5833 return true; 5834 } 5835 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but " 5836 "couldn't find a physical register\n"); 5837 return true; 5838 } 5839 5840 assert(Variable->isValidLocationForIntrinsic(DL) && 5841 "Expected inlined-at fields to agree"); 5842 MachineInstr *NewMI = nullptr; 5843 5844 if (Op->isReg()) 5845 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect); 5846 else 5847 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op, 5848 Variable, Expr); 5849 5850 // Otherwise, use ArgDbgValues. 5851 FuncInfo.ArgDbgValues.push_back(NewMI); 5852 return true; 5853 } 5854 5855 /// Return the appropriate SDDbgValue based on N. 5856 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5857 DILocalVariable *Variable, 5858 DIExpression *Expr, 5859 const DebugLoc &dl, 5860 unsigned DbgSDNodeOrder) { 5861 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5862 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5863 // stack slot locations. 5864 // 5865 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5866 // debug values here after optimization: 5867 // 5868 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5869 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5870 // 5871 // Both describe the direct values of their associated variables. 5872 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5873 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5874 } 5875 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5876 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5877 } 5878 5879 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5880 switch (Intrinsic) { 5881 case Intrinsic::smul_fix: 5882 return ISD::SMULFIX; 5883 case Intrinsic::umul_fix: 5884 return ISD::UMULFIX; 5885 case Intrinsic::smul_fix_sat: 5886 return ISD::SMULFIXSAT; 5887 case Intrinsic::umul_fix_sat: 5888 return ISD::UMULFIXSAT; 5889 case Intrinsic::sdiv_fix: 5890 return ISD::SDIVFIX; 5891 case Intrinsic::udiv_fix: 5892 return ISD::UDIVFIX; 5893 case Intrinsic::sdiv_fix_sat: 5894 return ISD::SDIVFIXSAT; 5895 case Intrinsic::udiv_fix_sat: 5896 return ISD::UDIVFIXSAT; 5897 default: 5898 llvm_unreachable("Unhandled fixed point intrinsic"); 5899 } 5900 } 5901 5902 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5903 const char *FunctionName) { 5904 assert(FunctionName && "FunctionName must not be nullptr"); 5905 SDValue Callee = DAG.getExternalSymbol( 5906 FunctionName, 5907 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5908 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 5909 } 5910 5911 /// Given a @llvm.call.preallocated.setup, return the corresponding 5912 /// preallocated call. 5913 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5914 assert(cast<CallBase>(PreallocatedSetup) 5915 ->getCalledFunction() 5916 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5917 "expected call_preallocated_setup Value"); 5918 for (const auto *U : PreallocatedSetup->users()) { 5919 auto *UseCall = cast<CallBase>(U); 5920 const Function *Fn = UseCall->getCalledFunction(); 5921 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5922 return UseCall; 5923 } 5924 } 5925 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5926 } 5927 5928 /// Lower the call to the specified intrinsic function. 5929 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5930 unsigned Intrinsic) { 5931 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5932 SDLoc sdl = getCurSDLoc(); 5933 DebugLoc dl = getCurDebugLoc(); 5934 SDValue Res; 5935 5936 SDNodeFlags Flags; 5937 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5938 Flags.copyFMF(*FPOp); 5939 5940 switch (Intrinsic) { 5941 default: 5942 // By default, turn this into a target intrinsic node. 5943 visitTargetIntrinsic(I, Intrinsic); 5944 return; 5945 case Intrinsic::vscale: { 5946 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5947 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1))); 5948 return; 5949 } 5950 case Intrinsic::vastart: visitVAStart(I); return; 5951 case Intrinsic::vaend: visitVAEnd(I); return; 5952 case Intrinsic::vacopy: visitVACopy(I); return; 5953 case Intrinsic::returnaddress: 5954 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5955 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5956 getValue(I.getArgOperand(0)))); 5957 return; 5958 case Intrinsic::addressofreturnaddress: 5959 setValue(&I, 5960 DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5961 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5962 return; 5963 case Intrinsic::sponentry: 5964 setValue(&I, 5965 DAG.getNode(ISD::SPONENTRY, sdl, 5966 TLI.getValueType(DAG.getDataLayout(), I.getType()))); 5967 return; 5968 case Intrinsic::frameaddress: 5969 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5970 TLI.getFrameIndexTy(DAG.getDataLayout()), 5971 getValue(I.getArgOperand(0)))); 5972 return; 5973 case Intrinsic::read_volatile_register: 5974 case Intrinsic::read_register: { 5975 Value *Reg = I.getArgOperand(0); 5976 SDValue Chain = getRoot(); 5977 SDValue RegName = 5978 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5979 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5980 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5981 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5982 setValue(&I, Res); 5983 DAG.setRoot(Res.getValue(1)); 5984 return; 5985 } 5986 case Intrinsic::write_register: { 5987 Value *Reg = I.getArgOperand(0); 5988 Value *RegValue = I.getArgOperand(1); 5989 SDValue Chain = getRoot(); 5990 SDValue RegName = 5991 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5992 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5993 RegName, getValue(RegValue))); 5994 return; 5995 } 5996 case Intrinsic::memcpy: { 5997 const auto &MCI = cast<MemCpyInst>(I); 5998 SDValue Op1 = getValue(I.getArgOperand(0)); 5999 SDValue Op2 = getValue(I.getArgOperand(1)); 6000 SDValue Op3 = getValue(I.getArgOperand(2)); 6001 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 6002 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6003 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6004 Align Alignment = std::min(DstAlign, SrcAlign); 6005 bool isVol = MCI.isVolatile(); 6006 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6007 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6008 // node. 6009 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6010 SDValue MC = DAG.getMemcpy( 6011 Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6012 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)), 6013 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6014 updateDAGForMaybeTailCall(MC); 6015 return; 6016 } 6017 case Intrinsic::memcpy_inline: { 6018 const auto &MCI = cast<MemCpyInlineInst>(I); 6019 SDValue Dst = getValue(I.getArgOperand(0)); 6020 SDValue Src = getValue(I.getArgOperand(1)); 6021 SDValue Size = getValue(I.getArgOperand(2)); 6022 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 6023 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 6024 Align DstAlign = MCI.getDestAlign().valueOrOne(); 6025 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 6026 Align Alignment = std::min(DstAlign, SrcAlign); 6027 bool isVol = MCI.isVolatile(); 6028 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6029 // FIXME: Support passing different dest/src alignments to the memcpy DAG 6030 // node. 6031 SDValue MC = DAG.getMemcpy( 6032 getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 6033 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)), 6034 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA); 6035 updateDAGForMaybeTailCall(MC); 6036 return; 6037 } 6038 case Intrinsic::memset: { 6039 const auto &MSI = cast<MemSetInst>(I); 6040 SDValue Op1 = getValue(I.getArgOperand(0)); 6041 SDValue Op2 = getValue(I.getArgOperand(1)); 6042 SDValue Op3 = getValue(I.getArgOperand(2)); 6043 // @llvm.memset defines 0 and 1 to both mean no alignment. 6044 Align Alignment = MSI.getDestAlign().valueOrOne(); 6045 bool isVol = MSI.isVolatile(); 6046 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6047 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6048 SDValue MS = DAG.getMemset( 6049 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false, 6050 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata()); 6051 updateDAGForMaybeTailCall(MS); 6052 return; 6053 } 6054 case Intrinsic::memset_inline: { 6055 const auto &MSII = cast<MemSetInlineInst>(I); 6056 SDValue Dst = getValue(I.getArgOperand(0)); 6057 SDValue Value = getValue(I.getArgOperand(1)); 6058 SDValue Size = getValue(I.getArgOperand(2)); 6059 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size"); 6060 // @llvm.memset defines 0 and 1 to both mean no alignment. 6061 Align DstAlign = MSII.getDestAlign().valueOrOne(); 6062 bool isVol = MSII.isVolatile(); 6063 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6064 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6065 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol, 6066 /* AlwaysInline */ true, isTC, 6067 MachinePointerInfo(I.getArgOperand(0)), 6068 I.getAAMetadata()); 6069 updateDAGForMaybeTailCall(MC); 6070 return; 6071 } 6072 case Intrinsic::memmove: { 6073 const auto &MMI = cast<MemMoveInst>(I); 6074 SDValue Op1 = getValue(I.getArgOperand(0)); 6075 SDValue Op2 = getValue(I.getArgOperand(1)); 6076 SDValue Op3 = getValue(I.getArgOperand(2)); 6077 // @llvm.memmove defines 0 and 1 to both mean no alignment. 6078 Align DstAlign = MMI.getDestAlign().valueOrOne(); 6079 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 6080 Align Alignment = std::min(DstAlign, SrcAlign); 6081 bool isVol = MMI.isVolatile(); 6082 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6083 // FIXME: Support passing different dest/src alignments to the memmove DAG 6084 // node. 6085 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 6086 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 6087 isTC, MachinePointerInfo(I.getArgOperand(0)), 6088 MachinePointerInfo(I.getArgOperand(1)), 6089 I.getAAMetadata(), AA); 6090 updateDAGForMaybeTailCall(MM); 6091 return; 6092 } 6093 case Intrinsic::memcpy_element_unordered_atomic: { 6094 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 6095 SDValue Dst = getValue(MI.getRawDest()); 6096 SDValue Src = getValue(MI.getRawSource()); 6097 SDValue Length = getValue(MI.getLength()); 6098 6099 Type *LengthTy = MI.getLength()->getType(); 6100 unsigned ElemSz = MI.getElementSizeInBytes(); 6101 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6102 SDValue MC = 6103 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6104 isTC, MachinePointerInfo(MI.getRawDest()), 6105 MachinePointerInfo(MI.getRawSource())); 6106 updateDAGForMaybeTailCall(MC); 6107 return; 6108 } 6109 case Intrinsic::memmove_element_unordered_atomic: { 6110 auto &MI = cast<AtomicMemMoveInst>(I); 6111 SDValue Dst = getValue(MI.getRawDest()); 6112 SDValue Src = getValue(MI.getRawSource()); 6113 SDValue Length = getValue(MI.getLength()); 6114 6115 Type *LengthTy = MI.getLength()->getType(); 6116 unsigned ElemSz = MI.getElementSizeInBytes(); 6117 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6118 SDValue MC = 6119 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz, 6120 isTC, MachinePointerInfo(MI.getRawDest()), 6121 MachinePointerInfo(MI.getRawSource())); 6122 updateDAGForMaybeTailCall(MC); 6123 return; 6124 } 6125 case Intrinsic::memset_element_unordered_atomic: { 6126 auto &MI = cast<AtomicMemSetInst>(I); 6127 SDValue Dst = getValue(MI.getRawDest()); 6128 SDValue Val = getValue(MI.getValue()); 6129 SDValue Length = getValue(MI.getLength()); 6130 6131 Type *LengthTy = MI.getLength()->getType(); 6132 unsigned ElemSz = MI.getElementSizeInBytes(); 6133 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 6134 SDValue MC = 6135 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz, 6136 isTC, MachinePointerInfo(MI.getRawDest())); 6137 updateDAGForMaybeTailCall(MC); 6138 return; 6139 } 6140 case Intrinsic::call_preallocated_setup: { 6141 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 6142 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6143 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 6144 getRoot(), SrcValue); 6145 setValue(&I, Res); 6146 DAG.setRoot(Res); 6147 return; 6148 } 6149 case Intrinsic::call_preallocated_arg: { 6150 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 6151 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 6152 SDValue Ops[3]; 6153 Ops[0] = getRoot(); 6154 Ops[1] = SrcValue; 6155 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 6156 MVT::i32); // arg index 6157 SDValue Res = DAG.getNode( 6158 ISD::PREALLOCATED_ARG, sdl, 6159 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 6160 setValue(&I, Res); 6161 DAG.setRoot(Res.getValue(1)); 6162 return; 6163 } 6164 case Intrinsic::dbg_declare: { 6165 const auto &DI = cast<DbgDeclareInst>(I); 6166 // Debug intrinsics are handled separately in assignment tracking mode. 6167 // Some intrinsics are handled right after Argument lowering. 6168 if (AssignmentTrackingEnabled || 6169 FuncInfo.PreprocessedDbgDeclares.count(&DI)) 6170 return; 6171 // Assume dbg.declare can not currently use DIArgList, i.e. 6172 // it is non-variadic. 6173 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList"); 6174 DILocalVariable *Variable = DI.getVariable(); 6175 DIExpression *Expression = DI.getExpression(); 6176 dropDanglingDebugInfo(Variable, Expression); 6177 assert(Variable && "Missing variable"); 6178 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 6179 << "\n"); 6180 // Check if address has undef value. 6181 const Value *Address = DI.getVariableLocationOp(0); 6182 if (!Address || isa<UndefValue>(Address) || 6183 (Address->use_empty() && !isa<Argument>(Address))) { 6184 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6185 << " (bad/undef/unused-arg address)\n"); 6186 return; 6187 } 6188 6189 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 6190 6191 SDValue &N = NodeMap[Address]; 6192 if (!N.getNode() && isa<Argument>(Address)) 6193 // Check unused arguments map. 6194 N = UnusedArgNodeMap[Address]; 6195 SDDbgValue *SDV; 6196 if (N.getNode()) { 6197 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 6198 Address = BCI->getOperand(0); 6199 // Parameters are handled specially. 6200 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 6201 if (isParameter && FINode) { 6202 // Byval parameter. We have a frame index at this point. 6203 SDV = 6204 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 6205 /*IsIndirect*/ true, dl, SDNodeOrder); 6206 } else if (isa<Argument>(Address)) { 6207 // Address is an argument, so try to emit its dbg value using 6208 // virtual register info from the FuncInfo.ValueMap. 6209 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6210 FuncArgumentDbgValueKind::Declare, N); 6211 return; 6212 } else { 6213 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 6214 true, dl, SDNodeOrder); 6215 } 6216 DAG.AddDbgValue(SDV, isParameter); 6217 } else { 6218 // If Address is an argument then try to emit its dbg value using 6219 // virtual register info from the FuncInfo.ValueMap. 6220 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 6221 FuncArgumentDbgValueKind::Declare, N)) { 6222 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 6223 << " (could not emit func-arg dbg_value)\n"); 6224 } 6225 } 6226 return; 6227 } 6228 case Intrinsic::dbg_label: { 6229 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 6230 DILabel *Label = DI.getLabel(); 6231 assert(Label && "Missing label"); 6232 6233 SDDbgLabel *SDV; 6234 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 6235 DAG.AddDbgLabel(SDV); 6236 return; 6237 } 6238 case Intrinsic::dbg_assign: { 6239 // Debug intrinsics are handled seperately in assignment tracking mode. 6240 if (AssignmentTrackingEnabled) 6241 return; 6242 // If assignment tracking hasn't been enabled then fall through and treat 6243 // the dbg.assign as a dbg.value. 6244 [[fallthrough]]; 6245 } 6246 case Intrinsic::dbg_value: { 6247 // Debug intrinsics are handled seperately in assignment tracking mode. 6248 if (AssignmentTrackingEnabled) 6249 return; 6250 const DbgValueInst &DI = cast<DbgValueInst>(I); 6251 assert(DI.getVariable() && "Missing variable"); 6252 6253 DILocalVariable *Variable = DI.getVariable(); 6254 DIExpression *Expression = DI.getExpression(); 6255 dropDanglingDebugInfo(Variable, Expression); 6256 6257 if (DI.isKillLocation()) { 6258 handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder); 6259 return; 6260 } 6261 6262 SmallVector<Value *, 4> Values(DI.getValues()); 6263 if (Values.empty()) 6264 return; 6265 6266 bool IsVariadic = DI.hasArgList(); 6267 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(), 6268 SDNodeOrder, IsVariadic)) 6269 addDanglingDebugInfo(&DI, SDNodeOrder); 6270 return; 6271 } 6272 6273 case Intrinsic::eh_typeid_for: { 6274 // Find the type id for the given typeinfo. 6275 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6276 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6277 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6278 setValue(&I, Res); 6279 return; 6280 } 6281 6282 case Intrinsic::eh_return_i32: 6283 case Intrinsic::eh_return_i64: 6284 DAG.getMachineFunction().setCallsEHReturn(true); 6285 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6286 MVT::Other, 6287 getControlRoot(), 6288 getValue(I.getArgOperand(0)), 6289 getValue(I.getArgOperand(1)))); 6290 return; 6291 case Intrinsic::eh_unwind_init: 6292 DAG.getMachineFunction().setCallsUnwindInit(true); 6293 return; 6294 case Intrinsic::eh_dwarf_cfa: 6295 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6296 TLI.getPointerTy(DAG.getDataLayout()), 6297 getValue(I.getArgOperand(0)))); 6298 return; 6299 case Intrinsic::eh_sjlj_callsite: { 6300 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6301 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0)); 6302 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6303 6304 MMI.setCurrentCallSite(CI->getZExtValue()); 6305 return; 6306 } 6307 case Intrinsic::eh_sjlj_functioncontext: { 6308 // Get and store the index of the function context. 6309 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6310 AllocaInst *FnCtx = 6311 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6312 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6313 MFI.setFunctionContextIndex(FI); 6314 return; 6315 } 6316 case Intrinsic::eh_sjlj_setjmp: { 6317 SDValue Ops[2]; 6318 Ops[0] = getRoot(); 6319 Ops[1] = getValue(I.getArgOperand(0)); 6320 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6321 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6322 setValue(&I, Op.getValue(0)); 6323 DAG.setRoot(Op.getValue(1)); 6324 return; 6325 } 6326 case Intrinsic::eh_sjlj_longjmp: 6327 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6328 getRoot(), getValue(I.getArgOperand(0)))); 6329 return; 6330 case Intrinsic::eh_sjlj_setup_dispatch: 6331 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6332 getRoot())); 6333 return; 6334 case Intrinsic::masked_gather: 6335 visitMaskedGather(I); 6336 return; 6337 case Intrinsic::masked_load: 6338 visitMaskedLoad(I); 6339 return; 6340 case Intrinsic::masked_scatter: 6341 visitMaskedScatter(I); 6342 return; 6343 case Intrinsic::masked_store: 6344 visitMaskedStore(I); 6345 return; 6346 case Intrinsic::masked_expandload: 6347 visitMaskedLoad(I, true /* IsExpanding */); 6348 return; 6349 case Intrinsic::masked_compressstore: 6350 visitMaskedStore(I, true /* IsCompressing */); 6351 return; 6352 case Intrinsic::powi: 6353 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6354 getValue(I.getArgOperand(1)), DAG)); 6355 return; 6356 case Intrinsic::log: 6357 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6358 return; 6359 case Intrinsic::log2: 6360 setValue(&I, 6361 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6362 return; 6363 case Intrinsic::log10: 6364 setValue(&I, 6365 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6366 return; 6367 case Intrinsic::exp: 6368 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6369 return; 6370 case Intrinsic::exp2: 6371 setValue(&I, 6372 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6373 return; 6374 case Intrinsic::pow: 6375 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6376 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6377 return; 6378 case Intrinsic::sqrt: 6379 case Intrinsic::fabs: 6380 case Intrinsic::sin: 6381 case Intrinsic::cos: 6382 case Intrinsic::floor: 6383 case Intrinsic::ceil: 6384 case Intrinsic::trunc: 6385 case Intrinsic::rint: 6386 case Intrinsic::nearbyint: 6387 case Intrinsic::round: 6388 case Intrinsic::roundeven: 6389 case Intrinsic::canonicalize: { 6390 unsigned Opcode; 6391 switch (Intrinsic) { 6392 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6393 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6394 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6395 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6396 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6397 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6398 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6399 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6400 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6401 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6402 case Intrinsic::round: Opcode = ISD::FROUND; break; 6403 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6404 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6405 } 6406 6407 setValue(&I, DAG.getNode(Opcode, sdl, 6408 getValue(I.getArgOperand(0)).getValueType(), 6409 getValue(I.getArgOperand(0)), Flags)); 6410 return; 6411 } 6412 case Intrinsic::lround: 6413 case Intrinsic::llround: 6414 case Intrinsic::lrint: 6415 case Intrinsic::llrint: { 6416 unsigned Opcode; 6417 switch (Intrinsic) { 6418 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6419 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6420 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6421 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6422 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6423 } 6424 6425 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6426 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6427 getValue(I.getArgOperand(0)))); 6428 return; 6429 } 6430 case Intrinsic::minnum: 6431 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6432 getValue(I.getArgOperand(0)).getValueType(), 6433 getValue(I.getArgOperand(0)), 6434 getValue(I.getArgOperand(1)), Flags)); 6435 return; 6436 case Intrinsic::maxnum: 6437 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6438 getValue(I.getArgOperand(0)).getValueType(), 6439 getValue(I.getArgOperand(0)), 6440 getValue(I.getArgOperand(1)), Flags)); 6441 return; 6442 case Intrinsic::minimum: 6443 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6444 getValue(I.getArgOperand(0)).getValueType(), 6445 getValue(I.getArgOperand(0)), 6446 getValue(I.getArgOperand(1)), Flags)); 6447 return; 6448 case Intrinsic::maximum: 6449 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6450 getValue(I.getArgOperand(0)).getValueType(), 6451 getValue(I.getArgOperand(0)), 6452 getValue(I.getArgOperand(1)), Flags)); 6453 return; 6454 case Intrinsic::copysign: 6455 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6456 getValue(I.getArgOperand(0)).getValueType(), 6457 getValue(I.getArgOperand(0)), 6458 getValue(I.getArgOperand(1)), Flags)); 6459 return; 6460 case Intrinsic::ldexp: 6461 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl, 6462 getValue(I.getArgOperand(0)).getValueType(), 6463 getValue(I.getArgOperand(0)), 6464 getValue(I.getArgOperand(1)), Flags)); 6465 return; 6466 case Intrinsic::arithmetic_fence: { 6467 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl, 6468 getValue(I.getArgOperand(0)).getValueType(), 6469 getValue(I.getArgOperand(0)), Flags)); 6470 return; 6471 } 6472 case Intrinsic::fma: 6473 setValue(&I, DAG.getNode( 6474 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6475 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6476 getValue(I.getArgOperand(2)), Flags)); 6477 return; 6478 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6479 case Intrinsic::INTRINSIC: 6480 #include "llvm/IR/ConstrainedOps.def" 6481 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6482 return; 6483 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6484 #include "llvm/IR/VPIntrinsics.def" 6485 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6486 return; 6487 case Intrinsic::fptrunc_round: { 6488 // Get the last argument, the metadata and convert it to an integer in the 6489 // call 6490 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata(); 6491 std::optional<RoundingMode> RoundMode = 6492 convertStrToRoundingMode(cast<MDString>(MD)->getString()); 6493 6494 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6495 6496 // Propagate fast-math-flags from IR to node(s). 6497 SDNodeFlags Flags; 6498 Flags.copyFMF(*cast<FPMathOperator>(&I)); 6499 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 6500 6501 SDValue Result; 6502 Result = DAG.getNode( 6503 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)), 6504 DAG.getTargetConstant((int)*RoundMode, sdl, 6505 TLI.getPointerTy(DAG.getDataLayout()))); 6506 setValue(&I, Result); 6507 6508 return; 6509 } 6510 case Intrinsic::fmuladd: { 6511 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6512 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6513 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6514 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6515 getValue(I.getArgOperand(0)).getValueType(), 6516 getValue(I.getArgOperand(0)), 6517 getValue(I.getArgOperand(1)), 6518 getValue(I.getArgOperand(2)), Flags)); 6519 } else { 6520 // TODO: Intrinsic calls should have fast-math-flags. 6521 SDValue Mul = DAG.getNode( 6522 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6523 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6524 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6525 getValue(I.getArgOperand(0)).getValueType(), 6526 Mul, getValue(I.getArgOperand(2)), Flags); 6527 setValue(&I, Add); 6528 } 6529 return; 6530 } 6531 case Intrinsic::convert_to_fp16: 6532 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6533 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6534 getValue(I.getArgOperand(0)), 6535 DAG.getTargetConstant(0, sdl, 6536 MVT::i32)))); 6537 return; 6538 case Intrinsic::convert_from_fp16: 6539 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6540 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6541 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6542 getValue(I.getArgOperand(0))))); 6543 return; 6544 case Intrinsic::fptosi_sat: { 6545 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6546 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT, 6547 getValue(I.getArgOperand(0)), 6548 DAG.getValueType(VT.getScalarType()))); 6549 return; 6550 } 6551 case Intrinsic::fptoui_sat: { 6552 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6553 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT, 6554 getValue(I.getArgOperand(0)), 6555 DAG.getValueType(VT.getScalarType()))); 6556 return; 6557 } 6558 case Intrinsic::set_rounding: 6559 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6560 {getRoot(), getValue(I.getArgOperand(0))}); 6561 setValue(&I, Res); 6562 DAG.setRoot(Res.getValue(0)); 6563 return; 6564 case Intrinsic::is_fpclass: { 6565 const DataLayout DLayout = DAG.getDataLayout(); 6566 EVT DestVT = TLI.getValueType(DLayout, I.getType()); 6567 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType()); 6568 FPClassTest Test = static_cast<FPClassTest>( 6569 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 6570 MachineFunction &MF = DAG.getMachineFunction(); 6571 const Function &F = MF.getFunction(); 6572 SDValue Op = getValue(I.getArgOperand(0)); 6573 SDNodeFlags Flags; 6574 Flags.setNoFPExcept( 6575 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP)); 6576 // If ISD::IS_FPCLASS should be expanded, do it right now, because the 6577 // expansion can use illegal types. Making expansion early allows 6578 // legalizing these types prior to selection. 6579 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) { 6580 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG); 6581 setValue(&I, Result); 6582 return; 6583 } 6584 6585 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32); 6586 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags); 6587 setValue(&I, V); 6588 return; 6589 } 6590 case Intrinsic::get_fpenv: { 6591 const DataLayout DLayout = DAG.getDataLayout(); 6592 EVT EnvVT = TLI.getValueType(DLayout, I.getType()); 6593 Align TempAlign = DAG.getEVTAlign(EnvVT); 6594 SDValue Chain = getRoot(); 6595 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node 6596 // and temporary storage in stack. 6597 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) { 6598 Res = DAG.getNode( 6599 ISD::GET_FPENV, sdl, 6600 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6601 MVT::Other), 6602 Chain); 6603 } else { 6604 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6605 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6606 auto MPI = 6607 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6608 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6609 MPI, MachineMemOperand::MOStore, MemoryLocation::UnknownSize, 6610 TempAlign); 6611 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6612 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI); 6613 } 6614 setValue(&I, Res); 6615 DAG.setRoot(Res.getValue(1)); 6616 return; 6617 } 6618 case Intrinsic::set_fpenv: { 6619 const DataLayout DLayout = DAG.getDataLayout(); 6620 SDValue Env = getValue(I.getArgOperand(0)); 6621 EVT EnvVT = Env.getValueType(); 6622 Align TempAlign = DAG.getEVTAlign(EnvVT); 6623 SDValue Chain = getRoot(); 6624 // If SET_FPENV is custom or legal, use it. Otherwise use loading 6625 // environment from memory. 6626 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) { 6627 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env); 6628 } else { 6629 // Allocate space in stack, copy environment bits into it and use this 6630 // memory in SET_FPENV_MEM. 6631 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value()); 6632 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex(); 6633 auto MPI = 6634 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 6635 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign, 6636 MachineMemOperand::MOStore); 6637 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 6638 MPI, MachineMemOperand::MOLoad, MemoryLocation::UnknownSize, 6639 TempAlign); 6640 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO); 6641 } 6642 DAG.setRoot(Chain); 6643 return; 6644 } 6645 case Intrinsic::reset_fpenv: 6646 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot())); 6647 return; 6648 case Intrinsic::pcmarker: { 6649 SDValue Tmp = getValue(I.getArgOperand(0)); 6650 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6651 return; 6652 } 6653 case Intrinsic::readcyclecounter: { 6654 SDValue Op = getRoot(); 6655 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6656 DAG.getVTList(MVT::i64, MVT::Other), Op); 6657 setValue(&I, Res); 6658 DAG.setRoot(Res.getValue(1)); 6659 return; 6660 } 6661 case Intrinsic::bitreverse: 6662 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6663 getValue(I.getArgOperand(0)).getValueType(), 6664 getValue(I.getArgOperand(0)))); 6665 return; 6666 case Intrinsic::bswap: 6667 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6668 getValue(I.getArgOperand(0)).getValueType(), 6669 getValue(I.getArgOperand(0)))); 6670 return; 6671 case Intrinsic::cttz: { 6672 SDValue Arg = getValue(I.getArgOperand(0)); 6673 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6674 EVT Ty = Arg.getValueType(); 6675 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6676 sdl, Ty, Arg)); 6677 return; 6678 } 6679 case Intrinsic::ctlz: { 6680 SDValue Arg = getValue(I.getArgOperand(0)); 6681 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6682 EVT Ty = Arg.getValueType(); 6683 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6684 sdl, Ty, Arg)); 6685 return; 6686 } 6687 case Intrinsic::ctpop: { 6688 SDValue Arg = getValue(I.getArgOperand(0)); 6689 EVT Ty = Arg.getValueType(); 6690 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6691 return; 6692 } 6693 case Intrinsic::fshl: 6694 case Intrinsic::fshr: { 6695 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6696 SDValue X = getValue(I.getArgOperand(0)); 6697 SDValue Y = getValue(I.getArgOperand(1)); 6698 SDValue Z = getValue(I.getArgOperand(2)); 6699 EVT VT = X.getValueType(); 6700 6701 if (X == Y) { 6702 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6703 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6704 } else { 6705 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6706 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6707 } 6708 return; 6709 } 6710 case Intrinsic::sadd_sat: { 6711 SDValue Op1 = getValue(I.getArgOperand(0)); 6712 SDValue Op2 = getValue(I.getArgOperand(1)); 6713 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6714 return; 6715 } 6716 case Intrinsic::uadd_sat: { 6717 SDValue Op1 = getValue(I.getArgOperand(0)); 6718 SDValue Op2 = getValue(I.getArgOperand(1)); 6719 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6720 return; 6721 } 6722 case Intrinsic::ssub_sat: { 6723 SDValue Op1 = getValue(I.getArgOperand(0)); 6724 SDValue Op2 = getValue(I.getArgOperand(1)); 6725 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6726 return; 6727 } 6728 case Intrinsic::usub_sat: { 6729 SDValue Op1 = getValue(I.getArgOperand(0)); 6730 SDValue Op2 = getValue(I.getArgOperand(1)); 6731 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6732 return; 6733 } 6734 case Intrinsic::sshl_sat: { 6735 SDValue Op1 = getValue(I.getArgOperand(0)); 6736 SDValue Op2 = getValue(I.getArgOperand(1)); 6737 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6738 return; 6739 } 6740 case Intrinsic::ushl_sat: { 6741 SDValue Op1 = getValue(I.getArgOperand(0)); 6742 SDValue Op2 = getValue(I.getArgOperand(1)); 6743 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6744 return; 6745 } 6746 case Intrinsic::smul_fix: 6747 case Intrinsic::umul_fix: 6748 case Intrinsic::smul_fix_sat: 6749 case Intrinsic::umul_fix_sat: { 6750 SDValue Op1 = getValue(I.getArgOperand(0)); 6751 SDValue Op2 = getValue(I.getArgOperand(1)); 6752 SDValue Op3 = getValue(I.getArgOperand(2)); 6753 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6754 Op1.getValueType(), Op1, Op2, Op3)); 6755 return; 6756 } 6757 case Intrinsic::sdiv_fix: 6758 case Intrinsic::udiv_fix: 6759 case Intrinsic::sdiv_fix_sat: 6760 case Intrinsic::udiv_fix_sat: { 6761 SDValue Op1 = getValue(I.getArgOperand(0)); 6762 SDValue Op2 = getValue(I.getArgOperand(1)); 6763 SDValue Op3 = getValue(I.getArgOperand(2)); 6764 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6765 Op1, Op2, Op3, DAG, TLI)); 6766 return; 6767 } 6768 case Intrinsic::smax: { 6769 SDValue Op1 = getValue(I.getArgOperand(0)); 6770 SDValue Op2 = getValue(I.getArgOperand(1)); 6771 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6772 return; 6773 } 6774 case Intrinsic::smin: { 6775 SDValue Op1 = getValue(I.getArgOperand(0)); 6776 SDValue Op2 = getValue(I.getArgOperand(1)); 6777 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6778 return; 6779 } 6780 case Intrinsic::umax: { 6781 SDValue Op1 = getValue(I.getArgOperand(0)); 6782 SDValue Op2 = getValue(I.getArgOperand(1)); 6783 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6784 return; 6785 } 6786 case Intrinsic::umin: { 6787 SDValue Op1 = getValue(I.getArgOperand(0)); 6788 SDValue Op2 = getValue(I.getArgOperand(1)); 6789 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6790 return; 6791 } 6792 case Intrinsic::abs: { 6793 // TODO: Preserve "int min is poison" arg in SDAG? 6794 SDValue Op1 = getValue(I.getArgOperand(0)); 6795 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6796 return; 6797 } 6798 case Intrinsic::stacksave: { 6799 SDValue Op = getRoot(); 6800 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6801 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6802 setValue(&I, Res); 6803 DAG.setRoot(Res.getValue(1)); 6804 return; 6805 } 6806 case Intrinsic::stackrestore: 6807 Res = getValue(I.getArgOperand(0)); 6808 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6809 return; 6810 case Intrinsic::get_dynamic_area_offset: { 6811 SDValue Op = getRoot(); 6812 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6813 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6814 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6815 // target. 6816 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6817 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6818 " intrinsic!"); 6819 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6820 Op); 6821 DAG.setRoot(Op); 6822 setValue(&I, Res); 6823 return; 6824 } 6825 case Intrinsic::stackguard: { 6826 MachineFunction &MF = DAG.getMachineFunction(); 6827 const Module &M = *MF.getFunction().getParent(); 6828 SDValue Chain = getRoot(); 6829 if (TLI.useLoadStackGuardNode()) { 6830 Res = getLoadStackGuard(DAG, sdl, Chain); 6831 } else { 6832 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6833 const Value *Global = TLI.getSDagStackGuard(M); 6834 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType()); 6835 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6836 MachinePointerInfo(Global, 0), Align, 6837 MachineMemOperand::MOVolatile); 6838 } 6839 if (TLI.useStackGuardXorFP()) 6840 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6841 DAG.setRoot(Chain); 6842 setValue(&I, Res); 6843 return; 6844 } 6845 case Intrinsic::stackprotector: { 6846 // Emit code into the DAG to store the stack guard onto the stack. 6847 MachineFunction &MF = DAG.getMachineFunction(); 6848 MachineFrameInfo &MFI = MF.getFrameInfo(); 6849 SDValue Src, Chain = getRoot(); 6850 6851 if (TLI.useLoadStackGuardNode()) 6852 Src = getLoadStackGuard(DAG, sdl, Chain); 6853 else 6854 Src = getValue(I.getArgOperand(0)); // The guard's value. 6855 6856 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6857 6858 int FI = FuncInfo.StaticAllocaMap[Slot]; 6859 MFI.setStackProtectorIndex(FI); 6860 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6861 6862 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6863 6864 // Store the stack protector onto the stack. 6865 Res = DAG.getStore( 6866 Chain, sdl, Src, FIN, 6867 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6868 MaybeAlign(), MachineMemOperand::MOVolatile); 6869 setValue(&I, Res); 6870 DAG.setRoot(Res); 6871 return; 6872 } 6873 case Intrinsic::objectsize: 6874 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6875 6876 case Intrinsic::is_constant: 6877 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6878 6879 case Intrinsic::annotation: 6880 case Intrinsic::ptr_annotation: 6881 case Intrinsic::launder_invariant_group: 6882 case Intrinsic::strip_invariant_group: 6883 // Drop the intrinsic, but forward the value 6884 setValue(&I, getValue(I.getOperand(0))); 6885 return; 6886 6887 case Intrinsic::assume: 6888 case Intrinsic::experimental_noalias_scope_decl: 6889 case Intrinsic::var_annotation: 6890 case Intrinsic::sideeffect: 6891 // Discard annotate attributes, noalias scope declarations, assumptions, and 6892 // artificial side-effects. 6893 return; 6894 6895 case Intrinsic::codeview_annotation: { 6896 // Emit a label associated with this metadata. 6897 MachineFunction &MF = DAG.getMachineFunction(); 6898 MCSymbol *Label = 6899 MF.getMMI().getContext().createTempSymbol("annotation", true); 6900 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6901 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6902 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6903 DAG.setRoot(Res); 6904 return; 6905 } 6906 6907 case Intrinsic::init_trampoline: { 6908 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6909 6910 SDValue Ops[6]; 6911 Ops[0] = getRoot(); 6912 Ops[1] = getValue(I.getArgOperand(0)); 6913 Ops[2] = getValue(I.getArgOperand(1)); 6914 Ops[3] = getValue(I.getArgOperand(2)); 6915 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6916 Ops[5] = DAG.getSrcValue(F); 6917 6918 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6919 6920 DAG.setRoot(Res); 6921 return; 6922 } 6923 case Intrinsic::adjust_trampoline: 6924 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6925 TLI.getPointerTy(DAG.getDataLayout()), 6926 getValue(I.getArgOperand(0)))); 6927 return; 6928 case Intrinsic::gcroot: { 6929 assert(DAG.getMachineFunction().getFunction().hasGC() && 6930 "only valid in functions with gc specified, enforced by Verifier"); 6931 assert(GFI && "implied by previous"); 6932 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6933 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6934 6935 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6936 GFI->addStackRoot(FI->getIndex(), TypeMap); 6937 return; 6938 } 6939 case Intrinsic::gcread: 6940 case Intrinsic::gcwrite: 6941 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6942 case Intrinsic::get_rounding: 6943 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot()); 6944 setValue(&I, Res); 6945 DAG.setRoot(Res.getValue(1)); 6946 return; 6947 6948 case Intrinsic::expect: 6949 // Just replace __builtin_expect(exp, c) with EXP. 6950 setValue(&I, getValue(I.getArgOperand(0))); 6951 return; 6952 6953 case Intrinsic::ubsantrap: 6954 case Intrinsic::debugtrap: 6955 case Intrinsic::trap: { 6956 StringRef TrapFuncName = 6957 I.getAttributes().getFnAttr("trap-func-name").getValueAsString(); 6958 if (TrapFuncName.empty()) { 6959 switch (Intrinsic) { 6960 case Intrinsic::trap: 6961 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6962 break; 6963 case Intrinsic::debugtrap: 6964 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6965 break; 6966 case Intrinsic::ubsantrap: 6967 DAG.setRoot(DAG.getNode( 6968 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6969 DAG.getTargetConstant( 6970 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6971 MVT::i32))); 6972 break; 6973 default: llvm_unreachable("unknown trap intrinsic"); 6974 } 6975 return; 6976 } 6977 TargetLowering::ArgListTy Args; 6978 if (Intrinsic == Intrinsic::ubsantrap) { 6979 Args.push_back(TargetLoweringBase::ArgListEntry()); 6980 Args[0].Val = I.getArgOperand(0); 6981 Args[0].Node = getValue(Args[0].Val); 6982 Args[0].Ty = Args[0].Val->getType(); 6983 } 6984 6985 TargetLowering::CallLoweringInfo CLI(DAG); 6986 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6987 CallingConv::C, I.getType(), 6988 DAG.getExternalSymbol(TrapFuncName.data(), 6989 TLI.getPointerTy(DAG.getDataLayout())), 6990 std::move(Args)); 6991 6992 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6993 DAG.setRoot(Result.second); 6994 return; 6995 } 6996 6997 case Intrinsic::uadd_with_overflow: 6998 case Intrinsic::sadd_with_overflow: 6999 case Intrinsic::usub_with_overflow: 7000 case Intrinsic::ssub_with_overflow: 7001 case Intrinsic::umul_with_overflow: 7002 case Intrinsic::smul_with_overflow: { 7003 ISD::NodeType Op; 7004 switch (Intrinsic) { 7005 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7006 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 7007 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 7008 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 7009 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 7010 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 7011 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 7012 } 7013 SDValue Op1 = getValue(I.getArgOperand(0)); 7014 SDValue Op2 = getValue(I.getArgOperand(1)); 7015 7016 EVT ResultVT = Op1.getValueType(); 7017 EVT OverflowVT = MVT::i1; 7018 if (ResultVT.isVector()) 7019 OverflowVT = EVT::getVectorVT( 7020 *Context, OverflowVT, ResultVT.getVectorElementCount()); 7021 7022 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 7023 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 7024 return; 7025 } 7026 case Intrinsic::prefetch: { 7027 SDValue Ops[5]; 7028 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7029 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 7030 Ops[0] = DAG.getRoot(); 7031 Ops[1] = getValue(I.getArgOperand(0)); 7032 Ops[2] = getValue(I.getArgOperand(1)); 7033 Ops[3] = getValue(I.getArgOperand(2)); 7034 Ops[4] = getValue(I.getArgOperand(3)); 7035 SDValue Result = DAG.getMemIntrinsicNode( 7036 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 7037 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 7038 /* align */ std::nullopt, Flags); 7039 7040 // Chain the prefetch in parallell with any pending loads, to stay out of 7041 // the way of later optimizations. 7042 PendingLoads.push_back(Result); 7043 Result = getRoot(); 7044 DAG.setRoot(Result); 7045 return; 7046 } 7047 case Intrinsic::lifetime_start: 7048 case Intrinsic::lifetime_end: { 7049 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 7050 // Stack coloring is not enabled in O0, discard region information. 7051 if (TM.getOptLevel() == CodeGenOpt::None) 7052 return; 7053 7054 const int64_t ObjectSize = 7055 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 7056 Value *const ObjectPtr = I.getArgOperand(1); 7057 SmallVector<const Value *, 4> Allocas; 7058 getUnderlyingObjects(ObjectPtr, Allocas); 7059 7060 for (const Value *Alloca : Allocas) { 7061 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 7062 7063 // Could not find an Alloca. 7064 if (!LifetimeObject) 7065 continue; 7066 7067 // First check that the Alloca is static, otherwise it won't have a 7068 // valid frame index. 7069 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 7070 if (SI == FuncInfo.StaticAllocaMap.end()) 7071 return; 7072 7073 const int FrameIndex = SI->second; 7074 int64_t Offset; 7075 if (GetPointerBaseWithConstantOffset( 7076 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 7077 Offset = -1; // Cannot determine offset from alloca to lifetime object. 7078 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 7079 Offset); 7080 DAG.setRoot(Res); 7081 } 7082 return; 7083 } 7084 case Intrinsic::pseudoprobe: { 7085 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 7086 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 7087 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 7088 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 7089 DAG.setRoot(Res); 7090 return; 7091 } 7092 case Intrinsic::invariant_start: 7093 // Discard region information. 7094 setValue(&I, 7095 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType()))); 7096 return; 7097 case Intrinsic::invariant_end: 7098 // Discard region information. 7099 return; 7100 case Intrinsic::clear_cache: 7101 /// FunctionName may be null. 7102 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 7103 lowerCallToExternalSymbol(I, FunctionName); 7104 return; 7105 case Intrinsic::donothing: 7106 case Intrinsic::seh_try_begin: 7107 case Intrinsic::seh_scope_begin: 7108 case Intrinsic::seh_try_end: 7109 case Intrinsic::seh_scope_end: 7110 // ignore 7111 return; 7112 case Intrinsic::experimental_stackmap: 7113 visitStackmap(I); 7114 return; 7115 case Intrinsic::experimental_patchpoint_void: 7116 case Intrinsic::experimental_patchpoint_i64: 7117 visitPatchpoint(I); 7118 return; 7119 case Intrinsic::experimental_gc_statepoint: 7120 LowerStatepoint(cast<GCStatepointInst>(I)); 7121 return; 7122 case Intrinsic::experimental_gc_result: 7123 visitGCResult(cast<GCResultInst>(I)); 7124 return; 7125 case Intrinsic::experimental_gc_relocate: 7126 visitGCRelocate(cast<GCRelocateInst>(I)); 7127 return; 7128 case Intrinsic::instrprof_cover: 7129 llvm_unreachable("instrprof failed to lower a cover"); 7130 case Intrinsic::instrprof_increment: 7131 llvm_unreachable("instrprof failed to lower an increment"); 7132 case Intrinsic::instrprof_timestamp: 7133 llvm_unreachable("instrprof failed to lower a timestamp"); 7134 case Intrinsic::instrprof_value_profile: 7135 llvm_unreachable("instrprof failed to lower a value profiling call"); 7136 case Intrinsic::localescape: { 7137 MachineFunction &MF = DAG.getMachineFunction(); 7138 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 7139 7140 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 7141 // is the same on all targets. 7142 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) { 7143 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 7144 if (isa<ConstantPointerNull>(Arg)) 7145 continue; // Skip null pointers. They represent a hole in index space. 7146 AllocaInst *Slot = cast<AllocaInst>(Arg); 7147 assert(FuncInfo.StaticAllocaMap.count(Slot) && 7148 "can only escape static allocas"); 7149 int FI = FuncInfo.StaticAllocaMap[Slot]; 7150 MCSymbol *FrameAllocSym = 7151 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7152 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 7153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 7154 TII->get(TargetOpcode::LOCAL_ESCAPE)) 7155 .addSym(FrameAllocSym) 7156 .addFrameIndex(FI); 7157 } 7158 7159 return; 7160 } 7161 7162 case Intrinsic::localrecover: { 7163 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 7164 MachineFunction &MF = DAG.getMachineFunction(); 7165 7166 // Get the symbol that defines the frame offset. 7167 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 7168 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 7169 unsigned IdxVal = 7170 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 7171 MCSymbol *FrameAllocSym = 7172 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 7173 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 7174 7175 Value *FP = I.getArgOperand(1); 7176 SDValue FPVal = getValue(FP); 7177 EVT PtrVT = FPVal.getValueType(); 7178 7179 // Create a MCSymbol for the label to avoid any target lowering 7180 // that would make this PC relative. 7181 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 7182 SDValue OffsetVal = 7183 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 7184 7185 // Add the offset to the FP. 7186 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 7187 setValue(&I, Add); 7188 7189 return; 7190 } 7191 7192 case Intrinsic::eh_exceptionpointer: 7193 case Intrinsic::eh_exceptioncode: { 7194 // Get the exception pointer vreg, copy from it, and resize it to fit. 7195 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 7196 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 7197 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 7198 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 7199 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT); 7200 if (Intrinsic == Intrinsic::eh_exceptioncode) 7201 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32); 7202 setValue(&I, N); 7203 return; 7204 } 7205 case Intrinsic::xray_customevent: { 7206 // Here we want to make sure that the intrinsic behaves as if it has a 7207 // specific calling convention. 7208 const auto &Triple = DAG.getTarget().getTargetTriple(); 7209 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7210 return; 7211 7212 SmallVector<SDValue, 8> Ops; 7213 7214 // We want to say that we always want the arguments in registers. 7215 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 7216 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 7217 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7218 SDValue Chain = getRoot(); 7219 Ops.push_back(LogEntryVal); 7220 Ops.push_back(StrSizeVal); 7221 Ops.push_back(Chain); 7222 7223 // We need to enforce the calling convention for the callsite, so that 7224 // argument ordering is enforced correctly, and that register allocation can 7225 // see that some registers may be assumed clobbered and have to preserve 7226 // them across calls to the intrinsic. 7227 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 7228 sdl, NodeTys, Ops); 7229 SDValue patchableNode = SDValue(MN, 0); 7230 DAG.setRoot(patchableNode); 7231 setValue(&I, patchableNode); 7232 return; 7233 } 7234 case Intrinsic::xray_typedevent: { 7235 // Here we want to make sure that the intrinsic behaves as if it has a 7236 // specific calling convention. 7237 const auto &Triple = DAG.getTarget().getTargetTriple(); 7238 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64) 7239 return; 7240 7241 SmallVector<SDValue, 8> Ops; 7242 7243 // We want to say that we always want the arguments in registers. 7244 // It's unclear to me how manipulating the selection DAG here forces callers 7245 // to provide arguments in registers instead of on the stack. 7246 SDValue LogTypeId = getValue(I.getArgOperand(0)); 7247 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 7248 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 7249 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7250 SDValue Chain = getRoot(); 7251 Ops.push_back(LogTypeId); 7252 Ops.push_back(LogEntryVal); 7253 Ops.push_back(StrSizeVal); 7254 Ops.push_back(Chain); 7255 7256 // We need to enforce the calling convention for the callsite, so that 7257 // argument ordering is enforced correctly, and that register allocation can 7258 // see that some registers may be assumed clobbered and have to preserve 7259 // them across calls to the intrinsic. 7260 MachineSDNode *MN = DAG.getMachineNode( 7261 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops); 7262 SDValue patchableNode = SDValue(MN, 0); 7263 DAG.setRoot(patchableNode); 7264 setValue(&I, patchableNode); 7265 return; 7266 } 7267 case Intrinsic::experimental_deoptimize: 7268 LowerDeoptimizeCall(&I); 7269 return; 7270 case Intrinsic::experimental_stepvector: 7271 visitStepVector(I); 7272 return; 7273 case Intrinsic::vector_reduce_fadd: 7274 case Intrinsic::vector_reduce_fmul: 7275 case Intrinsic::vector_reduce_add: 7276 case Intrinsic::vector_reduce_mul: 7277 case Intrinsic::vector_reduce_and: 7278 case Intrinsic::vector_reduce_or: 7279 case Intrinsic::vector_reduce_xor: 7280 case Intrinsic::vector_reduce_smax: 7281 case Intrinsic::vector_reduce_smin: 7282 case Intrinsic::vector_reduce_umax: 7283 case Intrinsic::vector_reduce_umin: 7284 case Intrinsic::vector_reduce_fmax: 7285 case Intrinsic::vector_reduce_fmin: 7286 case Intrinsic::vector_reduce_fmaximum: 7287 case Intrinsic::vector_reduce_fminimum: 7288 visitVectorReduce(I, Intrinsic); 7289 return; 7290 7291 case Intrinsic::icall_branch_funnel: { 7292 SmallVector<SDValue, 16> Ops; 7293 Ops.push_back(getValue(I.getArgOperand(0))); 7294 7295 int64_t Offset; 7296 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7297 I.getArgOperand(1), Offset, DAG.getDataLayout())); 7298 if (!Base) 7299 report_fatal_error( 7300 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7301 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0)); 7302 7303 struct BranchFunnelTarget { 7304 int64_t Offset; 7305 SDValue Target; 7306 }; 7307 SmallVector<BranchFunnelTarget, 8> Targets; 7308 7309 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) { 7310 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 7311 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 7312 if (ElemBase != Base) 7313 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 7314 "to the same GlobalValue"); 7315 7316 SDValue Val = getValue(I.getArgOperand(Op + 1)); 7317 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 7318 if (!GA) 7319 report_fatal_error( 7320 "llvm.icall.branch.funnel operand must be a GlobalValue"); 7321 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 7322 GA->getGlobal(), sdl, Val.getValueType(), 7323 GA->getOffset())}); 7324 } 7325 llvm::sort(Targets, 7326 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 7327 return T1.Offset < T2.Offset; 7328 }); 7329 7330 for (auto &T : Targets) { 7331 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32)); 7332 Ops.push_back(T.Target); 7333 } 7334 7335 Ops.push_back(DAG.getRoot()); // Chain 7336 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl, 7337 MVT::Other, Ops), 7338 0); 7339 DAG.setRoot(N); 7340 setValue(&I, N); 7341 HasTailCall = true; 7342 return; 7343 } 7344 7345 case Intrinsic::wasm_landingpad_index: 7346 // Information this intrinsic contained has been transferred to 7347 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 7348 // delete it now. 7349 return; 7350 7351 case Intrinsic::aarch64_settag: 7352 case Intrinsic::aarch64_settag_zero: { 7353 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7354 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 7355 SDValue Val = TSI.EmitTargetCodeForSetTag( 7356 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)), 7357 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 7358 ZeroMemory); 7359 DAG.setRoot(Val); 7360 setValue(&I, Val); 7361 return; 7362 } 7363 case Intrinsic::ptrmask: { 7364 SDValue Ptr = getValue(I.getOperand(0)); 7365 SDValue Const = getValue(I.getOperand(1)); 7366 7367 EVT PtrVT = Ptr.getValueType(); 7368 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, 7369 DAG.getZExtOrTrunc(Const, sdl, PtrVT))); 7370 return; 7371 } 7372 case Intrinsic::threadlocal_address: { 7373 setValue(&I, getValue(I.getOperand(0))); 7374 return; 7375 } 7376 case Intrinsic::get_active_lane_mask: { 7377 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7378 SDValue Index = getValue(I.getOperand(0)); 7379 EVT ElementVT = Index.getValueType(); 7380 7381 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) { 7382 visitTargetIntrinsic(I, Intrinsic); 7383 return; 7384 } 7385 7386 SDValue TripCount = getValue(I.getOperand(1)); 7387 auto VecTy = CCVT.changeVectorElementType(ElementVT); 7388 7389 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index); 7390 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount); 7391 SDValue VectorStep = DAG.getStepVector(sdl, VecTy); 7392 SDValue VectorInduction = DAG.getNode( 7393 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep); 7394 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction, 7395 VectorTripCount, ISD::CondCode::SETULT); 7396 setValue(&I, SetCC); 7397 return; 7398 } 7399 case Intrinsic::experimental_get_vector_length: { 7400 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 && 7401 "Expected positive VF"); 7402 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue(); 7403 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne(); 7404 7405 SDValue Count = getValue(I.getOperand(0)); 7406 EVT CountVT = Count.getValueType(); 7407 7408 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) { 7409 visitTargetIntrinsic(I, Intrinsic); 7410 return; 7411 } 7412 7413 // Expand to a umin between the trip count and the maximum elements the type 7414 // can hold. 7415 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7416 7417 // Extend the trip count to at least the result VT. 7418 if (CountVT.bitsLT(VT)) { 7419 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count); 7420 CountVT = VT; 7421 } 7422 7423 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT, 7424 ElementCount::get(VF, IsScalable)); 7425 7426 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL); 7427 // Clip to the result type if needed. 7428 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin); 7429 7430 setValue(&I, Trunc); 7431 return; 7432 } 7433 case Intrinsic::vector_insert: { 7434 SDValue Vec = getValue(I.getOperand(0)); 7435 SDValue SubVec = getValue(I.getOperand(1)); 7436 SDValue Index = getValue(I.getOperand(2)); 7437 7438 // The intrinsic's index type is i64, but the SDNode requires an index type 7439 // suitable for the target. Convert the index as required. 7440 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7441 if (Index.getValueType() != VectorIdxTy) 7442 Index = DAG.getVectorIdxConstant( 7443 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7444 7445 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7446 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec, 7447 Index)); 7448 return; 7449 } 7450 case Intrinsic::vector_extract: { 7451 SDValue Vec = getValue(I.getOperand(0)); 7452 SDValue Index = getValue(I.getOperand(1)); 7453 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7454 7455 // The intrinsic's index type is i64, but the SDNode requires an index type 7456 // suitable for the target. Convert the index as required. 7457 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7458 if (Index.getValueType() != VectorIdxTy) 7459 Index = DAG.getVectorIdxConstant( 7460 cast<ConstantSDNode>(Index)->getZExtValue(), sdl); 7461 7462 setValue(&I, 7463 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index)); 7464 return; 7465 } 7466 case Intrinsic::experimental_vector_reverse: 7467 visitVectorReverse(I); 7468 return; 7469 case Intrinsic::experimental_vector_splice: 7470 visitVectorSplice(I); 7471 return; 7472 case Intrinsic::callbr_landingpad: 7473 visitCallBrLandingPad(I); 7474 return; 7475 case Intrinsic::experimental_vector_interleave2: 7476 visitVectorInterleave(I); 7477 return; 7478 case Intrinsic::experimental_vector_deinterleave2: 7479 visitVectorDeinterleave(I); 7480 return; 7481 } 7482 } 7483 7484 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7485 const ConstrainedFPIntrinsic &FPI) { 7486 SDLoc sdl = getCurSDLoc(); 7487 7488 // We do not need to serialize constrained FP intrinsics against 7489 // each other or against (nonvolatile) loads, so they can be 7490 // chained like loads. 7491 SDValue Chain = DAG.getRoot(); 7492 SmallVector<SDValue, 4> Opers; 7493 Opers.push_back(Chain); 7494 if (FPI.isUnaryOp()) { 7495 Opers.push_back(getValue(FPI.getArgOperand(0))); 7496 } else if (FPI.isTernaryOp()) { 7497 Opers.push_back(getValue(FPI.getArgOperand(0))); 7498 Opers.push_back(getValue(FPI.getArgOperand(1))); 7499 Opers.push_back(getValue(FPI.getArgOperand(2))); 7500 } else { 7501 Opers.push_back(getValue(FPI.getArgOperand(0))); 7502 Opers.push_back(getValue(FPI.getArgOperand(1))); 7503 } 7504 7505 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7506 assert(Result.getNode()->getNumValues() == 2); 7507 7508 // Push node to the appropriate list so that future instructions can be 7509 // chained up correctly. 7510 SDValue OutChain = Result.getValue(1); 7511 switch (EB) { 7512 case fp::ExceptionBehavior::ebIgnore: 7513 // The only reason why ebIgnore nodes still need to be chained is that 7514 // they might depend on the current rounding mode, and therefore must 7515 // not be moved across instruction that may change that mode. 7516 [[fallthrough]]; 7517 case fp::ExceptionBehavior::ebMayTrap: 7518 // These must not be moved across calls or instructions that may change 7519 // floating-point exception masks. 7520 PendingConstrainedFP.push_back(OutChain); 7521 break; 7522 case fp::ExceptionBehavior::ebStrict: 7523 // These must not be moved across calls or instructions that may change 7524 // floating-point exception masks or read floating-point exception flags. 7525 // In addition, they cannot be optimized out even if unused. 7526 PendingConstrainedFPStrict.push_back(OutChain); 7527 break; 7528 } 7529 }; 7530 7531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7532 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType()); 7533 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 7534 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); 7535 7536 SDNodeFlags Flags; 7537 if (EB == fp::ExceptionBehavior::ebIgnore) 7538 Flags.setNoFPExcept(true); 7539 7540 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7541 Flags.copyFMF(*FPOp); 7542 7543 unsigned Opcode; 7544 switch (FPI.getIntrinsicID()) { 7545 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7546 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7547 case Intrinsic::INTRINSIC: \ 7548 Opcode = ISD::STRICT_##DAGN; \ 7549 break; 7550 #include "llvm/IR/ConstrainedOps.def" 7551 case Intrinsic::experimental_constrained_fmuladd: { 7552 Opcode = ISD::STRICT_FMA; 7553 // Break fmuladd into fmul and fadd. 7554 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7555 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 7556 Opers.pop_back(); 7557 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7558 pushOutChain(Mul, EB); 7559 Opcode = ISD::STRICT_FADD; 7560 Opers.clear(); 7561 Opers.push_back(Mul.getValue(1)); 7562 Opers.push_back(Mul.getValue(0)); 7563 Opers.push_back(getValue(FPI.getArgOperand(2))); 7564 } 7565 break; 7566 } 7567 } 7568 7569 // A few strict DAG nodes carry additional operands that are not 7570 // set up by the default code above. 7571 switch (Opcode) { 7572 default: break; 7573 case ISD::STRICT_FP_ROUND: 7574 Opers.push_back( 7575 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7576 break; 7577 case ISD::STRICT_FSETCC: 7578 case ISD::STRICT_FSETCCS: { 7579 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7580 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7581 if (TM.Options.NoNaNsFPMath) 7582 Condition = getFCmpCodeWithoutNaN(Condition); 7583 Opers.push_back(DAG.getCondCode(Condition)); 7584 break; 7585 } 7586 } 7587 7588 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7589 pushOutChain(Result, EB); 7590 7591 SDValue FPResult = Result.getValue(0); 7592 setValue(&FPI, FPResult); 7593 } 7594 7595 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7596 std::optional<unsigned> ResOPC; 7597 switch (VPIntrin.getIntrinsicID()) { 7598 case Intrinsic::vp_ctlz: { 7599 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7600 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ; 7601 break; 7602 } 7603 case Intrinsic::vp_cttz: { 7604 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne(); 7605 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ; 7606 break; 7607 } 7608 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \ 7609 case Intrinsic::VPID: \ 7610 ResOPC = ISD::VPSD; \ 7611 break; 7612 #include "llvm/IR/VPIntrinsics.def" 7613 } 7614 7615 if (!ResOPC) 7616 llvm_unreachable( 7617 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7618 7619 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD || 7620 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) { 7621 if (VPIntrin.getFastMathFlags().allowReassoc()) 7622 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD 7623 : ISD::VP_REDUCE_FMUL; 7624 } 7625 7626 return *ResOPC; 7627 } 7628 7629 void SelectionDAGBuilder::visitVPLoad( 7630 const VPIntrinsic &VPIntrin, EVT VT, 7631 const SmallVectorImpl<SDValue> &OpValues) { 7632 SDLoc DL = getCurSDLoc(); 7633 Value *PtrOperand = VPIntrin.getArgOperand(0); 7634 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7635 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7636 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7637 SDValue LD; 7638 // Do not serialize variable-length loads of constant memory with 7639 // anything. 7640 if (!Alignment) 7641 Alignment = DAG.getEVTAlign(VT); 7642 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7643 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7644 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7645 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7646 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7647 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7648 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2], 7649 MMO, false /*IsExpanding */); 7650 if (AddToChain) 7651 PendingLoads.push_back(LD.getValue(1)); 7652 setValue(&VPIntrin, LD); 7653 } 7654 7655 void SelectionDAGBuilder::visitVPGather( 7656 const VPIntrinsic &VPIntrin, EVT VT, 7657 const SmallVectorImpl<SDValue> &OpValues) { 7658 SDLoc DL = getCurSDLoc(); 7659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7660 Value *PtrOperand = VPIntrin.getArgOperand(0); 7661 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7662 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7663 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7664 SDValue LD; 7665 if (!Alignment) 7666 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7667 unsigned AS = 7668 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7669 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7670 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 7671 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7672 SDValue Base, Index, Scale; 7673 ISD::MemIndexType IndexType; 7674 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7675 this, VPIntrin.getParent(), 7676 VT.getScalarStoreSize()); 7677 if (!UniformBase) { 7678 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7679 Index = getValue(PtrOperand); 7680 IndexType = ISD::SIGNED_SCALED; 7681 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7682 } 7683 EVT IdxVT = Index.getValueType(); 7684 EVT EltTy = IdxVT.getVectorElementType(); 7685 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7686 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7687 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7688 } 7689 LD = DAG.getGatherVP( 7690 DAG.getVTList(VT, MVT::Other), VT, DL, 7691 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO, 7692 IndexType); 7693 PendingLoads.push_back(LD.getValue(1)); 7694 setValue(&VPIntrin, LD); 7695 } 7696 7697 void SelectionDAGBuilder::visitVPStore( 7698 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7699 SDLoc DL = getCurSDLoc(); 7700 Value *PtrOperand = VPIntrin.getArgOperand(1); 7701 EVT VT = OpValues[0].getValueType(); 7702 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7703 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7704 SDValue ST; 7705 if (!Alignment) 7706 Alignment = DAG.getEVTAlign(VT); 7707 SDValue Ptr = OpValues[1]; 7708 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 7709 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7710 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7711 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7712 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset, 7713 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED, 7714 /* IsTruncating */ false, /*IsCompressing*/ false); 7715 DAG.setRoot(ST); 7716 setValue(&VPIntrin, ST); 7717 } 7718 7719 void SelectionDAGBuilder::visitVPScatter( 7720 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7721 SDLoc DL = getCurSDLoc(); 7722 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7723 Value *PtrOperand = VPIntrin.getArgOperand(1); 7724 EVT VT = OpValues[0].getValueType(); 7725 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7726 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7727 SDValue ST; 7728 if (!Alignment) 7729 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7730 unsigned AS = 7731 PtrOperand->getType()->getScalarType()->getPointerAddressSpace(); 7732 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7733 MachinePointerInfo(AS), MachineMemOperand::MOStore, 7734 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7735 SDValue Base, Index, Scale; 7736 ISD::MemIndexType IndexType; 7737 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale, 7738 this, VPIntrin.getParent(), 7739 VT.getScalarStoreSize()); 7740 if (!UniformBase) { 7741 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout())); 7742 Index = getValue(PtrOperand); 7743 IndexType = ISD::SIGNED_SCALED; 7744 Scale = 7745 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())); 7746 } 7747 EVT IdxVT = Index.getValueType(); 7748 EVT EltTy = IdxVT.getVectorElementType(); 7749 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 7750 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 7751 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index); 7752 } 7753 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL, 7754 {getMemoryRoot(), OpValues[0], Base, Index, Scale, 7755 OpValues[2], OpValues[3]}, 7756 MMO, IndexType); 7757 DAG.setRoot(ST); 7758 setValue(&VPIntrin, ST); 7759 } 7760 7761 void SelectionDAGBuilder::visitVPStridedLoad( 7762 const VPIntrinsic &VPIntrin, EVT VT, 7763 const SmallVectorImpl<SDValue> &OpValues) { 7764 SDLoc DL = getCurSDLoc(); 7765 Value *PtrOperand = VPIntrin.getArgOperand(0); 7766 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7767 if (!Alignment) 7768 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7769 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7770 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range); 7771 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo); 7772 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 7773 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 7774 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7775 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 7776 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 7777 7778 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], 7779 OpValues[2], OpValues[3], MMO, 7780 false /*IsExpanding*/); 7781 7782 if (AddToChain) 7783 PendingLoads.push_back(LD.getValue(1)); 7784 setValue(&VPIntrin, LD); 7785 } 7786 7787 void SelectionDAGBuilder::visitVPStridedStore( 7788 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) { 7789 SDLoc DL = getCurSDLoc(); 7790 Value *PtrOperand = VPIntrin.getArgOperand(1); 7791 EVT VT = OpValues[0].getValueType(); 7792 MaybeAlign Alignment = VPIntrin.getPointerAlignment(); 7793 if (!Alignment) 7794 Alignment = DAG.getEVTAlign(VT.getScalarType()); 7795 AAMDNodes AAInfo = VPIntrin.getAAMetadata(); 7796 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 7797 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 7798 MemoryLocation::UnknownSize, *Alignment, AAInfo); 7799 7800 SDValue ST = DAG.getStridedStoreVP( 7801 getMemoryRoot(), DL, OpValues[0], OpValues[1], 7802 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3], 7803 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false, 7804 /*IsCompressing*/ false); 7805 7806 DAG.setRoot(ST); 7807 setValue(&VPIntrin, ST); 7808 } 7809 7810 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) { 7811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7812 SDLoc DL = getCurSDLoc(); 7813 7814 ISD::CondCode Condition; 7815 CmpInst::Predicate CondCode = VPIntrin.getPredicate(); 7816 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy(); 7817 if (IsFP) { 7818 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan) 7819 // flags, but calls that don't return floating-point types can't be 7820 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too. 7821 Condition = getFCmpCondCode(CondCode); 7822 if (TM.Options.NoNaNsFPMath) 7823 Condition = getFCmpCodeWithoutNaN(Condition); 7824 } else { 7825 Condition = getICmpCondCode(CondCode); 7826 } 7827 7828 SDValue Op1 = getValue(VPIntrin.getOperand(0)); 7829 SDValue Op2 = getValue(VPIntrin.getOperand(1)); 7830 // #2 is the condition code 7831 SDValue MaskOp = getValue(VPIntrin.getOperand(3)); 7832 SDValue EVL = getValue(VPIntrin.getOperand(4)); 7833 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7834 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7835 "Unexpected target EVL type"); 7836 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL); 7837 7838 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7839 VPIntrin.getType()); 7840 setValue(&VPIntrin, 7841 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL)); 7842 } 7843 7844 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7845 const VPIntrinsic &VPIntrin) { 7846 SDLoc DL = getCurSDLoc(); 7847 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7848 7849 auto IID = VPIntrin.getIntrinsicID(); 7850 7851 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin)) 7852 return visitVPCmp(*CmpI); 7853 7854 SmallVector<EVT, 4> ValueVTs; 7855 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7856 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7857 SDVTList VTs = DAG.getVTList(ValueVTs); 7858 7859 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID); 7860 7861 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy(); 7862 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) && 7863 "Unexpected target EVL type"); 7864 7865 // Request operands. 7866 SmallVector<SDValue, 7> OpValues; 7867 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) { 7868 auto Op = getValue(VPIntrin.getArgOperand(I)); 7869 if (I == EVLParamPos) 7870 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op); 7871 OpValues.push_back(Op); 7872 } 7873 7874 switch (Opcode) { 7875 default: { 7876 SDNodeFlags SDFlags; 7877 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7878 SDFlags.copyFMF(*FPMO); 7879 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags); 7880 setValue(&VPIntrin, Result); 7881 break; 7882 } 7883 case ISD::VP_LOAD: 7884 visitVPLoad(VPIntrin, ValueVTs[0], OpValues); 7885 break; 7886 case ISD::VP_GATHER: 7887 visitVPGather(VPIntrin, ValueVTs[0], OpValues); 7888 break; 7889 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: 7890 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues); 7891 break; 7892 case ISD::VP_STORE: 7893 visitVPStore(VPIntrin, OpValues); 7894 break; 7895 case ISD::VP_SCATTER: 7896 visitVPScatter(VPIntrin, OpValues); 7897 break; 7898 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 7899 visitVPStridedStore(VPIntrin, OpValues); 7900 break; 7901 case ISD::VP_FMULADD: { 7902 assert(OpValues.size() == 5 && "Unexpected number of operands"); 7903 SDNodeFlags SDFlags; 7904 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin)) 7905 SDFlags.copyFMF(*FPMO); 7906 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 7907 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) { 7908 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags)); 7909 } else { 7910 SDValue Mul = DAG.getNode( 7911 ISD::VP_FMUL, DL, VTs, 7912 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags); 7913 SDValue Add = 7914 DAG.getNode(ISD::VP_FADD, DL, VTs, 7915 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags); 7916 setValue(&VPIntrin, Add); 7917 } 7918 break; 7919 } 7920 case ISD::VP_INTTOPTR: { 7921 SDValue N = OpValues[0]; 7922 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType()); 7923 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType()); 7924 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7925 OpValues[2]); 7926 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7927 OpValues[2]); 7928 setValue(&VPIntrin, N); 7929 break; 7930 } 7931 case ISD::VP_PTRTOINT: { 7932 SDValue N = OpValues[0]; 7933 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7934 VPIntrin.getType()); 7935 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), 7936 VPIntrin.getOperand(0)->getType()); 7937 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1], 7938 OpValues[2]); 7939 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1], 7940 OpValues[2]); 7941 setValue(&VPIntrin, N); 7942 break; 7943 } 7944 case ISD::VP_ABS: 7945 case ISD::VP_CTLZ: 7946 case ISD::VP_CTLZ_ZERO_UNDEF: 7947 case ISD::VP_CTTZ: 7948 case ISD::VP_CTTZ_ZERO_UNDEF: { 7949 SDValue Result = 7950 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]}); 7951 setValue(&VPIntrin, Result); 7952 break; 7953 } 7954 } 7955 } 7956 7957 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain, 7958 const BasicBlock *EHPadBB, 7959 MCSymbol *&BeginLabel) { 7960 MachineFunction &MF = DAG.getMachineFunction(); 7961 MachineModuleInfo &MMI = MF.getMMI(); 7962 7963 // Insert a label before the invoke call to mark the try range. This can be 7964 // used to detect deletion of the invoke via the MachineModuleInfo. 7965 BeginLabel = MMI.getContext().createTempSymbol(); 7966 7967 // For SjLj, keep track of which landing pads go with which invokes 7968 // so as to maintain the ordering of pads in the LSDA. 7969 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7970 if (CallSiteIndex) { 7971 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7972 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7973 7974 // Now that the call site is handled, stop tracking it. 7975 MMI.setCurrentCallSite(0); 7976 } 7977 7978 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel); 7979 } 7980 7981 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II, 7982 const BasicBlock *EHPadBB, 7983 MCSymbol *BeginLabel) { 7984 assert(BeginLabel && "BeginLabel should've been set"); 7985 7986 MachineFunction &MF = DAG.getMachineFunction(); 7987 MachineModuleInfo &MMI = MF.getMMI(); 7988 7989 // Insert a label at the end of the invoke call to mark the try range. This 7990 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7991 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7992 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel); 7993 7994 // Inform MachineModuleInfo of range. 7995 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7996 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7997 // actually use outlined funclets and their LSDA info style. 7998 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7999 assert(II && "II should've been set"); 8000 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo(); 8001 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel); 8002 } else if (!isScopedEHPersonality(Pers)) { 8003 assert(EHPadBB); 8004 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 8005 } 8006 8007 return Chain; 8008 } 8009 8010 std::pair<SDValue, SDValue> 8011 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 8012 const BasicBlock *EHPadBB) { 8013 MCSymbol *BeginLabel = nullptr; 8014 8015 if (EHPadBB) { 8016 // Both PendingLoads and PendingExports must be flushed here; 8017 // this call might not return. 8018 (void)getRoot(); 8019 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel)); 8020 CLI.setChain(getRoot()); 8021 } 8022 8023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8024 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 8025 8026 assert((CLI.IsTailCall || Result.second.getNode()) && 8027 "Non-null chain expected with non-tail call!"); 8028 assert((Result.second.getNode() || !Result.first.getNode()) && 8029 "Null value expected with tail call!"); 8030 8031 if (!Result.second.getNode()) { 8032 // As a special case, a null chain means that a tail call has been emitted 8033 // and the DAG root is already updated. 8034 HasTailCall = true; 8035 8036 // Since there's no actual continuation from this block, nothing can be 8037 // relying on us setting vregs for them. 8038 PendingExports.clear(); 8039 } else { 8040 DAG.setRoot(Result.second); 8041 } 8042 8043 if (EHPadBB) { 8044 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB, 8045 BeginLabel)); 8046 } 8047 8048 return Result; 8049 } 8050 8051 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 8052 bool isTailCall, 8053 bool isMustTailCall, 8054 const BasicBlock *EHPadBB) { 8055 auto &DL = DAG.getDataLayout(); 8056 FunctionType *FTy = CB.getFunctionType(); 8057 Type *RetTy = CB.getType(); 8058 8059 TargetLowering::ArgListTy Args; 8060 Args.reserve(CB.arg_size()); 8061 8062 const Value *SwiftErrorVal = nullptr; 8063 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8064 8065 if (isTailCall) { 8066 // Avoid emitting tail calls in functions with the disable-tail-calls 8067 // attribute. 8068 auto *Caller = CB.getParent()->getParent(); 8069 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 8070 "true" && !isMustTailCall) 8071 isTailCall = false; 8072 8073 // We can't tail call inside a function with a swifterror argument. Lowering 8074 // does not support this yet. It would have to move into the swifterror 8075 // register before the call. 8076 if (TLI.supportSwiftError() && 8077 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 8078 isTailCall = false; 8079 } 8080 8081 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 8082 TargetLowering::ArgListEntry Entry; 8083 const Value *V = *I; 8084 8085 // Skip empty types 8086 if (V->getType()->isEmptyTy()) 8087 continue; 8088 8089 SDValue ArgNode = getValue(V); 8090 Entry.Node = ArgNode; Entry.Ty = V->getType(); 8091 8092 Entry.setAttributes(&CB, I - CB.arg_begin()); 8093 8094 // Use swifterror virtual register as input to the call. 8095 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 8096 SwiftErrorVal = V; 8097 // We find the virtual register for the actual swifterror argument. 8098 // Instead of using the Value, we use the virtual register instead. 8099 Entry.Node = 8100 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 8101 EVT(TLI.getPointerTy(DL))); 8102 } 8103 8104 Args.push_back(Entry); 8105 8106 // If we have an explicit sret argument that is an Instruction, (i.e., it 8107 // might point to function-local memory), we can't meaningfully tail-call. 8108 if (Entry.IsSRet && isa<Instruction>(V)) 8109 isTailCall = false; 8110 } 8111 8112 // If call site has a cfguardtarget operand bundle, create and add an 8113 // additional ArgListEntry. 8114 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 8115 TargetLowering::ArgListEntry Entry; 8116 Value *V = Bundle->Inputs[0]; 8117 SDValue ArgNode = getValue(V); 8118 Entry.Node = ArgNode; 8119 Entry.Ty = V->getType(); 8120 Entry.IsCFGuardTarget = true; 8121 Args.push_back(Entry); 8122 } 8123 8124 // Check if target-independent constraints permit a tail call here. 8125 // Target-dependent constraints are checked within TLI->LowerCallTo. 8126 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 8127 isTailCall = false; 8128 8129 // Disable tail calls if there is an swifterror argument. Targets have not 8130 // been updated to support tail calls. 8131 if (TLI.supportSwiftError() && SwiftErrorVal) 8132 isTailCall = false; 8133 8134 ConstantInt *CFIType = nullptr; 8135 if (CB.isIndirectCall()) { 8136 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) { 8137 if (!TLI.supportKCFIBundles()) 8138 report_fatal_error( 8139 "Target doesn't support calls with kcfi operand bundles."); 8140 CFIType = cast<ConstantInt>(Bundle->Inputs[0]); 8141 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type"); 8142 } 8143 } 8144 8145 TargetLowering::CallLoweringInfo CLI(DAG); 8146 CLI.setDebugLoc(getCurSDLoc()) 8147 .setChain(getRoot()) 8148 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 8149 .setTailCall(isTailCall) 8150 .setConvergent(CB.isConvergent()) 8151 .setIsPreallocated( 8152 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0) 8153 .setCFIType(CFIType); 8154 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8155 8156 if (Result.first.getNode()) { 8157 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 8158 setValue(&CB, Result.first); 8159 } 8160 8161 // The last element of CLI.InVals has the SDValue for swifterror return. 8162 // Here we copy it to a virtual register and update SwiftErrorMap for 8163 // book-keeping. 8164 if (SwiftErrorVal && TLI.supportSwiftError()) { 8165 // Get the last element of InVals. 8166 SDValue Src = CLI.InVals.back(); 8167 Register VReg = 8168 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 8169 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 8170 DAG.setRoot(CopyNode); 8171 } 8172 } 8173 8174 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 8175 SelectionDAGBuilder &Builder) { 8176 // Check to see if this load can be trivially constant folded, e.g. if the 8177 // input is from a string literal. 8178 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 8179 // Cast pointer to the type we really want to load. 8180 Type *LoadTy = 8181 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 8182 if (LoadVT.isVector()) 8183 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 8184 8185 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 8186 PointerType::getUnqual(LoadTy)); 8187 8188 if (const Constant *LoadCst = 8189 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 8190 LoadTy, Builder.DAG.getDataLayout())) 8191 return Builder.getValue(LoadCst); 8192 } 8193 8194 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 8195 // still constant memory, the input chain can be the entry node. 8196 SDValue Root; 8197 bool ConstantMemory = false; 8198 8199 // Do not serialize (non-volatile) loads of constant memory with anything. 8200 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 8201 Root = Builder.DAG.getEntryNode(); 8202 ConstantMemory = true; 8203 } else { 8204 // Do not serialize non-volatile loads against each other. 8205 Root = Builder.DAG.getRoot(); 8206 } 8207 8208 SDValue Ptr = Builder.getValue(PtrVal); 8209 SDValue LoadVal = 8210 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 8211 MachinePointerInfo(PtrVal), Align(1)); 8212 8213 if (!ConstantMemory) 8214 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 8215 return LoadVal; 8216 } 8217 8218 /// Record the value for an instruction that produces an integer result, 8219 /// converting the type where necessary. 8220 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 8221 SDValue Value, 8222 bool IsSigned) { 8223 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8224 I.getType(), true); 8225 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT); 8226 setValue(&I, Value); 8227 } 8228 8229 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 8230 /// true and lower it. Otherwise return false, and it will be lowered like a 8231 /// normal call. 8232 /// The caller already checked that \p I calls the appropriate LibFunc with a 8233 /// correct prototype. 8234 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 8235 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 8236 const Value *Size = I.getArgOperand(2); 8237 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size)); 8238 if (CSize && CSize->getZExtValue() == 0) { 8239 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 8240 I.getType(), true); 8241 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 8242 return true; 8243 } 8244 8245 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8246 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 8247 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 8248 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 8249 if (Res.first.getNode()) { 8250 processIntegerCallValue(I, Res.first, true); 8251 PendingLoads.push_back(Res.second); 8252 return true; 8253 } 8254 8255 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 8256 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 8257 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 8258 return false; 8259 8260 // If the target has a fast compare for the given size, it will return a 8261 // preferred load type for that size. Require that the load VT is legal and 8262 // that the target supports unaligned loads of that type. Otherwise, return 8263 // INVALID. 8264 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 8265 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8266 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 8267 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 8268 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 8269 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 8270 // TODO: Check alignment of src and dest ptrs. 8271 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 8272 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 8273 if (!TLI.isTypeLegal(LVT) || 8274 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 8275 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 8276 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 8277 } 8278 8279 return LVT; 8280 }; 8281 8282 // This turns into unaligned loads. We only do this if the target natively 8283 // supports the MVT we'll be loading or if it is small enough (<= 4) that 8284 // we'll only produce a small number of byte loads. 8285 MVT LoadVT; 8286 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 8287 switch (NumBitsToCompare) { 8288 default: 8289 return false; 8290 case 16: 8291 LoadVT = MVT::i16; 8292 break; 8293 case 32: 8294 LoadVT = MVT::i32; 8295 break; 8296 case 64: 8297 case 128: 8298 case 256: 8299 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 8300 break; 8301 } 8302 8303 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 8304 return false; 8305 8306 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 8307 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 8308 8309 // Bitcast to a wide integer type if the loads are vectors. 8310 if (LoadVT.isVector()) { 8311 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 8312 LoadL = DAG.getBitcast(CmpVT, LoadL); 8313 LoadR = DAG.getBitcast(CmpVT, LoadR); 8314 } 8315 8316 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 8317 processIntegerCallValue(I, Cmp, false); 8318 return true; 8319 } 8320 8321 /// See if we can lower a memchr call into an optimized form. If so, return 8322 /// true and lower it. Otherwise return false, and it will be lowered like a 8323 /// normal call. 8324 /// The caller already checked that \p I calls the appropriate LibFunc with a 8325 /// correct prototype. 8326 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 8327 const Value *Src = I.getArgOperand(0); 8328 const Value *Char = I.getArgOperand(1); 8329 const Value *Length = I.getArgOperand(2); 8330 8331 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8332 std::pair<SDValue, SDValue> Res = 8333 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 8334 getValue(Src), getValue(Char), getValue(Length), 8335 MachinePointerInfo(Src)); 8336 if (Res.first.getNode()) { 8337 setValue(&I, Res.first); 8338 PendingLoads.push_back(Res.second); 8339 return true; 8340 } 8341 8342 return false; 8343 } 8344 8345 /// See if we can lower a mempcpy call into an optimized form. If so, return 8346 /// true and lower it. Otherwise return false, and it will be lowered like a 8347 /// normal call. 8348 /// The caller already checked that \p I calls the appropriate LibFunc with a 8349 /// correct prototype. 8350 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 8351 SDValue Dst = getValue(I.getArgOperand(0)); 8352 SDValue Src = getValue(I.getArgOperand(1)); 8353 SDValue Size = getValue(I.getArgOperand(2)); 8354 8355 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 8356 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 8357 // DAG::getMemcpy needs Alignment to be defined. 8358 Align Alignment = std::min(DstAlign, SrcAlign); 8359 8360 SDLoc sdl = getCurSDLoc(); 8361 8362 // In the mempcpy context we need to pass in a false value for isTailCall 8363 // because the return pointer needs to be adjusted by the size of 8364 // the copied memory. 8365 SDValue Root = getMemoryRoot(); 8366 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false, 8367 /*isTailCall=*/false, 8368 MachinePointerInfo(I.getArgOperand(0)), 8369 MachinePointerInfo(I.getArgOperand(1)), 8370 I.getAAMetadata()); 8371 assert(MC.getNode() != nullptr && 8372 "** memcpy should not be lowered as TailCall in mempcpy context **"); 8373 DAG.setRoot(MC); 8374 8375 // Check if Size needs to be truncated or extended. 8376 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 8377 8378 // Adjust return pointer to point just past the last dst byte. 8379 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 8380 Dst, Size); 8381 setValue(&I, DstPlusSize); 8382 return true; 8383 } 8384 8385 /// See if we can lower a strcpy call into an optimized form. If so, return 8386 /// true and lower it, otherwise return false and it will be lowered like a 8387 /// normal call. 8388 /// The caller already checked that \p I calls the appropriate LibFunc with a 8389 /// correct prototype. 8390 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 8391 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8392 8393 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8394 std::pair<SDValue, SDValue> Res = 8395 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 8396 getValue(Arg0), getValue(Arg1), 8397 MachinePointerInfo(Arg0), 8398 MachinePointerInfo(Arg1), isStpcpy); 8399 if (Res.first.getNode()) { 8400 setValue(&I, Res.first); 8401 DAG.setRoot(Res.second); 8402 return true; 8403 } 8404 8405 return false; 8406 } 8407 8408 /// See if we can lower a strcmp call into an optimized form. If so, return 8409 /// true and lower it, otherwise return false and it will be lowered like a 8410 /// normal call. 8411 /// The caller already checked that \p I calls the appropriate LibFunc with a 8412 /// correct prototype. 8413 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 8414 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8415 8416 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8417 std::pair<SDValue, SDValue> Res = 8418 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 8419 getValue(Arg0), getValue(Arg1), 8420 MachinePointerInfo(Arg0), 8421 MachinePointerInfo(Arg1)); 8422 if (Res.first.getNode()) { 8423 processIntegerCallValue(I, Res.first, true); 8424 PendingLoads.push_back(Res.second); 8425 return true; 8426 } 8427 8428 return false; 8429 } 8430 8431 /// See if we can lower a strlen call into an optimized form. If so, return 8432 /// true and lower it, otherwise return false and it will be lowered like a 8433 /// normal call. 8434 /// The caller already checked that \p I calls the appropriate LibFunc with a 8435 /// correct prototype. 8436 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 8437 const Value *Arg0 = I.getArgOperand(0); 8438 8439 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8440 std::pair<SDValue, SDValue> Res = 8441 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 8442 getValue(Arg0), MachinePointerInfo(Arg0)); 8443 if (Res.first.getNode()) { 8444 processIntegerCallValue(I, Res.first, false); 8445 PendingLoads.push_back(Res.second); 8446 return true; 8447 } 8448 8449 return false; 8450 } 8451 8452 /// See if we can lower a strnlen call into an optimized form. If so, return 8453 /// true and lower it, otherwise return false and it will be lowered like a 8454 /// normal call. 8455 /// The caller already checked that \p I calls the appropriate LibFunc with a 8456 /// correct prototype. 8457 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 8458 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 8459 8460 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 8461 std::pair<SDValue, SDValue> Res = 8462 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 8463 getValue(Arg0), getValue(Arg1), 8464 MachinePointerInfo(Arg0)); 8465 if (Res.first.getNode()) { 8466 processIntegerCallValue(I, Res.first, false); 8467 PendingLoads.push_back(Res.second); 8468 return true; 8469 } 8470 8471 return false; 8472 } 8473 8474 /// See if we can lower a unary floating-point operation into an SDNode with 8475 /// the specified Opcode. If so, return true and lower it, otherwise return 8476 /// false and it will be lowered like a normal call. 8477 /// The caller already checked that \p I calls the appropriate LibFunc with a 8478 /// correct prototype. 8479 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 8480 unsigned Opcode) { 8481 // We already checked this call's prototype; verify it doesn't modify errno. 8482 if (!I.onlyReadsMemory()) 8483 return false; 8484 8485 SDNodeFlags Flags; 8486 Flags.copyFMF(cast<FPMathOperator>(I)); 8487 8488 SDValue Tmp = getValue(I.getArgOperand(0)); 8489 setValue(&I, 8490 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 8491 return true; 8492 } 8493 8494 /// See if we can lower a binary floating-point operation into an SDNode with 8495 /// the specified Opcode. If so, return true and lower it. Otherwise return 8496 /// false, and it will be lowered like a normal call. 8497 /// The caller already checked that \p I calls the appropriate LibFunc with a 8498 /// correct prototype. 8499 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 8500 unsigned Opcode) { 8501 // We already checked this call's prototype; verify it doesn't modify errno. 8502 if (!I.onlyReadsMemory()) 8503 return false; 8504 8505 SDNodeFlags Flags; 8506 Flags.copyFMF(cast<FPMathOperator>(I)); 8507 8508 SDValue Tmp0 = getValue(I.getArgOperand(0)); 8509 SDValue Tmp1 = getValue(I.getArgOperand(1)); 8510 EVT VT = Tmp0.getValueType(); 8511 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 8512 return true; 8513 } 8514 8515 void SelectionDAGBuilder::visitCall(const CallInst &I) { 8516 // Handle inline assembly differently. 8517 if (I.isInlineAsm()) { 8518 visitInlineAsm(I); 8519 return; 8520 } 8521 8522 diagnoseDontCall(I); 8523 8524 if (Function *F = I.getCalledFunction()) { 8525 if (F->isDeclaration()) { 8526 // Is this an LLVM intrinsic or a target-specific intrinsic? 8527 unsigned IID = F->getIntrinsicID(); 8528 if (!IID) 8529 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 8530 IID = II->getIntrinsicID(F); 8531 8532 if (IID) { 8533 visitIntrinsicCall(I, IID); 8534 return; 8535 } 8536 } 8537 8538 // Check for well-known libc/libm calls. If the function is internal, it 8539 // can't be a library call. Don't do the check if marked as nobuiltin for 8540 // some reason or the call site requires strict floating point semantics. 8541 LibFunc Func; 8542 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 8543 F->hasName() && LibInfo->getLibFunc(*F, Func) && 8544 LibInfo->hasOptimizedCodeGen(Func)) { 8545 switch (Func) { 8546 default: break; 8547 case LibFunc_bcmp: 8548 if (visitMemCmpBCmpCall(I)) 8549 return; 8550 break; 8551 case LibFunc_copysign: 8552 case LibFunc_copysignf: 8553 case LibFunc_copysignl: 8554 // We already checked this call's prototype; verify it doesn't modify 8555 // errno. 8556 if (I.onlyReadsMemory()) { 8557 SDValue LHS = getValue(I.getArgOperand(0)); 8558 SDValue RHS = getValue(I.getArgOperand(1)); 8559 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 8560 LHS.getValueType(), LHS, RHS)); 8561 return; 8562 } 8563 break; 8564 case LibFunc_fabs: 8565 case LibFunc_fabsf: 8566 case LibFunc_fabsl: 8567 if (visitUnaryFloatCall(I, ISD::FABS)) 8568 return; 8569 break; 8570 case LibFunc_fmin: 8571 case LibFunc_fminf: 8572 case LibFunc_fminl: 8573 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 8574 return; 8575 break; 8576 case LibFunc_fmax: 8577 case LibFunc_fmaxf: 8578 case LibFunc_fmaxl: 8579 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 8580 return; 8581 break; 8582 case LibFunc_sin: 8583 case LibFunc_sinf: 8584 case LibFunc_sinl: 8585 if (visitUnaryFloatCall(I, ISD::FSIN)) 8586 return; 8587 break; 8588 case LibFunc_cos: 8589 case LibFunc_cosf: 8590 case LibFunc_cosl: 8591 if (visitUnaryFloatCall(I, ISD::FCOS)) 8592 return; 8593 break; 8594 case LibFunc_sqrt: 8595 case LibFunc_sqrtf: 8596 case LibFunc_sqrtl: 8597 case LibFunc_sqrt_finite: 8598 case LibFunc_sqrtf_finite: 8599 case LibFunc_sqrtl_finite: 8600 if (visitUnaryFloatCall(I, ISD::FSQRT)) 8601 return; 8602 break; 8603 case LibFunc_floor: 8604 case LibFunc_floorf: 8605 case LibFunc_floorl: 8606 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 8607 return; 8608 break; 8609 case LibFunc_nearbyint: 8610 case LibFunc_nearbyintf: 8611 case LibFunc_nearbyintl: 8612 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 8613 return; 8614 break; 8615 case LibFunc_ceil: 8616 case LibFunc_ceilf: 8617 case LibFunc_ceill: 8618 if (visitUnaryFloatCall(I, ISD::FCEIL)) 8619 return; 8620 break; 8621 case LibFunc_rint: 8622 case LibFunc_rintf: 8623 case LibFunc_rintl: 8624 if (visitUnaryFloatCall(I, ISD::FRINT)) 8625 return; 8626 break; 8627 case LibFunc_round: 8628 case LibFunc_roundf: 8629 case LibFunc_roundl: 8630 if (visitUnaryFloatCall(I, ISD::FROUND)) 8631 return; 8632 break; 8633 case LibFunc_trunc: 8634 case LibFunc_truncf: 8635 case LibFunc_truncl: 8636 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 8637 return; 8638 break; 8639 case LibFunc_log2: 8640 case LibFunc_log2f: 8641 case LibFunc_log2l: 8642 if (visitUnaryFloatCall(I, ISD::FLOG2)) 8643 return; 8644 break; 8645 case LibFunc_exp2: 8646 case LibFunc_exp2f: 8647 case LibFunc_exp2l: 8648 if (visitUnaryFloatCall(I, ISD::FEXP2)) 8649 return; 8650 break; 8651 case LibFunc_ldexp: 8652 case LibFunc_ldexpf: 8653 case LibFunc_ldexpl: 8654 if (visitBinaryFloatCall(I, ISD::FLDEXP)) 8655 return; 8656 break; 8657 case LibFunc_memcmp: 8658 if (visitMemCmpBCmpCall(I)) 8659 return; 8660 break; 8661 case LibFunc_mempcpy: 8662 if (visitMemPCpyCall(I)) 8663 return; 8664 break; 8665 case LibFunc_memchr: 8666 if (visitMemChrCall(I)) 8667 return; 8668 break; 8669 case LibFunc_strcpy: 8670 if (visitStrCpyCall(I, false)) 8671 return; 8672 break; 8673 case LibFunc_stpcpy: 8674 if (visitStrCpyCall(I, true)) 8675 return; 8676 break; 8677 case LibFunc_strcmp: 8678 if (visitStrCmpCall(I)) 8679 return; 8680 break; 8681 case LibFunc_strlen: 8682 if (visitStrLenCall(I)) 8683 return; 8684 break; 8685 case LibFunc_strnlen: 8686 if (visitStrNLenCall(I)) 8687 return; 8688 break; 8689 } 8690 } 8691 } 8692 8693 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 8694 // have to do anything here to lower funclet bundles. 8695 // CFGuardTarget bundles are lowered in LowerCallTo. 8696 assert(!I.hasOperandBundlesOtherThan( 8697 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 8698 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated, 8699 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) && 8700 "Cannot lower calls with arbitrary operand bundles!"); 8701 8702 SDValue Callee = getValue(I.getCalledOperand()); 8703 8704 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 8705 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 8706 else 8707 // Check if we can potentially perform a tail call. More detailed checking 8708 // is be done within LowerCallTo, after more information about the call is 8709 // known. 8710 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall()); 8711 } 8712 8713 namespace { 8714 8715 /// AsmOperandInfo - This contains information for each constraint that we are 8716 /// lowering. 8717 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 8718 public: 8719 /// CallOperand - If this is the result output operand or a clobber 8720 /// this is null, otherwise it is the incoming operand to the CallInst. 8721 /// This gets modified as the asm is processed. 8722 SDValue CallOperand; 8723 8724 /// AssignedRegs - If this is a register or register class operand, this 8725 /// contains the set of register corresponding to the operand. 8726 RegsForValue AssignedRegs; 8727 8728 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 8729 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 8730 } 8731 8732 /// Whether or not this operand accesses memory 8733 bool hasMemory(const TargetLowering &TLI) const { 8734 // Indirect operand accesses access memory. 8735 if (isIndirect) 8736 return true; 8737 8738 for (const auto &Code : Codes) 8739 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 8740 return true; 8741 8742 return false; 8743 } 8744 }; 8745 8746 8747 } // end anonymous namespace 8748 8749 /// Make sure that the output operand \p OpInfo and its corresponding input 8750 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 8751 /// out). 8752 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 8753 SDISelAsmOperandInfo &MatchingOpInfo, 8754 SelectionDAG &DAG) { 8755 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 8756 return; 8757 8758 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 8759 const auto &TLI = DAG.getTargetLoweringInfo(); 8760 8761 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 8762 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 8763 OpInfo.ConstraintVT); 8764 std::pair<unsigned, const TargetRegisterClass *> InputRC = 8765 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 8766 MatchingOpInfo.ConstraintVT); 8767 if ((OpInfo.ConstraintVT.isInteger() != 8768 MatchingOpInfo.ConstraintVT.isInteger()) || 8769 (MatchRC.second != InputRC.second)) { 8770 // FIXME: error out in a more elegant fashion 8771 report_fatal_error("Unsupported asm: input constraint" 8772 " with a matching output constraint of" 8773 " incompatible type!"); 8774 } 8775 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8776 } 8777 8778 /// Get a direct memory input to behave well as an indirect operand. 8779 /// This may introduce stores, hence the need for a \p Chain. 8780 /// \return The (possibly updated) chain. 8781 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8782 SDISelAsmOperandInfo &OpInfo, 8783 SelectionDAG &DAG) { 8784 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8785 8786 // If we don't have an indirect input, put it in the constpool if we can, 8787 // otherwise spill it to a stack slot. 8788 // TODO: This isn't quite right. We need to handle these according to 8789 // the addressing mode that the constraint wants. Also, this may take 8790 // an additional register for the computation and we don't want that 8791 // either. 8792 8793 // If the operand is a float, integer, or vector constant, spill to a 8794 // constant pool entry to get its address. 8795 const Value *OpVal = OpInfo.CallOperandVal; 8796 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8797 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8798 OpInfo.CallOperand = DAG.getConstantPool( 8799 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8800 return Chain; 8801 } 8802 8803 // Otherwise, create a stack slot and emit a store to it before the asm. 8804 Type *Ty = OpVal->getType(); 8805 auto &DL = DAG.getDataLayout(); 8806 uint64_t TySize = DL.getTypeAllocSize(Ty); 8807 MachineFunction &MF = DAG.getMachineFunction(); 8808 int SSFI = MF.getFrameInfo().CreateStackObject( 8809 TySize, DL.getPrefTypeAlign(Ty), false); 8810 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8811 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8812 MachinePointerInfo::getFixedStack(MF, SSFI), 8813 TLI.getMemValueType(DL, Ty)); 8814 OpInfo.CallOperand = StackSlot; 8815 8816 return Chain; 8817 } 8818 8819 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8820 /// specified operand. We prefer to assign virtual registers, to allow the 8821 /// register allocator to handle the assignment process. However, if the asm 8822 /// uses features that we can't model on machineinstrs, we have SDISel do the 8823 /// allocation. This produces generally horrible, but correct, code. 8824 /// 8825 /// OpInfo describes the operand 8826 /// RefOpInfo describes the matching operand if any, the operand otherwise 8827 static std::optional<unsigned> 8828 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8829 SDISelAsmOperandInfo &OpInfo, 8830 SDISelAsmOperandInfo &RefOpInfo) { 8831 LLVMContext &Context = *DAG.getContext(); 8832 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8833 8834 MachineFunction &MF = DAG.getMachineFunction(); 8835 SmallVector<unsigned, 4> Regs; 8836 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8837 8838 // No work to do for memory/address operands. 8839 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8840 OpInfo.ConstraintType == TargetLowering::C_Address) 8841 return std::nullopt; 8842 8843 // If this is a constraint for a single physreg, or a constraint for a 8844 // register class, find it. 8845 unsigned AssignedReg; 8846 const TargetRegisterClass *RC; 8847 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8848 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8849 // RC is unset only on failure. Return immediately. 8850 if (!RC) 8851 return std::nullopt; 8852 8853 // Get the actual register value type. This is important, because the user 8854 // may have asked for (e.g.) the AX register in i32 type. We need to 8855 // remember that AX is actually i16 to get the right extension. 8856 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8857 8858 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) { 8859 // If this is an FP operand in an integer register (or visa versa), or more 8860 // generally if the operand value disagrees with the register class we plan 8861 // to stick it in, fix the operand type. 8862 // 8863 // If this is an input value, the bitcast to the new type is done now. 8864 // Bitcast for output value is done at the end of visitInlineAsm(). 8865 if ((OpInfo.Type == InlineAsm::isOutput || 8866 OpInfo.Type == InlineAsm::isInput) && 8867 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8868 // Try to convert to the first EVT that the reg class contains. If the 8869 // types are identical size, use a bitcast to convert (e.g. two differing 8870 // vector types). Note: output bitcast is done at the end of 8871 // visitInlineAsm(). 8872 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8873 // Exclude indirect inputs while they are unsupported because the code 8874 // to perform the load is missing and thus OpInfo.CallOperand still 8875 // refers to the input address rather than the pointed-to value. 8876 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8877 OpInfo.CallOperand = 8878 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8879 OpInfo.ConstraintVT = RegVT; 8880 // If the operand is an FP value and we want it in integer registers, 8881 // use the corresponding integer type. This turns an f64 value into 8882 // i64, which can be passed with two i32 values on a 32-bit machine. 8883 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8884 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8885 if (OpInfo.Type == InlineAsm::isInput) 8886 OpInfo.CallOperand = 8887 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8888 OpInfo.ConstraintVT = VT; 8889 } 8890 } 8891 } 8892 8893 // No need to allocate a matching input constraint since the constraint it's 8894 // matching to has already been allocated. 8895 if (OpInfo.isMatchingInputConstraint()) 8896 return std::nullopt; 8897 8898 EVT ValueVT = OpInfo.ConstraintVT; 8899 if (OpInfo.ConstraintVT == MVT::Other) 8900 ValueVT = RegVT; 8901 8902 // Initialize NumRegs. 8903 unsigned NumRegs = 1; 8904 if (OpInfo.ConstraintVT != MVT::Other) 8905 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT); 8906 8907 // If this is a constraint for a specific physical register, like {r17}, 8908 // assign it now. 8909 8910 // If this associated to a specific register, initialize iterator to correct 8911 // place. If virtual, make sure we have enough registers 8912 8913 // Initialize iterator if necessary 8914 TargetRegisterClass::iterator I = RC->begin(); 8915 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8916 8917 // Do not check for single registers. 8918 if (AssignedReg) { 8919 I = std::find(I, RC->end(), AssignedReg); 8920 if (I == RC->end()) { 8921 // RC does not contain the selected register, which indicates a 8922 // mismatch between the register and the required type/bitwidth. 8923 return {AssignedReg}; 8924 } 8925 } 8926 8927 for (; NumRegs; --NumRegs, ++I) { 8928 assert(I != RC->end() && "Ran out of registers to allocate!"); 8929 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8930 Regs.push_back(R); 8931 } 8932 8933 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8934 return std::nullopt; 8935 } 8936 8937 static unsigned 8938 findMatchingInlineAsmOperand(unsigned OperandNo, 8939 const std::vector<SDValue> &AsmNodeOperands) { 8940 // Scan until we find the definition we already emitted of this operand. 8941 unsigned CurOp = InlineAsm::Op_FirstOperand; 8942 for (; OperandNo; --OperandNo) { 8943 // Advance to the next operand. 8944 unsigned OpFlag = 8945 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8946 assert((InlineAsm::isRegDefKind(OpFlag) || 8947 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8948 InlineAsm::isMemKind(OpFlag)) && 8949 "Skipped past definitions?"); 8950 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8951 } 8952 return CurOp; 8953 } 8954 8955 namespace { 8956 8957 class ExtraFlags { 8958 unsigned Flags = 0; 8959 8960 public: 8961 explicit ExtraFlags(const CallBase &Call) { 8962 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8963 if (IA->hasSideEffects()) 8964 Flags |= InlineAsm::Extra_HasSideEffects; 8965 if (IA->isAlignStack()) 8966 Flags |= InlineAsm::Extra_IsAlignStack; 8967 if (Call.isConvergent()) 8968 Flags |= InlineAsm::Extra_IsConvergent; 8969 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8970 } 8971 8972 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8973 // Ideally, we would only check against memory constraints. However, the 8974 // meaning of an Other constraint can be target-specific and we can't easily 8975 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8976 // for Other constraints as well. 8977 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8978 OpInfo.ConstraintType == TargetLowering::C_Other) { 8979 if (OpInfo.Type == InlineAsm::isInput) 8980 Flags |= InlineAsm::Extra_MayLoad; 8981 else if (OpInfo.Type == InlineAsm::isOutput) 8982 Flags |= InlineAsm::Extra_MayStore; 8983 else if (OpInfo.Type == InlineAsm::isClobber) 8984 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8985 } 8986 } 8987 8988 unsigned get() const { return Flags; } 8989 }; 8990 8991 } // end anonymous namespace 8992 8993 static bool isFunction(SDValue Op) { 8994 if (Op && Op.getOpcode() == ISD::GlobalAddress) { 8995 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 8996 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal()); 8997 8998 // In normal "call dllimport func" instruction (non-inlineasm) it force 8999 // indirect access by specifing call opcode. And usually specially print 9000 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can 9001 // not do in this way now. (In fact, this is similar with "Data Access" 9002 // action). So here we ignore dllimport function. 9003 if (Fn && !Fn->hasDLLImportStorageClass()) 9004 return true; 9005 } 9006 } 9007 return false; 9008 } 9009 9010 /// visitInlineAsm - Handle a call to an InlineAsm object. 9011 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call, 9012 const BasicBlock *EHPadBB) { 9013 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 9014 9015 /// ConstraintOperands - Information about all of the constraints. 9016 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 9017 9018 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9019 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 9020 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 9021 9022 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 9023 // AsmDialect, MayLoad, MayStore). 9024 bool HasSideEffect = IA->hasSideEffects(); 9025 ExtraFlags ExtraInfo(Call); 9026 9027 for (auto &T : TargetConstraints) { 9028 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 9029 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 9030 9031 if (OpInfo.CallOperandVal) 9032 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 9033 9034 if (!HasSideEffect) 9035 HasSideEffect = OpInfo.hasMemory(TLI); 9036 9037 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 9038 // FIXME: Could we compute this on OpInfo rather than T? 9039 9040 // Compute the constraint code and ConstraintType to use. 9041 TLI.ComputeConstraintToUse(T, SDValue()); 9042 9043 if (T.ConstraintType == TargetLowering::C_Immediate && 9044 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 9045 // We've delayed emitting a diagnostic like the "n" constraint because 9046 // inlining could cause an integer showing up. 9047 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 9048 "' expects an integer constant " 9049 "expression"); 9050 9051 ExtraInfo.update(T); 9052 } 9053 9054 // We won't need to flush pending loads if this asm doesn't touch 9055 // memory and is nonvolatile. 9056 SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 9057 9058 bool EmitEHLabels = isa<InvokeInst>(Call); 9059 if (EmitEHLabels) { 9060 assert(EHPadBB && "InvokeInst must have an EHPadBB"); 9061 } 9062 bool IsCallBr = isa<CallBrInst>(Call); 9063 9064 if (IsCallBr || EmitEHLabels) { 9065 // If this is a callbr or invoke we need to flush pending exports since 9066 // inlineasm_br and invoke are terminators. 9067 // We need to do this before nodes are glued to the inlineasm_br node. 9068 Chain = getControlRoot(); 9069 } 9070 9071 MCSymbol *BeginLabel = nullptr; 9072 if (EmitEHLabels) { 9073 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel); 9074 } 9075 9076 int OpNo = -1; 9077 SmallVector<StringRef> AsmStrs; 9078 IA->collectAsmStrs(AsmStrs); 9079 9080 // Second pass over the constraints: compute which constraint option to use. 9081 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9082 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput) 9083 OpNo++; 9084 9085 // If this is an output operand with a matching input operand, look up the 9086 // matching input. If their types mismatch, e.g. one is an integer, the 9087 // other is floating point, or their sizes are different, flag it as an 9088 // error. 9089 if (OpInfo.hasMatchingInput()) { 9090 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 9091 patchMatchingInput(OpInfo, Input, DAG); 9092 } 9093 9094 // Compute the constraint code and ConstraintType to use. 9095 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 9096 9097 if ((OpInfo.ConstraintType == TargetLowering::C_Memory && 9098 OpInfo.Type == InlineAsm::isClobber) || 9099 OpInfo.ConstraintType == TargetLowering::C_Address) 9100 continue; 9101 9102 // In Linux PIC model, there are 4 cases about value/label addressing: 9103 // 9104 // 1: Function call or Label jmp inside the module. 9105 // 2: Data access (such as global variable, static variable) inside module. 9106 // 3: Function call or Label jmp outside the module. 9107 // 4: Data access (such as global variable) outside the module. 9108 // 9109 // Due to current llvm inline asm architecture designed to not "recognize" 9110 // the asm code, there are quite troubles for us to treat mem addressing 9111 // differently for same value/adress used in different instuctions. 9112 // For example, in pic model, call a func may in plt way or direclty 9113 // pc-related, but lea/mov a function adress may use got. 9114 // 9115 // Here we try to "recognize" function call for the case 1 and case 3 in 9116 // inline asm. And try to adjust the constraint for them. 9117 // 9118 // TODO: Due to current inline asm didn't encourage to jmp to the outsider 9119 // label, so here we don't handle jmp function label now, but we need to 9120 // enhance it (especilly in PIC model) if we meet meaningful requirements. 9121 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) && 9122 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) && 9123 TM.getCodeModel() != CodeModel::Large) { 9124 OpInfo.isIndirect = false; 9125 OpInfo.ConstraintType = TargetLowering::C_Address; 9126 } 9127 9128 // If this is a memory input, and if the operand is not indirect, do what we 9129 // need to provide an address for the memory input. 9130 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 9131 !OpInfo.isIndirect) { 9132 assert((OpInfo.isMultipleAlternative || 9133 (OpInfo.Type == InlineAsm::isInput)) && 9134 "Can only indirectify direct input operands!"); 9135 9136 // Memory operands really want the address of the value. 9137 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 9138 9139 // There is no longer a Value* corresponding to this operand. 9140 OpInfo.CallOperandVal = nullptr; 9141 9142 // It is now an indirect operand. 9143 OpInfo.isIndirect = true; 9144 } 9145 9146 } 9147 9148 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 9149 std::vector<SDValue> AsmNodeOperands; 9150 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 9151 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 9152 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 9153 9154 // If we have a !srcloc metadata node associated with it, we want to attach 9155 // this to the ultimately generated inline asm machineinstr. To do this, we 9156 // pass in the third operand as this (potentially null) inline asm MDNode. 9157 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 9158 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 9159 9160 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 9161 // bits as operand 3. 9162 AsmNodeOperands.push_back(DAG.getTargetConstant( 9163 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9164 9165 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 9166 // this, assign virtual and physical registers for inputs and otput. 9167 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9168 // Assign Registers. 9169 SDISelAsmOperandInfo &RefOpInfo = 9170 OpInfo.isMatchingInputConstraint() 9171 ? ConstraintOperands[OpInfo.getMatchedOperand()] 9172 : OpInfo; 9173 const auto RegError = 9174 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 9175 if (RegError) { 9176 const MachineFunction &MF = DAG.getMachineFunction(); 9177 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9178 const char *RegName = TRI.getName(*RegError); 9179 emitInlineAsmError(Call, "register '" + Twine(RegName) + 9180 "' allocated for constraint '" + 9181 Twine(OpInfo.ConstraintCode) + 9182 "' does not match required type"); 9183 return; 9184 } 9185 9186 auto DetectWriteToReservedRegister = [&]() { 9187 const MachineFunction &MF = DAG.getMachineFunction(); 9188 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9189 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 9190 if (Register::isPhysicalRegister(Reg) && 9191 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 9192 const char *RegName = TRI.getName(Reg); 9193 emitInlineAsmError(Call, "write to reserved register '" + 9194 Twine(RegName) + "'"); 9195 return true; 9196 } 9197 } 9198 return false; 9199 }; 9200 assert((OpInfo.ConstraintType != TargetLowering::C_Address || 9201 (OpInfo.Type == InlineAsm::isInput && 9202 !OpInfo.isMatchingInputConstraint())) && 9203 "Only address as input operand is allowed."); 9204 9205 switch (OpInfo.Type) { 9206 case InlineAsm::isOutput: 9207 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9208 unsigned ConstraintID = 9209 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9210 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9211 "Failed to convert memory constraint code to constraint id."); 9212 9213 // Add information to the INLINEASM node to know about this output. 9214 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9215 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 9216 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 9217 MVT::i32)); 9218 AsmNodeOperands.push_back(OpInfo.CallOperand); 9219 } else { 9220 // Otherwise, this outputs to a register (directly for C_Register / 9221 // C_RegisterClass, and a target-defined fashion for 9222 // C_Immediate/C_Other). Find a register that we can use. 9223 if (OpInfo.AssignedRegs.Regs.empty()) { 9224 emitInlineAsmError( 9225 Call, "couldn't allocate output register for constraint '" + 9226 Twine(OpInfo.ConstraintCode) + "'"); 9227 return; 9228 } 9229 9230 if (DetectWriteToReservedRegister()) 9231 return; 9232 9233 // Add information to the INLINEASM node to know that this register is 9234 // set. 9235 OpInfo.AssignedRegs.AddInlineAsmOperands( 9236 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 9237 : InlineAsm::Kind_RegDef, 9238 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 9239 } 9240 break; 9241 9242 case InlineAsm::isInput: 9243 case InlineAsm::isLabel: { 9244 SDValue InOperandVal = OpInfo.CallOperand; 9245 9246 if (OpInfo.isMatchingInputConstraint()) { 9247 // If this is required to match an output register we have already set, 9248 // just use its register. 9249 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 9250 AsmNodeOperands); 9251 unsigned OpFlag = 9252 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 9253 if (InlineAsm::isRegDefKind(OpFlag) || 9254 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 9255 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 9256 if (OpInfo.isIndirect) { 9257 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 9258 emitInlineAsmError(Call, "inline asm not supported yet: " 9259 "don't know how to handle tied " 9260 "indirect register inputs"); 9261 return; 9262 } 9263 9264 SmallVector<unsigned, 4> Regs; 9265 MachineFunction &MF = DAG.getMachineFunction(); 9266 MachineRegisterInfo &MRI = MF.getRegInfo(); 9267 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 9268 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]); 9269 Register TiedReg = R->getReg(); 9270 MVT RegVT = R->getSimpleValueType(0); 9271 const TargetRegisterClass *RC = 9272 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg) 9273 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT) 9274 : TRI.getMinimalPhysRegClass(TiedReg); 9275 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 9276 for (unsigned i = 0; i != NumRegs; ++i) 9277 Regs.push_back(MRI.createVirtualRegister(RC)); 9278 9279 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 9280 9281 SDLoc dl = getCurSDLoc(); 9282 // Use the produced MatchedRegs object to 9283 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call); 9284 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 9285 true, OpInfo.getMatchedOperand(), dl, 9286 DAG, AsmNodeOperands); 9287 break; 9288 } 9289 9290 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 9291 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 9292 "Unexpected number of operands"); 9293 // Add information to the INLINEASM node to know about this input. 9294 // See InlineAsm.h isUseOperandTiedToDef. 9295 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 9296 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 9297 OpInfo.getMatchedOperand()); 9298 AsmNodeOperands.push_back(DAG.getTargetConstant( 9299 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9300 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 9301 break; 9302 } 9303 9304 // Treat indirect 'X' constraint as memory. 9305 if (OpInfo.ConstraintType == TargetLowering::C_Other && 9306 OpInfo.isIndirect) 9307 OpInfo.ConstraintType = TargetLowering::C_Memory; 9308 9309 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 9310 OpInfo.ConstraintType == TargetLowering::C_Other) { 9311 std::vector<SDValue> Ops; 9312 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 9313 Ops, DAG); 9314 if (Ops.empty()) { 9315 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 9316 if (isa<ConstantSDNode>(InOperandVal)) { 9317 emitInlineAsmError(Call, "value out of range for constraint '" + 9318 Twine(OpInfo.ConstraintCode) + "'"); 9319 return; 9320 } 9321 9322 emitInlineAsmError(Call, 9323 "invalid operand for inline asm constraint '" + 9324 Twine(OpInfo.ConstraintCode) + "'"); 9325 return; 9326 } 9327 9328 // Add information to the INLINEASM node to know about this input. 9329 unsigned ResOpType = 9330 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 9331 AsmNodeOperands.push_back(DAG.getTargetConstant( 9332 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 9333 llvm::append_range(AsmNodeOperands, Ops); 9334 break; 9335 } 9336 9337 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 9338 assert((OpInfo.isIndirect || 9339 OpInfo.ConstraintType != TargetLowering::C_Memory) && 9340 "Operand must be indirect to be a mem!"); 9341 assert(InOperandVal.getValueType() == 9342 TLI.getPointerTy(DAG.getDataLayout()) && 9343 "Memory operands expect pointer values"); 9344 9345 unsigned ConstraintID = 9346 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9347 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9348 "Failed to convert memory constraint code to constraint id."); 9349 9350 // Add information to the INLINEASM node to know about this input. 9351 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9352 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9353 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 9354 getCurSDLoc(), 9355 MVT::i32)); 9356 AsmNodeOperands.push_back(InOperandVal); 9357 break; 9358 } 9359 9360 if (OpInfo.ConstraintType == TargetLowering::C_Address) { 9361 assert(InOperandVal.getValueType() == 9362 TLI.getPointerTy(DAG.getDataLayout()) && 9363 "Address operands expect pointer values"); 9364 9365 unsigned ConstraintID = 9366 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 9367 assert(ConstraintID != InlineAsm::Constraint_Unknown && 9368 "Failed to convert memory constraint code to constraint id."); 9369 9370 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 9371 9372 SDValue AsmOp = InOperandVal; 9373 if (isFunction(InOperandVal)) { 9374 auto *GA = cast<GlobalAddressSDNode>(InOperandVal); 9375 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1); 9376 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(), 9377 InOperandVal.getValueType(), 9378 GA->getOffset()); 9379 } 9380 9381 // Add information to the INLINEASM node to know about this input. 9382 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 9383 9384 AsmNodeOperands.push_back( 9385 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32)); 9386 9387 AsmNodeOperands.push_back(AsmOp); 9388 break; 9389 } 9390 9391 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 9392 OpInfo.ConstraintType == TargetLowering::C_Register) && 9393 "Unknown constraint type!"); 9394 9395 // TODO: Support this. 9396 if (OpInfo.isIndirect) { 9397 emitInlineAsmError( 9398 Call, "Don't know how to handle indirect register inputs yet " 9399 "for constraint '" + 9400 Twine(OpInfo.ConstraintCode) + "'"); 9401 return; 9402 } 9403 9404 // Copy the input into the appropriate registers. 9405 if (OpInfo.AssignedRegs.Regs.empty()) { 9406 emitInlineAsmError(Call, 9407 "couldn't allocate input reg for constraint '" + 9408 Twine(OpInfo.ConstraintCode) + "'"); 9409 return; 9410 } 9411 9412 if (DetectWriteToReservedRegister()) 9413 return; 9414 9415 SDLoc dl = getCurSDLoc(); 9416 9417 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, 9418 &Call); 9419 9420 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 9421 dl, DAG, AsmNodeOperands); 9422 break; 9423 } 9424 case InlineAsm::isClobber: 9425 // Add the clobbered value to the operand list, so that the register 9426 // allocator is aware that the physreg got clobbered. 9427 if (!OpInfo.AssignedRegs.Regs.empty()) 9428 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 9429 false, 0, getCurSDLoc(), DAG, 9430 AsmNodeOperands); 9431 break; 9432 } 9433 } 9434 9435 // Finish up input operands. Set the input chain and add the flag last. 9436 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 9437 if (Glue.getNode()) AsmNodeOperands.push_back(Glue); 9438 9439 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 9440 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 9441 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 9442 Glue = Chain.getValue(1); 9443 9444 // Do additional work to generate outputs. 9445 9446 SmallVector<EVT, 1> ResultVTs; 9447 SmallVector<SDValue, 1> ResultValues; 9448 SmallVector<SDValue, 8> OutChains; 9449 9450 llvm::Type *CallResultType = Call.getType(); 9451 ArrayRef<Type *> ResultTypes; 9452 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 9453 ResultTypes = StructResult->elements(); 9454 else if (!CallResultType->isVoidTy()) 9455 ResultTypes = ArrayRef(CallResultType); 9456 9457 auto CurResultType = ResultTypes.begin(); 9458 auto handleRegAssign = [&](SDValue V) { 9459 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 9460 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 9461 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 9462 ++CurResultType; 9463 // If the type of the inline asm call site return value is different but has 9464 // same size as the type of the asm output bitcast it. One example of this 9465 // is for vectors with different width / number of elements. This can 9466 // happen for register classes that can contain multiple different value 9467 // types. The preg or vreg allocated may not have the same VT as was 9468 // expected. 9469 // 9470 // This can also happen for a return value that disagrees with the register 9471 // class it is put in, eg. a double in a general-purpose register on a 9472 // 32-bit machine. 9473 if (ResultVT != V.getValueType() && 9474 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 9475 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 9476 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 9477 V.getValueType().isInteger()) { 9478 // If a result value was tied to an input value, the computed result 9479 // may have a wider width than the expected result. Extract the 9480 // relevant portion. 9481 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 9482 } 9483 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 9484 ResultVTs.push_back(ResultVT); 9485 ResultValues.push_back(V); 9486 }; 9487 9488 // Deal with output operands. 9489 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 9490 if (OpInfo.Type == InlineAsm::isOutput) { 9491 SDValue Val; 9492 // Skip trivial output operands. 9493 if (OpInfo.AssignedRegs.Regs.empty()) 9494 continue; 9495 9496 switch (OpInfo.ConstraintType) { 9497 case TargetLowering::C_Register: 9498 case TargetLowering::C_RegisterClass: 9499 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 9500 Chain, &Glue, &Call); 9501 break; 9502 case TargetLowering::C_Immediate: 9503 case TargetLowering::C_Other: 9504 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(), 9505 OpInfo, DAG); 9506 break; 9507 case TargetLowering::C_Memory: 9508 break; // Already handled. 9509 case TargetLowering::C_Address: 9510 break; // Silence warning. 9511 case TargetLowering::C_Unknown: 9512 assert(false && "Unexpected unknown constraint"); 9513 } 9514 9515 // Indirect output manifest as stores. Record output chains. 9516 if (OpInfo.isIndirect) { 9517 const Value *Ptr = OpInfo.CallOperandVal; 9518 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 9519 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 9520 MachinePointerInfo(Ptr)); 9521 OutChains.push_back(Store); 9522 } else { 9523 // generate CopyFromRegs to associated registers. 9524 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 9525 if (Val.getOpcode() == ISD::MERGE_VALUES) { 9526 for (const SDValue &V : Val->op_values()) 9527 handleRegAssign(V); 9528 } else 9529 handleRegAssign(Val); 9530 } 9531 } 9532 } 9533 9534 // Set results. 9535 if (!ResultValues.empty()) { 9536 assert(CurResultType == ResultTypes.end() && 9537 "Mismatch in number of ResultTypes"); 9538 assert(ResultValues.size() == ResultTypes.size() && 9539 "Mismatch in number of output operands in asm result"); 9540 9541 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 9542 DAG.getVTList(ResultVTs), ResultValues); 9543 setValue(&Call, V); 9544 } 9545 9546 // Collect store chains. 9547 if (!OutChains.empty()) 9548 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 9549 9550 if (EmitEHLabels) { 9551 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel); 9552 } 9553 9554 // Only Update Root if inline assembly has a memory effect. 9555 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr || 9556 EmitEHLabels) 9557 DAG.setRoot(Chain); 9558 } 9559 9560 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 9561 const Twine &Message) { 9562 LLVMContext &Ctx = *DAG.getContext(); 9563 Ctx.emitError(&Call, Message); 9564 9565 // Make sure we leave the DAG in a valid state 9566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9567 SmallVector<EVT, 1> ValueVTs; 9568 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 9569 9570 if (ValueVTs.empty()) 9571 return; 9572 9573 SmallVector<SDValue, 1> Ops; 9574 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 9575 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 9576 9577 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 9578 } 9579 9580 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 9581 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 9582 MVT::Other, getRoot(), 9583 getValue(I.getArgOperand(0)), 9584 DAG.getSrcValue(I.getArgOperand(0)))); 9585 } 9586 9587 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 9588 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9589 const DataLayout &DL = DAG.getDataLayout(); 9590 SDValue V = DAG.getVAArg( 9591 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 9592 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 9593 DL.getABITypeAlign(I.getType()).value()); 9594 DAG.setRoot(V.getValue(1)); 9595 9596 if (I.getType()->isPointerTy()) 9597 V = DAG.getPtrExtOrTrunc( 9598 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 9599 setValue(&I, V); 9600 } 9601 9602 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 9603 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 9604 MVT::Other, getRoot(), 9605 getValue(I.getArgOperand(0)), 9606 DAG.getSrcValue(I.getArgOperand(0)))); 9607 } 9608 9609 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 9610 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 9611 MVT::Other, getRoot(), 9612 getValue(I.getArgOperand(0)), 9613 getValue(I.getArgOperand(1)), 9614 DAG.getSrcValue(I.getArgOperand(0)), 9615 DAG.getSrcValue(I.getArgOperand(1)))); 9616 } 9617 9618 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 9619 const Instruction &I, 9620 SDValue Op) { 9621 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 9622 if (!Range) 9623 return Op; 9624 9625 ConstantRange CR = getConstantRangeFromMetadata(*Range); 9626 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 9627 return Op; 9628 9629 APInt Lo = CR.getUnsignedMin(); 9630 if (!Lo.isMinValue()) 9631 return Op; 9632 9633 APInt Hi = CR.getUnsignedMax(); 9634 unsigned Bits = std::max(Hi.getActiveBits(), 9635 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 9636 9637 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9638 9639 SDLoc SL = getCurSDLoc(); 9640 9641 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 9642 DAG.getValueType(SmallVT)); 9643 unsigned NumVals = Op.getNode()->getNumValues(); 9644 if (NumVals == 1) 9645 return ZExt; 9646 9647 SmallVector<SDValue, 4> Ops; 9648 9649 Ops.push_back(ZExt); 9650 for (unsigned I = 1; I != NumVals; ++I) 9651 Ops.push_back(Op.getValue(I)); 9652 9653 return DAG.getMergeValues(Ops, SL); 9654 } 9655 9656 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 9657 /// the call being lowered. 9658 /// 9659 /// This is a helper for lowering intrinsics that follow a target calling 9660 /// convention or require stack pointer adjustment. Only a subset of the 9661 /// intrinsic's operands need to participate in the calling convention. 9662 void SelectionDAGBuilder::populateCallLoweringInfo( 9663 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 9664 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 9665 bool IsPatchPoint) { 9666 TargetLowering::ArgListTy Args; 9667 Args.reserve(NumArgs); 9668 9669 // Populate the argument list. 9670 // Attributes for args start at offset 1, after the return attribute. 9671 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 9672 ArgI != ArgE; ++ArgI) { 9673 const Value *V = Call->getOperand(ArgI); 9674 9675 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 9676 9677 TargetLowering::ArgListEntry Entry; 9678 Entry.Node = getValue(V); 9679 Entry.Ty = V->getType(); 9680 Entry.setAttributes(Call, ArgI); 9681 Args.push_back(Entry); 9682 } 9683 9684 CLI.setDebugLoc(getCurSDLoc()) 9685 .setChain(getRoot()) 9686 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 9687 .setDiscardResult(Call->use_empty()) 9688 .setIsPatchPoint(IsPatchPoint) 9689 .setIsPreallocated( 9690 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 9691 } 9692 9693 /// Add a stack map intrinsic call's live variable operands to a stackmap 9694 /// or patchpoint target node's operand list. 9695 /// 9696 /// Constants are converted to TargetConstants purely as an optimization to 9697 /// avoid constant materialization and register allocation. 9698 /// 9699 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 9700 /// generate addess computation nodes, and so FinalizeISel can convert the 9701 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 9702 /// address materialization and register allocation, but may also be required 9703 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 9704 /// alloca in the entry block, then the runtime may assume that the alloca's 9705 /// StackMap location can be read immediately after compilation and that the 9706 /// location is valid at any point during execution (this is similar to the 9707 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 9708 /// only available in a register, then the runtime would need to trap when 9709 /// execution reaches the StackMap in order to read the alloca's location. 9710 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 9711 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 9712 SelectionDAGBuilder &Builder) { 9713 SelectionDAG &DAG = Builder.DAG; 9714 for (unsigned I = StartIdx; I < Call.arg_size(); I++) { 9715 SDValue Op = Builder.getValue(Call.getArgOperand(I)); 9716 9717 // Things on the stack are pointer-typed, meaning that they are already 9718 // legal and can be emitted directly to target nodes. 9719 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 9720 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType())); 9721 } else { 9722 // Otherwise emit a target independent node to be legalised. 9723 Ops.push_back(Builder.getValue(Call.getArgOperand(I))); 9724 } 9725 } 9726 } 9727 9728 /// Lower llvm.experimental.stackmap. 9729 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 9730 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 9731 // [live variables...]) 9732 9733 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 9734 9735 SDValue Chain, InGlue, Callee; 9736 SmallVector<SDValue, 32> Ops; 9737 9738 SDLoc DL = getCurSDLoc(); 9739 Callee = getValue(CI.getCalledOperand()); 9740 9741 // The stackmap intrinsic only records the live variables (the arguments 9742 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 9743 // intrinsic, this won't be lowered to a function call. This means we don't 9744 // have to worry about calling conventions and target specific lowering code. 9745 // Instead we perform the call lowering right here. 9746 // 9747 // chain, flag = CALLSEQ_START(chain, 0, 0) 9748 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 9749 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 9750 // 9751 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 9752 InGlue = Chain.getValue(1); 9753 9754 // Add the STACKMAP operands, starting with DAG house-keeping. 9755 Ops.push_back(Chain); 9756 Ops.push_back(InGlue); 9757 9758 // Add the <id>, <numShadowBytes> operands. 9759 // 9760 // These do not require legalisation, and can be emitted directly to target 9761 // constant nodes. 9762 SDValue ID = getValue(CI.getArgOperand(0)); 9763 assert(ID.getValueType() == MVT::i64); 9764 SDValue IDConst = DAG.getTargetConstant( 9765 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType()); 9766 Ops.push_back(IDConst); 9767 9768 SDValue Shad = getValue(CI.getArgOperand(1)); 9769 assert(Shad.getValueType() == MVT::i32); 9770 SDValue ShadConst = DAG.getTargetConstant( 9771 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType()); 9772 Ops.push_back(ShadConst); 9773 9774 // Add the live variables. 9775 addStackMapLiveVars(CI, 2, DL, Ops, *this); 9776 9777 // Create the STACKMAP node. 9778 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9779 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops); 9780 InGlue = Chain.getValue(1); 9781 9782 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL); 9783 9784 // Stackmaps don't generate values, so nothing goes into the NodeMap. 9785 9786 // Set the root to the target-lowered call chain. 9787 DAG.setRoot(Chain); 9788 9789 // Inform the Frame Information that we have a stackmap in this function. 9790 FuncInfo.MF->getFrameInfo().setHasStackMap(); 9791 } 9792 9793 /// Lower llvm.experimental.patchpoint directly to its target opcode. 9794 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 9795 const BasicBlock *EHPadBB) { 9796 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 9797 // i32 <numBytes>, 9798 // i8* <target>, 9799 // i32 <numArgs>, 9800 // [Args...], 9801 // [live variables...]) 9802 9803 CallingConv::ID CC = CB.getCallingConv(); 9804 bool IsAnyRegCC = CC == CallingConv::AnyReg; 9805 bool HasDef = !CB.getType()->isVoidTy(); 9806 SDLoc dl = getCurSDLoc(); 9807 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 9808 9809 // Handle immediate and symbolic callees. 9810 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 9811 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 9812 /*isTarget=*/true); 9813 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 9814 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 9815 SDLoc(SymbolicCallee), 9816 SymbolicCallee->getValueType(0)); 9817 9818 // Get the real number of arguments participating in the call <numArgs> 9819 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 9820 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 9821 9822 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 9823 // Intrinsics include all meta-operands up to but not including CC. 9824 unsigned NumMetaOpers = PatchPointOpers::CCPos; 9825 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 9826 "Not enough arguments provided to the patchpoint intrinsic"); 9827 9828 // For AnyRegCC the arguments are lowered later on manually. 9829 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 9830 Type *ReturnTy = 9831 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 9832 9833 TargetLowering::CallLoweringInfo CLI(DAG); 9834 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 9835 ReturnTy, true); 9836 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 9837 9838 SDNode *CallEnd = Result.second.getNode(); 9839 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 9840 CallEnd = CallEnd->getOperand(0).getNode(); 9841 9842 /// Get a call instruction from the call sequence chain. 9843 /// Tail calls are not allowed. 9844 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 9845 "Expected a callseq node."); 9846 SDNode *Call = CallEnd->getOperand(0).getNode(); 9847 bool HasGlue = Call->getGluedNode(); 9848 9849 // Replace the target specific call node with the patchable intrinsic. 9850 SmallVector<SDValue, 8> Ops; 9851 9852 // Push the chain. 9853 Ops.push_back(*(Call->op_begin())); 9854 9855 // Optionally, push the glue (if any). 9856 if (HasGlue) 9857 Ops.push_back(*(Call->op_end() - 1)); 9858 9859 // Push the register mask info. 9860 if (HasGlue) 9861 Ops.push_back(*(Call->op_end() - 2)); 9862 else 9863 Ops.push_back(*(Call->op_end() - 1)); 9864 9865 // Add the <id> and <numBytes> constants. 9866 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9867 Ops.push_back(DAG.getTargetConstant( 9868 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9869 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9870 Ops.push_back(DAG.getTargetConstant( 9871 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9872 MVT::i32)); 9873 9874 // Add the callee. 9875 Ops.push_back(Callee); 9876 9877 // Adjust <numArgs> to account for any arguments that have been passed on the 9878 // stack instead. 9879 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9880 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9881 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9882 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9883 9884 // Add the calling convention 9885 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9886 9887 // Add the arguments we omitted previously. The register allocator should 9888 // place these in any free register. 9889 if (IsAnyRegCC) 9890 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9891 Ops.push_back(getValue(CB.getArgOperand(i))); 9892 9893 // Push the arguments from the call instruction. 9894 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9895 Ops.append(Call->op_begin() + 2, e); 9896 9897 // Push live variables for the stack map. 9898 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9899 9900 SDVTList NodeTys; 9901 if (IsAnyRegCC && HasDef) { 9902 // Create the return types based on the intrinsic definition 9903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9904 SmallVector<EVT, 3> ValueVTs; 9905 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9906 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9907 9908 // There is always a chain and a glue type at the end 9909 ValueVTs.push_back(MVT::Other); 9910 ValueVTs.push_back(MVT::Glue); 9911 NodeTys = DAG.getVTList(ValueVTs); 9912 } else 9913 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9914 9915 // Replace the target specific call node with a PATCHPOINT node. 9916 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops); 9917 9918 // Update the NodeMap. 9919 if (HasDef) { 9920 if (IsAnyRegCC) 9921 setValue(&CB, SDValue(PPV.getNode(), 0)); 9922 else 9923 setValue(&CB, Result.first); 9924 } 9925 9926 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9927 // call sequence. Furthermore the location of the chain and glue can change 9928 // when the AnyReg calling convention is used and the intrinsic returns a 9929 // value. 9930 if (IsAnyRegCC && HasDef) { 9931 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9932 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)}; 9933 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9934 } else 9935 DAG.ReplaceAllUsesWith(Call, PPV.getNode()); 9936 DAG.DeleteNode(Call); 9937 9938 // Inform the Frame Information that we have a patchpoint in this function. 9939 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9940 } 9941 9942 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9943 unsigned Intrinsic) { 9944 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9945 SDValue Op1 = getValue(I.getArgOperand(0)); 9946 SDValue Op2; 9947 if (I.arg_size() > 1) 9948 Op2 = getValue(I.getArgOperand(1)); 9949 SDLoc dl = getCurSDLoc(); 9950 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9951 SDValue Res; 9952 SDNodeFlags SDFlags; 9953 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9954 SDFlags.copyFMF(*FPMO); 9955 9956 switch (Intrinsic) { 9957 case Intrinsic::vector_reduce_fadd: 9958 if (SDFlags.hasAllowReassociation()) 9959 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9960 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9961 SDFlags); 9962 else 9963 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9964 break; 9965 case Intrinsic::vector_reduce_fmul: 9966 if (SDFlags.hasAllowReassociation()) 9967 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9968 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9969 SDFlags); 9970 else 9971 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9972 break; 9973 case Intrinsic::vector_reduce_add: 9974 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9975 break; 9976 case Intrinsic::vector_reduce_mul: 9977 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9978 break; 9979 case Intrinsic::vector_reduce_and: 9980 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9981 break; 9982 case Intrinsic::vector_reduce_or: 9983 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9984 break; 9985 case Intrinsic::vector_reduce_xor: 9986 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9987 break; 9988 case Intrinsic::vector_reduce_smax: 9989 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9990 break; 9991 case Intrinsic::vector_reduce_smin: 9992 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9993 break; 9994 case Intrinsic::vector_reduce_umax: 9995 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9996 break; 9997 case Intrinsic::vector_reduce_umin: 9998 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9999 break; 10000 case Intrinsic::vector_reduce_fmax: 10001 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 10002 break; 10003 case Intrinsic::vector_reduce_fmin: 10004 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 10005 break; 10006 case Intrinsic::vector_reduce_fmaximum: 10007 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags); 10008 break; 10009 case Intrinsic::vector_reduce_fminimum: 10010 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags); 10011 break; 10012 default: 10013 llvm_unreachable("Unhandled vector reduce intrinsic"); 10014 } 10015 setValue(&I, Res); 10016 } 10017 10018 /// Returns an AttributeList representing the attributes applied to the return 10019 /// value of the given call. 10020 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 10021 SmallVector<Attribute::AttrKind, 2> Attrs; 10022 if (CLI.RetSExt) 10023 Attrs.push_back(Attribute::SExt); 10024 if (CLI.RetZExt) 10025 Attrs.push_back(Attribute::ZExt); 10026 if (CLI.IsInReg) 10027 Attrs.push_back(Attribute::InReg); 10028 10029 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 10030 Attrs); 10031 } 10032 10033 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 10034 /// implementation, which just calls LowerCall. 10035 /// FIXME: When all targets are 10036 /// migrated to using LowerCall, this hook should be integrated into SDISel. 10037 std::pair<SDValue, SDValue> 10038 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 10039 // Handle the incoming return values from the call. 10040 CLI.Ins.clear(); 10041 Type *OrigRetTy = CLI.RetTy; 10042 SmallVector<EVT, 4> RetTys; 10043 SmallVector<uint64_t, 4> Offsets; 10044 auto &DL = CLI.DAG.getDataLayout(); 10045 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets, 0); 10046 10047 if (CLI.IsPostTypeLegalization) { 10048 // If we are lowering a libcall after legalization, split the return type. 10049 SmallVector<EVT, 4> OldRetTys; 10050 SmallVector<uint64_t, 4> OldOffsets; 10051 RetTys.swap(OldRetTys); 10052 Offsets.swap(OldOffsets); 10053 10054 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 10055 EVT RetVT = OldRetTys[i]; 10056 uint64_t Offset = OldOffsets[i]; 10057 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 10058 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 10059 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 10060 RetTys.append(NumRegs, RegisterVT); 10061 for (unsigned j = 0; j != NumRegs; ++j) 10062 Offsets.push_back(Offset + j * RegisterVTByteSZ); 10063 } 10064 } 10065 10066 SmallVector<ISD::OutputArg, 4> Outs; 10067 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 10068 10069 bool CanLowerReturn = 10070 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 10071 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 10072 10073 SDValue DemoteStackSlot; 10074 int DemoteStackIdx = -100; 10075 if (!CanLowerReturn) { 10076 // FIXME: equivalent assert? 10077 // assert(!CS.hasInAllocaArgument() && 10078 // "sret demotion is incompatible with inalloca"); 10079 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 10080 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 10081 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10082 DemoteStackIdx = 10083 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 10084 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 10085 DL.getAllocaAddrSpace()); 10086 10087 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 10088 ArgListEntry Entry; 10089 Entry.Node = DemoteStackSlot; 10090 Entry.Ty = StackSlotPtrType; 10091 Entry.IsSExt = false; 10092 Entry.IsZExt = false; 10093 Entry.IsInReg = false; 10094 Entry.IsSRet = true; 10095 Entry.IsNest = false; 10096 Entry.IsByVal = false; 10097 Entry.IsByRef = false; 10098 Entry.IsReturned = false; 10099 Entry.IsSwiftSelf = false; 10100 Entry.IsSwiftAsync = false; 10101 Entry.IsSwiftError = false; 10102 Entry.IsCFGuardTarget = false; 10103 Entry.Alignment = Alignment; 10104 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 10105 CLI.NumFixedArgs += 1; 10106 CLI.getArgs()[0].IndirectType = CLI.RetTy; 10107 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 10108 10109 // sret demotion isn't compatible with tail-calls, since the sret argument 10110 // points into the callers stack frame. 10111 CLI.IsTailCall = false; 10112 } else { 10113 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10114 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL); 10115 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10116 ISD::ArgFlagsTy Flags; 10117 if (NeedsRegBlock) { 10118 Flags.setInConsecutiveRegs(); 10119 if (I == RetTys.size() - 1) 10120 Flags.setInConsecutiveRegsLast(); 10121 } 10122 EVT VT = RetTys[I]; 10123 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10124 CLI.CallConv, VT); 10125 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10126 CLI.CallConv, VT); 10127 for (unsigned i = 0; i != NumRegs; ++i) { 10128 ISD::InputArg MyFlags; 10129 MyFlags.Flags = Flags; 10130 MyFlags.VT = RegisterVT; 10131 MyFlags.ArgVT = VT; 10132 MyFlags.Used = CLI.IsReturnValueUsed; 10133 if (CLI.RetTy->isPointerTy()) { 10134 MyFlags.Flags.setPointer(); 10135 MyFlags.Flags.setPointerAddrSpace( 10136 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 10137 } 10138 if (CLI.RetSExt) 10139 MyFlags.Flags.setSExt(); 10140 if (CLI.RetZExt) 10141 MyFlags.Flags.setZExt(); 10142 if (CLI.IsInReg) 10143 MyFlags.Flags.setInReg(); 10144 CLI.Ins.push_back(MyFlags); 10145 } 10146 } 10147 } 10148 10149 // We push in swifterror return as the last element of CLI.Ins. 10150 ArgListTy &Args = CLI.getArgs(); 10151 if (supportSwiftError()) { 10152 for (const ArgListEntry &Arg : Args) { 10153 if (Arg.IsSwiftError) { 10154 ISD::InputArg MyFlags; 10155 MyFlags.VT = getPointerTy(DL); 10156 MyFlags.ArgVT = EVT(getPointerTy(DL)); 10157 MyFlags.Flags.setSwiftError(); 10158 CLI.Ins.push_back(MyFlags); 10159 } 10160 } 10161 } 10162 10163 // Handle all of the outgoing arguments. 10164 CLI.Outs.clear(); 10165 CLI.OutVals.clear(); 10166 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 10167 SmallVector<EVT, 4> ValueVTs; 10168 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 10169 // FIXME: Split arguments if CLI.IsPostTypeLegalization 10170 Type *FinalType = Args[i].Ty; 10171 if (Args[i].IsByVal) 10172 FinalType = Args[i].IndirectType; 10173 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 10174 FinalType, CLI.CallConv, CLI.IsVarArg, DL); 10175 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 10176 ++Value) { 10177 EVT VT = ValueVTs[Value]; 10178 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 10179 SDValue Op = SDValue(Args[i].Node.getNode(), 10180 Args[i].Node.getResNo() + Value); 10181 ISD::ArgFlagsTy Flags; 10182 10183 // Certain targets (such as MIPS), may have a different ABI alignment 10184 // for a type depending on the context. Give the target a chance to 10185 // specify the alignment it wants. 10186 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 10187 Flags.setOrigAlign(OriginalAlignment); 10188 10189 if (Args[i].Ty->isPointerTy()) { 10190 Flags.setPointer(); 10191 Flags.setPointerAddrSpace( 10192 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 10193 } 10194 if (Args[i].IsZExt) 10195 Flags.setZExt(); 10196 if (Args[i].IsSExt) 10197 Flags.setSExt(); 10198 if (Args[i].IsInReg) { 10199 // If we are using vectorcall calling convention, a structure that is 10200 // passed InReg - is surely an HVA 10201 if (CLI.CallConv == CallingConv::X86_VectorCall && 10202 isa<StructType>(FinalType)) { 10203 // The first value of a structure is marked 10204 if (0 == Value) 10205 Flags.setHvaStart(); 10206 Flags.setHva(); 10207 } 10208 // Set InReg Flag 10209 Flags.setInReg(); 10210 } 10211 if (Args[i].IsSRet) 10212 Flags.setSRet(); 10213 if (Args[i].IsSwiftSelf) 10214 Flags.setSwiftSelf(); 10215 if (Args[i].IsSwiftAsync) 10216 Flags.setSwiftAsync(); 10217 if (Args[i].IsSwiftError) 10218 Flags.setSwiftError(); 10219 if (Args[i].IsCFGuardTarget) 10220 Flags.setCFGuardTarget(); 10221 if (Args[i].IsByVal) 10222 Flags.setByVal(); 10223 if (Args[i].IsByRef) 10224 Flags.setByRef(); 10225 if (Args[i].IsPreallocated) { 10226 Flags.setPreallocated(); 10227 // Set the byval flag for CCAssignFn callbacks that don't know about 10228 // preallocated. This way we can know how many bytes we should've 10229 // allocated and how many bytes a callee cleanup function will pop. If 10230 // we port preallocated to more targets, we'll have to add custom 10231 // preallocated handling in the various CC lowering callbacks. 10232 Flags.setByVal(); 10233 } 10234 if (Args[i].IsInAlloca) { 10235 Flags.setInAlloca(); 10236 // Set the byval flag for CCAssignFn callbacks that don't know about 10237 // inalloca. This way we can know how many bytes we should've allocated 10238 // and how many bytes a callee cleanup function will pop. If we port 10239 // inalloca to more targets, we'll have to add custom inalloca handling 10240 // in the various CC lowering callbacks. 10241 Flags.setByVal(); 10242 } 10243 Align MemAlign; 10244 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 10245 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType); 10246 Flags.setByValSize(FrameSize); 10247 10248 // info is not there but there are cases it cannot get right. 10249 if (auto MA = Args[i].Alignment) 10250 MemAlign = *MA; 10251 else 10252 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL)); 10253 } else if (auto MA = Args[i].Alignment) { 10254 MemAlign = *MA; 10255 } else { 10256 MemAlign = OriginalAlignment; 10257 } 10258 Flags.setMemAlign(MemAlign); 10259 if (Args[i].IsNest) 10260 Flags.setNest(); 10261 if (NeedsRegBlock) 10262 Flags.setInConsecutiveRegs(); 10263 10264 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10265 CLI.CallConv, VT); 10266 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10267 CLI.CallConv, VT); 10268 SmallVector<SDValue, 4> Parts(NumParts); 10269 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 10270 10271 if (Args[i].IsSExt) 10272 ExtendKind = ISD::SIGN_EXTEND; 10273 else if (Args[i].IsZExt) 10274 ExtendKind = ISD::ZERO_EXTEND; 10275 10276 // Conservatively only handle 'returned' on non-vectors that can be lowered, 10277 // for now. 10278 if (Args[i].IsReturned && !Op.getValueType().isVector() && 10279 CanLowerReturn) { 10280 assert((CLI.RetTy == Args[i].Ty || 10281 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 10282 CLI.RetTy->getPointerAddressSpace() == 10283 Args[i].Ty->getPointerAddressSpace())) && 10284 RetTys.size() == NumValues && "unexpected use of 'returned'"); 10285 // Before passing 'returned' to the target lowering code, ensure that 10286 // either the register MVT and the actual EVT are the same size or that 10287 // the return value and argument are extended in the same way; in these 10288 // cases it's safe to pass the argument register value unchanged as the 10289 // return register value (although it's at the target's option whether 10290 // to do so) 10291 // TODO: allow code generation to take advantage of partially preserved 10292 // registers rather than clobbering the entire register when the 10293 // parameter extension method is not compatible with the return 10294 // extension method 10295 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 10296 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 10297 CLI.RetZExt == Args[i].IsZExt)) 10298 Flags.setReturned(); 10299 } 10300 10301 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 10302 CLI.CallConv, ExtendKind); 10303 10304 for (unsigned j = 0; j != NumParts; ++j) { 10305 // if it isn't first piece, alignment must be 1 10306 // For scalable vectors the scalable part is currently handled 10307 // by individual targets, so we just use the known minimum size here. 10308 ISD::OutputArg MyFlags( 10309 Flags, Parts[j].getValueType().getSimpleVT(), VT, 10310 i < CLI.NumFixedArgs, i, 10311 j * Parts[j].getValueType().getStoreSize().getKnownMinValue()); 10312 if (NumParts > 1 && j == 0) 10313 MyFlags.Flags.setSplit(); 10314 else if (j != 0) { 10315 MyFlags.Flags.setOrigAlign(Align(1)); 10316 if (j == NumParts - 1) 10317 MyFlags.Flags.setSplitEnd(); 10318 } 10319 10320 CLI.Outs.push_back(MyFlags); 10321 CLI.OutVals.push_back(Parts[j]); 10322 } 10323 10324 if (NeedsRegBlock && Value == NumValues - 1) 10325 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 10326 } 10327 } 10328 10329 SmallVector<SDValue, 4> InVals; 10330 CLI.Chain = LowerCall(CLI, InVals); 10331 10332 // Update CLI.InVals to use outside of this function. 10333 CLI.InVals = InVals; 10334 10335 // Verify that the target's LowerCall behaved as expected. 10336 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 10337 "LowerCall didn't return a valid chain!"); 10338 assert((!CLI.IsTailCall || InVals.empty()) && 10339 "LowerCall emitted a return value for a tail call!"); 10340 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 10341 "LowerCall didn't emit the correct number of values!"); 10342 10343 // For a tail call, the return value is merely live-out and there aren't 10344 // any nodes in the DAG representing it. Return a special value to 10345 // indicate that a tail call has been emitted and no more Instructions 10346 // should be processed in the current block. 10347 if (CLI.IsTailCall) { 10348 CLI.DAG.setRoot(CLI.Chain); 10349 return std::make_pair(SDValue(), SDValue()); 10350 } 10351 10352 #ifndef NDEBUG 10353 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 10354 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 10355 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 10356 "LowerCall emitted a value with the wrong type!"); 10357 } 10358 #endif 10359 10360 SmallVector<SDValue, 4> ReturnValues; 10361 if (!CanLowerReturn) { 10362 // The instruction result is the result of loading from the 10363 // hidden sret parameter. 10364 SmallVector<EVT, 1> PVTs; 10365 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 10366 10367 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 10368 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 10369 EVT PtrVT = PVTs[0]; 10370 10371 unsigned NumValues = RetTys.size(); 10372 ReturnValues.resize(NumValues); 10373 SmallVector<SDValue, 4> Chains(NumValues); 10374 10375 // An aggregate return value cannot wrap around the address space, so 10376 // offsets to its parts don't wrap either. 10377 SDNodeFlags Flags; 10378 Flags.setNoUnsignedWrap(true); 10379 10380 MachineFunction &MF = CLI.DAG.getMachineFunction(); 10381 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 10382 for (unsigned i = 0; i < NumValues; ++i) { 10383 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 10384 CLI.DAG.getConstant(Offsets[i], CLI.DL, 10385 PtrVT), Flags); 10386 SDValue L = CLI.DAG.getLoad( 10387 RetTys[i], CLI.DL, CLI.Chain, Add, 10388 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 10389 DemoteStackIdx, Offsets[i]), 10390 HiddenSRetAlign); 10391 ReturnValues[i] = L; 10392 Chains[i] = L.getValue(1); 10393 } 10394 10395 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 10396 } else { 10397 // Collect the legal value parts into potentially illegal values 10398 // that correspond to the original function's return values. 10399 std::optional<ISD::NodeType> AssertOp; 10400 if (CLI.RetSExt) 10401 AssertOp = ISD::AssertSext; 10402 else if (CLI.RetZExt) 10403 AssertOp = ISD::AssertZext; 10404 unsigned CurReg = 0; 10405 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 10406 EVT VT = RetTys[I]; 10407 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 10408 CLI.CallConv, VT); 10409 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 10410 CLI.CallConv, VT); 10411 10412 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 10413 NumRegs, RegisterVT, VT, nullptr, 10414 CLI.CallConv, AssertOp)); 10415 CurReg += NumRegs; 10416 } 10417 10418 // For a function returning void, there is no return value. We can't create 10419 // such a node, so we just return a null return value in that case. In 10420 // that case, nothing will actually look at the value. 10421 if (ReturnValues.empty()) 10422 return std::make_pair(SDValue(), CLI.Chain); 10423 } 10424 10425 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 10426 CLI.DAG.getVTList(RetTys), ReturnValues); 10427 return std::make_pair(Res, CLI.Chain); 10428 } 10429 10430 /// Places new result values for the node in Results (their number 10431 /// and types must exactly match those of the original return values of 10432 /// the node), or leaves Results empty, which indicates that the node is not 10433 /// to be custom lowered after all. 10434 void TargetLowering::LowerOperationWrapper(SDNode *N, 10435 SmallVectorImpl<SDValue> &Results, 10436 SelectionDAG &DAG) const { 10437 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 10438 10439 if (!Res.getNode()) 10440 return; 10441 10442 // If the original node has one result, take the return value from 10443 // LowerOperation as is. It might not be result number 0. 10444 if (N->getNumValues() == 1) { 10445 Results.push_back(Res); 10446 return; 10447 } 10448 10449 // If the original node has multiple results, then the return node should 10450 // have the same number of results. 10451 assert((N->getNumValues() == Res->getNumValues()) && 10452 "Lowering returned the wrong number of results!"); 10453 10454 // Places new result values base on N result number. 10455 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 10456 Results.push_back(Res.getValue(I)); 10457 } 10458 10459 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10460 llvm_unreachable("LowerOperation not implemented for this target!"); 10461 } 10462 10463 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, 10464 unsigned Reg, 10465 ISD::NodeType ExtendType) { 10466 SDValue Op = getNonRegisterValue(V); 10467 assert((Op.getOpcode() != ISD::CopyFromReg || 10468 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 10469 "Copy from a reg to the same reg!"); 10470 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 10471 10472 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10473 // If this is an InlineAsm we have to match the registers required, not the 10474 // notional registers required by the type. 10475 10476 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 10477 std::nullopt); // This is not an ABI copy. 10478 SDValue Chain = DAG.getEntryNode(); 10479 10480 if (ExtendType == ISD::ANY_EXTEND) { 10481 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V); 10482 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end()) 10483 ExtendType = PreferredExtendIt->second; 10484 } 10485 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 10486 PendingExports.push_back(Chain); 10487 } 10488 10489 #include "llvm/CodeGen/SelectionDAGISel.h" 10490 10491 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 10492 /// entry block, return true. This includes arguments used by switches, since 10493 /// the switch may expand into multiple basic blocks. 10494 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 10495 // With FastISel active, we may be splitting blocks, so force creation 10496 // of virtual registers for all non-dead arguments. 10497 if (FastISel) 10498 return A->use_empty(); 10499 10500 const BasicBlock &Entry = A->getParent()->front(); 10501 for (const User *U : A->users()) 10502 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 10503 return false; // Use not in entry block. 10504 10505 return true; 10506 } 10507 10508 using ArgCopyElisionMapTy = 10509 DenseMap<const Argument *, 10510 std::pair<const AllocaInst *, const StoreInst *>>; 10511 10512 /// Scan the entry block of the function in FuncInfo for arguments that look 10513 /// like copies into a local alloca. Record any copied arguments in 10514 /// ArgCopyElisionCandidates. 10515 static void 10516 findArgumentCopyElisionCandidates(const DataLayout &DL, 10517 FunctionLoweringInfo *FuncInfo, 10518 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 10519 // Record the state of every static alloca used in the entry block. Argument 10520 // allocas are all used in the entry block, so we need approximately as many 10521 // entries as we have arguments. 10522 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 10523 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 10524 unsigned NumArgs = FuncInfo->Fn->arg_size(); 10525 StaticAllocas.reserve(NumArgs * 2); 10526 10527 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 10528 if (!V) 10529 return nullptr; 10530 V = V->stripPointerCasts(); 10531 const auto *AI = dyn_cast<AllocaInst>(V); 10532 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 10533 return nullptr; 10534 auto Iter = StaticAllocas.insert({AI, Unknown}); 10535 return &Iter.first->second; 10536 }; 10537 10538 // Look for stores of arguments to static allocas. Look through bitcasts and 10539 // GEPs to handle type coercions, as long as the alloca is fully initialized 10540 // by the store. Any non-store use of an alloca escapes it and any subsequent 10541 // unanalyzed store might write it. 10542 // FIXME: Handle structs initialized with multiple stores. 10543 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 10544 // Look for stores, and handle non-store uses conservatively. 10545 const auto *SI = dyn_cast<StoreInst>(&I); 10546 if (!SI) { 10547 // We will look through cast uses, so ignore them completely. 10548 if (I.isCast()) 10549 continue; 10550 // Ignore debug info and pseudo op intrinsics, they don't escape or store 10551 // to allocas. 10552 if (I.isDebugOrPseudoInst()) 10553 continue; 10554 // This is an unknown instruction. Assume it escapes or writes to all 10555 // static alloca operands. 10556 for (const Use &U : I.operands()) { 10557 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 10558 *Info = StaticAllocaInfo::Clobbered; 10559 } 10560 continue; 10561 } 10562 10563 // If the stored value is a static alloca, mark it as escaped. 10564 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 10565 *Info = StaticAllocaInfo::Clobbered; 10566 10567 // Check if the destination is a static alloca. 10568 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 10569 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 10570 if (!Info) 10571 continue; 10572 const AllocaInst *AI = cast<AllocaInst>(Dst); 10573 10574 // Skip allocas that have been initialized or clobbered. 10575 if (*Info != StaticAllocaInfo::Unknown) 10576 continue; 10577 10578 // Check if the stored value is an argument, and that this store fully 10579 // initializes the alloca. 10580 // If the argument type has padding bits we can't directly forward a pointer 10581 // as the upper bits may contain garbage. 10582 // Don't elide copies from the same argument twice. 10583 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 10584 const auto *Arg = dyn_cast<Argument>(Val); 10585 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 10586 Arg->getType()->isEmptyTy() || 10587 DL.getTypeStoreSize(Arg->getType()) != 10588 DL.getTypeAllocSize(AI->getAllocatedType()) || 10589 !DL.typeSizeEqualsStoreSize(Arg->getType()) || 10590 ArgCopyElisionCandidates.count(Arg)) { 10591 *Info = StaticAllocaInfo::Clobbered; 10592 continue; 10593 } 10594 10595 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 10596 << '\n'); 10597 10598 // Mark this alloca and store for argument copy elision. 10599 *Info = StaticAllocaInfo::Elidable; 10600 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 10601 10602 // Stop scanning if we've seen all arguments. This will happen early in -O0 10603 // builds, which is useful, because -O0 builds have large entry blocks and 10604 // many allocas. 10605 if (ArgCopyElisionCandidates.size() == NumArgs) 10606 break; 10607 } 10608 } 10609 10610 /// Try to elide argument copies from memory into a local alloca. Succeeds if 10611 /// ArgVal is a load from a suitable fixed stack object. 10612 static void tryToElideArgumentCopy( 10613 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 10614 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 10615 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 10616 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 10617 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) { 10618 // Check if this is a load from a fixed stack object. 10619 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]); 10620 if (!LNode) 10621 return; 10622 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 10623 if (!FINode) 10624 return; 10625 10626 // Check that the fixed stack object is the right size and alignment. 10627 // Look at the alignment that the user wrote on the alloca instead of looking 10628 // at the stack object. 10629 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 10630 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 10631 const AllocaInst *AI = ArgCopyIter->second.first; 10632 int FixedIndex = FINode->getIndex(); 10633 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 10634 int OldIndex = AllocaIndex; 10635 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 10636 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 10637 LLVM_DEBUG( 10638 dbgs() << " argument copy elision failed due to bad fixed stack " 10639 "object size\n"); 10640 return; 10641 } 10642 Align RequiredAlignment = AI->getAlign(); 10643 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 10644 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 10645 "greater than stack argument alignment (" 10646 << DebugStr(RequiredAlignment) << " vs " 10647 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 10648 return; 10649 } 10650 10651 // Perform the elision. Delete the old stack object and replace its only use 10652 // in the variable info map. Mark the stack object as mutable. 10653 LLVM_DEBUG({ 10654 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 10655 << " Replacing frame index " << OldIndex << " with " << FixedIndex 10656 << '\n'; 10657 }); 10658 MFI.RemoveStackObject(OldIndex); 10659 MFI.setIsImmutableObjectIndex(FixedIndex, false); 10660 AllocaIndex = FixedIndex; 10661 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 10662 for (SDValue ArgVal : ArgVals) 10663 Chains.push_back(ArgVal.getValue(1)); 10664 10665 // Avoid emitting code for the store implementing the copy. 10666 const StoreInst *SI = ArgCopyIter->second.second; 10667 ElidedArgCopyInstrs.insert(SI); 10668 10669 // Check for uses of the argument again so that we can avoid exporting ArgVal 10670 // if it is't used by anything other than the store. 10671 for (const Value *U : Arg.users()) { 10672 if (U != SI) { 10673 ArgHasUses = true; 10674 break; 10675 } 10676 } 10677 } 10678 10679 void SelectionDAGISel::LowerArguments(const Function &F) { 10680 SelectionDAG &DAG = SDB->DAG; 10681 SDLoc dl = SDB->getCurSDLoc(); 10682 const DataLayout &DL = DAG.getDataLayout(); 10683 SmallVector<ISD::InputArg, 16> Ins; 10684 10685 // In Naked functions we aren't going to save any registers. 10686 if (F.hasFnAttribute(Attribute::Naked)) 10687 return; 10688 10689 if (!FuncInfo->CanLowerReturn) { 10690 // Put in an sret pointer parameter before all the other parameters. 10691 SmallVector<EVT, 1> ValueVTs; 10692 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10693 F.getReturnType()->getPointerTo( 10694 DAG.getDataLayout().getAllocaAddrSpace()), 10695 ValueVTs); 10696 10697 // NOTE: Assuming that a pointer will never break down to more than one VT 10698 // or one register. 10699 ISD::ArgFlagsTy Flags; 10700 Flags.setSRet(); 10701 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 10702 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 10703 ISD::InputArg::NoArgIndex, 0); 10704 Ins.push_back(RetArg); 10705 } 10706 10707 // Look for stores of arguments to static allocas. Mark such arguments with a 10708 // flag to ask the target to give us the memory location of that argument if 10709 // available. 10710 ArgCopyElisionMapTy ArgCopyElisionCandidates; 10711 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 10712 ArgCopyElisionCandidates); 10713 10714 // Set up the incoming argument description vector. 10715 for (const Argument &Arg : F.args()) { 10716 unsigned ArgNo = Arg.getArgNo(); 10717 SmallVector<EVT, 4> ValueVTs; 10718 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10719 bool isArgValueUsed = !Arg.use_empty(); 10720 unsigned PartBase = 0; 10721 Type *FinalType = Arg.getType(); 10722 if (Arg.hasAttribute(Attribute::ByVal)) 10723 FinalType = Arg.getParamByValType(); 10724 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 10725 FinalType, F.getCallingConv(), F.isVarArg(), DL); 10726 for (unsigned Value = 0, NumValues = ValueVTs.size(); 10727 Value != NumValues; ++Value) { 10728 EVT VT = ValueVTs[Value]; 10729 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 10730 ISD::ArgFlagsTy Flags; 10731 10732 10733 if (Arg.getType()->isPointerTy()) { 10734 Flags.setPointer(); 10735 Flags.setPointerAddrSpace( 10736 cast<PointerType>(Arg.getType())->getAddressSpace()); 10737 } 10738 if (Arg.hasAttribute(Attribute::ZExt)) 10739 Flags.setZExt(); 10740 if (Arg.hasAttribute(Attribute::SExt)) 10741 Flags.setSExt(); 10742 if (Arg.hasAttribute(Attribute::InReg)) { 10743 // If we are using vectorcall calling convention, a structure that is 10744 // passed InReg - is surely an HVA 10745 if (F.getCallingConv() == CallingConv::X86_VectorCall && 10746 isa<StructType>(Arg.getType())) { 10747 // The first value of a structure is marked 10748 if (0 == Value) 10749 Flags.setHvaStart(); 10750 Flags.setHva(); 10751 } 10752 // Set InReg Flag 10753 Flags.setInReg(); 10754 } 10755 if (Arg.hasAttribute(Attribute::StructRet)) 10756 Flags.setSRet(); 10757 if (Arg.hasAttribute(Attribute::SwiftSelf)) 10758 Flags.setSwiftSelf(); 10759 if (Arg.hasAttribute(Attribute::SwiftAsync)) 10760 Flags.setSwiftAsync(); 10761 if (Arg.hasAttribute(Attribute::SwiftError)) 10762 Flags.setSwiftError(); 10763 if (Arg.hasAttribute(Attribute::ByVal)) 10764 Flags.setByVal(); 10765 if (Arg.hasAttribute(Attribute::ByRef)) 10766 Flags.setByRef(); 10767 if (Arg.hasAttribute(Attribute::InAlloca)) { 10768 Flags.setInAlloca(); 10769 // Set the byval flag for CCAssignFn callbacks that don't know about 10770 // inalloca. This way we can know how many bytes we should've allocated 10771 // and how many bytes a callee cleanup function will pop. If we port 10772 // inalloca to more targets, we'll have to add custom inalloca handling 10773 // in the various CC lowering callbacks. 10774 Flags.setByVal(); 10775 } 10776 if (Arg.hasAttribute(Attribute::Preallocated)) { 10777 Flags.setPreallocated(); 10778 // Set the byval flag for CCAssignFn callbacks that don't know about 10779 // preallocated. This way we can know how many bytes we should've 10780 // allocated and how many bytes a callee cleanup function will pop. If 10781 // we port preallocated to more targets, we'll have to add custom 10782 // preallocated handling in the various CC lowering callbacks. 10783 Flags.setByVal(); 10784 } 10785 10786 // Certain targets (such as MIPS), may have a different ABI alignment 10787 // for a type depending on the context. Give the target a chance to 10788 // specify the alignment it wants. 10789 const Align OriginalAlignment( 10790 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 10791 Flags.setOrigAlign(OriginalAlignment); 10792 10793 Align MemAlign; 10794 Type *ArgMemTy = nullptr; 10795 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 10796 Flags.isByRef()) { 10797 if (!ArgMemTy) 10798 ArgMemTy = Arg.getPointeeInMemoryValueType(); 10799 10800 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 10801 10802 // For in-memory arguments, size and alignment should be passed from FE. 10803 // BE will guess if this info is not there but there are cases it cannot 10804 // get right. 10805 if (auto ParamAlign = Arg.getParamStackAlign()) 10806 MemAlign = *ParamAlign; 10807 else if ((ParamAlign = Arg.getParamAlign())) 10808 MemAlign = *ParamAlign; 10809 else 10810 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 10811 if (Flags.isByRef()) 10812 Flags.setByRefSize(MemSize); 10813 else 10814 Flags.setByValSize(MemSize); 10815 } else if (auto ParamAlign = Arg.getParamStackAlign()) { 10816 MemAlign = *ParamAlign; 10817 } else { 10818 MemAlign = OriginalAlignment; 10819 } 10820 Flags.setMemAlign(MemAlign); 10821 10822 if (Arg.hasAttribute(Attribute::Nest)) 10823 Flags.setNest(); 10824 if (NeedsRegBlock) 10825 Flags.setInConsecutiveRegs(); 10826 if (ArgCopyElisionCandidates.count(&Arg)) 10827 Flags.setCopyElisionCandidate(); 10828 if (Arg.hasAttribute(Attribute::Returned)) 10829 Flags.setReturned(); 10830 10831 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 10832 *CurDAG->getContext(), F.getCallingConv(), VT); 10833 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 10834 *CurDAG->getContext(), F.getCallingConv(), VT); 10835 for (unsigned i = 0; i != NumRegs; ++i) { 10836 // For scalable vectors, use the minimum size; individual targets 10837 // are responsible for handling scalable vector arguments and 10838 // return values. 10839 ISD::InputArg MyFlags( 10840 Flags, RegisterVT, VT, isArgValueUsed, ArgNo, 10841 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue()); 10842 if (NumRegs > 1 && i == 0) 10843 MyFlags.Flags.setSplit(); 10844 // if it isn't first piece, alignment must be 1 10845 else if (i > 0) { 10846 MyFlags.Flags.setOrigAlign(Align(1)); 10847 if (i == NumRegs - 1) 10848 MyFlags.Flags.setSplitEnd(); 10849 } 10850 Ins.push_back(MyFlags); 10851 } 10852 if (NeedsRegBlock && Value == NumValues - 1) 10853 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 10854 PartBase += VT.getStoreSize().getKnownMinValue(); 10855 } 10856 } 10857 10858 // Call the target to set up the argument values. 10859 SmallVector<SDValue, 8> InVals; 10860 SDValue NewRoot = TLI->LowerFormalArguments( 10861 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 10862 10863 // Verify that the target's LowerFormalArguments behaved as expected. 10864 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 10865 "LowerFormalArguments didn't return a valid chain!"); 10866 assert(InVals.size() == Ins.size() && 10867 "LowerFormalArguments didn't emit the correct number of values!"); 10868 LLVM_DEBUG({ 10869 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 10870 assert(InVals[i].getNode() && 10871 "LowerFormalArguments emitted a null value!"); 10872 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 10873 "LowerFormalArguments emitted a value with the wrong type!"); 10874 } 10875 }); 10876 10877 // Update the DAG with the new chain value resulting from argument lowering. 10878 DAG.setRoot(NewRoot); 10879 10880 // Set up the argument values. 10881 unsigned i = 0; 10882 if (!FuncInfo->CanLowerReturn) { 10883 // Create a virtual register for the sret pointer, and put in a copy 10884 // from the sret argument into it. 10885 SmallVector<EVT, 1> ValueVTs; 10886 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10887 F.getReturnType()->getPointerTo( 10888 DAG.getDataLayout().getAllocaAddrSpace()), 10889 ValueVTs); 10890 MVT VT = ValueVTs[0].getSimpleVT(); 10891 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10892 std::optional<ISD::NodeType> AssertOp; 10893 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10894 nullptr, F.getCallingConv(), AssertOp); 10895 10896 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10897 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10898 Register SRetReg = 10899 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10900 FuncInfo->DemoteRegister = SRetReg; 10901 NewRoot = 10902 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10903 DAG.setRoot(NewRoot); 10904 10905 // i indexes lowered arguments. Bump it past the hidden sret argument. 10906 ++i; 10907 } 10908 10909 SmallVector<SDValue, 4> Chains; 10910 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10911 for (const Argument &Arg : F.args()) { 10912 SmallVector<SDValue, 4> ArgValues; 10913 SmallVector<EVT, 4> ValueVTs; 10914 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10915 unsigned NumValues = ValueVTs.size(); 10916 if (NumValues == 0) 10917 continue; 10918 10919 bool ArgHasUses = !Arg.use_empty(); 10920 10921 // Elide the copying store if the target loaded this argument from a 10922 // suitable fixed stack object. 10923 if (Ins[i].Flags.isCopyElisionCandidate()) { 10924 unsigned NumParts = 0; 10925 for (EVT VT : ValueVTs) 10926 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), 10927 F.getCallingConv(), VT); 10928 10929 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10930 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10931 ArrayRef(&InVals[i], NumParts), ArgHasUses); 10932 } 10933 10934 // If this argument is unused then remember its value. It is used to generate 10935 // debugging information. 10936 bool isSwiftErrorArg = 10937 TLI->supportSwiftError() && 10938 Arg.hasAttribute(Attribute::SwiftError); 10939 if (!ArgHasUses && !isSwiftErrorArg) { 10940 SDB->setUnusedArgValue(&Arg, InVals[i]); 10941 10942 // Also remember any frame index for use in FastISel. 10943 if (FrameIndexSDNode *FI = 10944 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10945 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10946 } 10947 10948 for (unsigned Val = 0; Val != NumValues; ++Val) { 10949 EVT VT = ValueVTs[Val]; 10950 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10951 F.getCallingConv(), VT); 10952 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10953 *CurDAG->getContext(), F.getCallingConv(), VT); 10954 10955 // Even an apparent 'unused' swifterror argument needs to be returned. So 10956 // we do generate a copy for it that can be used on return from the 10957 // function. 10958 if (ArgHasUses || isSwiftErrorArg) { 10959 std::optional<ISD::NodeType> AssertOp; 10960 if (Arg.hasAttribute(Attribute::SExt)) 10961 AssertOp = ISD::AssertSext; 10962 else if (Arg.hasAttribute(Attribute::ZExt)) 10963 AssertOp = ISD::AssertZext; 10964 10965 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10966 PartVT, VT, nullptr, 10967 F.getCallingConv(), AssertOp)); 10968 } 10969 10970 i += NumParts; 10971 } 10972 10973 // We don't need to do anything else for unused arguments. 10974 if (ArgValues.empty()) 10975 continue; 10976 10977 // Note down frame index. 10978 if (FrameIndexSDNode *FI = 10979 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10980 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10981 10982 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues), 10983 SDB->getCurSDLoc()); 10984 10985 SDB->setValue(&Arg, Res); 10986 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10987 // We want to associate the argument with the frame index, among 10988 // involved operands, that correspond to the lowest address. The 10989 // getCopyFromParts function, called earlier, is swapping the order of 10990 // the operands to BUILD_PAIR depending on endianness. The result of 10991 // that swapping is that the least significant bits of the argument will 10992 // be in the first operand of the BUILD_PAIR node, and the most 10993 // significant bits will be in the second operand. 10994 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10995 if (LoadSDNode *LNode = 10996 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10997 if (FrameIndexSDNode *FI = 10998 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10999 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 11000 } 11001 11002 // Analyses past this point are naive and don't expect an assertion. 11003 if (Res.getOpcode() == ISD::AssertZext) 11004 Res = Res.getOperand(0); 11005 11006 // Update the SwiftErrorVRegDefMap. 11007 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 11008 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11009 if (Register::isVirtualRegister(Reg)) 11010 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 11011 Reg); 11012 } 11013 11014 // If this argument is live outside of the entry block, insert a copy from 11015 // wherever we got it to the vreg that other BB's will reference it as. 11016 if (Res.getOpcode() == ISD::CopyFromReg) { 11017 // If we can, though, try to skip creating an unnecessary vreg. 11018 // FIXME: This isn't very clean... it would be nice to make this more 11019 // general. 11020 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 11021 if (Register::isVirtualRegister(Reg)) { 11022 FuncInfo->ValueMap[&Arg] = Reg; 11023 continue; 11024 } 11025 } 11026 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 11027 FuncInfo->InitializeRegForValue(&Arg); 11028 SDB->CopyToExportRegsIfNeeded(&Arg); 11029 } 11030 } 11031 11032 if (!Chains.empty()) { 11033 Chains.push_back(NewRoot); 11034 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 11035 } 11036 11037 DAG.setRoot(NewRoot); 11038 11039 assert(i == InVals.size() && "Argument register count mismatch!"); 11040 11041 // If any argument copy elisions occurred and we have debug info, update the 11042 // stale frame indices used in the dbg.declare variable info table. 11043 if (!ArgCopyElisionFrameIndexMap.empty()) { 11044 for (MachineFunction::VariableDbgInfo &VI : 11045 MF->getInStackSlotVariableDbgInfo()) { 11046 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot()); 11047 if (I != ArgCopyElisionFrameIndexMap.end()) 11048 VI.updateStackSlot(I->second); 11049 } 11050 } 11051 11052 // Finally, if the target has anything special to do, allow it to do so. 11053 emitFunctionEntryCode(); 11054 } 11055 11056 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 11057 /// ensure constants are generated when needed. Remember the virtual registers 11058 /// that need to be added to the Machine PHI nodes as input. We cannot just 11059 /// directly add them, because expansion might result in multiple MBB's for one 11060 /// BB. As such, the start of the BB might correspond to a different MBB than 11061 /// the end. 11062 void 11063 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 11064 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11065 11066 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 11067 11068 // Check PHI nodes in successors that expect a value to be available from this 11069 // block. 11070 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) { 11071 if (!isa<PHINode>(SuccBB->begin())) continue; 11072 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 11073 11074 // If this terminator has multiple identical successors (common for 11075 // switches), only handle each succ once. 11076 if (!SuccsHandled.insert(SuccMBB).second) 11077 continue; 11078 11079 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 11080 11081 // At this point we know that there is a 1-1 correspondence between LLVM PHI 11082 // nodes and Machine PHI nodes, but the incoming operands have not been 11083 // emitted yet. 11084 for (const PHINode &PN : SuccBB->phis()) { 11085 // Ignore dead phi's. 11086 if (PN.use_empty()) 11087 continue; 11088 11089 // Skip empty types 11090 if (PN.getType()->isEmptyTy()) 11091 continue; 11092 11093 unsigned Reg; 11094 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 11095 11096 if (const auto *C = dyn_cast<Constant>(PHIOp)) { 11097 unsigned &RegOut = ConstantsOut[C]; 11098 if (RegOut == 0) { 11099 RegOut = FuncInfo.CreateRegs(C); 11100 // We need to zero/sign extend ConstantInt phi operands to match 11101 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo. 11102 ISD::NodeType ExtendType = ISD::ANY_EXTEND; 11103 if (auto *CI = dyn_cast<ConstantInt>(C)) 11104 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND 11105 : ISD::ZERO_EXTEND; 11106 CopyValueToVirtualRegister(C, RegOut, ExtendType); 11107 } 11108 Reg = RegOut; 11109 } else { 11110 DenseMap<const Value *, Register>::iterator I = 11111 FuncInfo.ValueMap.find(PHIOp); 11112 if (I != FuncInfo.ValueMap.end()) 11113 Reg = I->second; 11114 else { 11115 assert(isa<AllocaInst>(PHIOp) && 11116 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 11117 "Didn't codegen value into a register!??"); 11118 Reg = FuncInfo.CreateRegs(PHIOp); 11119 CopyValueToVirtualRegister(PHIOp, Reg); 11120 } 11121 } 11122 11123 // Remember that this register needs to added to the machine PHI node as 11124 // the input for this MBB. 11125 SmallVector<EVT, 4> ValueVTs; 11126 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 11127 for (EVT VT : ValueVTs) { 11128 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 11129 for (unsigned i = 0; i != NumRegisters; ++i) 11130 FuncInfo.PHINodesToUpdate.push_back( 11131 std::make_pair(&*MBBI++, Reg + i)); 11132 Reg += NumRegisters; 11133 } 11134 } 11135 } 11136 11137 ConstantsOut.clear(); 11138 } 11139 11140 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 11141 MachineFunction::iterator I(MBB); 11142 if (++I == FuncInfo.MF->end()) 11143 return nullptr; 11144 return &*I; 11145 } 11146 11147 /// During lowering new call nodes can be created (such as memset, etc.). 11148 /// Those will become new roots of the current DAG, but complications arise 11149 /// when they are tail calls. In such cases, the call lowering will update 11150 /// the root, but the builder still needs to know that a tail call has been 11151 /// lowered in order to avoid generating an additional return. 11152 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 11153 // If the node is null, we do have a tail call. 11154 if (MaybeTC.getNode() != nullptr) 11155 DAG.setRoot(MaybeTC); 11156 else 11157 HasTailCall = true; 11158 } 11159 11160 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 11161 MachineBasicBlock *SwitchMBB, 11162 MachineBasicBlock *DefaultMBB) { 11163 MachineFunction *CurMF = FuncInfo.MF; 11164 MachineBasicBlock *NextMBB = nullptr; 11165 MachineFunction::iterator BBI(W.MBB); 11166 if (++BBI != FuncInfo.MF->end()) 11167 NextMBB = &*BBI; 11168 11169 unsigned Size = W.LastCluster - W.FirstCluster + 1; 11170 11171 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11172 11173 if (Size == 2 && W.MBB == SwitchMBB) { 11174 // If any two of the cases has the same destination, and if one value 11175 // is the same as the other, but has one bit unset that the other has set, 11176 // use bit manipulation to do two compares at once. For example: 11177 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 11178 // TODO: This could be extended to merge any 2 cases in switches with 3 11179 // cases. 11180 // TODO: Handle cases where W.CaseBB != SwitchBB. 11181 CaseCluster &Small = *W.FirstCluster; 11182 CaseCluster &Big = *W.LastCluster; 11183 11184 if (Small.Low == Small.High && Big.Low == Big.High && 11185 Small.MBB == Big.MBB) { 11186 const APInt &SmallValue = Small.Low->getValue(); 11187 const APInt &BigValue = Big.Low->getValue(); 11188 11189 // Check that there is only one bit different. 11190 APInt CommonBit = BigValue ^ SmallValue; 11191 if (CommonBit.isPowerOf2()) { 11192 SDValue CondLHS = getValue(Cond); 11193 EVT VT = CondLHS.getValueType(); 11194 SDLoc DL = getCurSDLoc(); 11195 11196 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 11197 DAG.getConstant(CommonBit, DL, VT)); 11198 SDValue Cond = DAG.getSetCC( 11199 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 11200 ISD::SETEQ); 11201 11202 // Update successor info. 11203 // Both Small and Big will jump to Small.BB, so we sum up the 11204 // probabilities. 11205 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 11206 if (BPI) 11207 addSuccessorWithProb( 11208 SwitchMBB, DefaultMBB, 11209 // The default destination is the first successor in IR. 11210 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 11211 else 11212 addSuccessorWithProb(SwitchMBB, DefaultMBB); 11213 11214 // Insert the true branch. 11215 SDValue BrCond = 11216 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 11217 DAG.getBasicBlock(Small.MBB)); 11218 // Insert the false branch. 11219 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 11220 DAG.getBasicBlock(DefaultMBB)); 11221 11222 DAG.setRoot(BrCond); 11223 return; 11224 } 11225 } 11226 } 11227 11228 if (TM.getOptLevel() != CodeGenOpt::None) { 11229 // Here, we order cases by probability so the most likely case will be 11230 // checked first. However, two clusters can have the same probability in 11231 // which case their relative ordering is non-deterministic. So we use Low 11232 // as a tie-breaker as clusters are guaranteed to never overlap. 11233 llvm::sort(W.FirstCluster, W.LastCluster + 1, 11234 [](const CaseCluster &a, const CaseCluster &b) { 11235 return a.Prob != b.Prob ? 11236 a.Prob > b.Prob : 11237 a.Low->getValue().slt(b.Low->getValue()); 11238 }); 11239 11240 // Rearrange the case blocks so that the last one falls through if possible 11241 // without changing the order of probabilities. 11242 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 11243 --I; 11244 if (I->Prob > W.LastCluster->Prob) 11245 break; 11246 if (I->Kind == CC_Range && I->MBB == NextMBB) { 11247 std::swap(*I, *W.LastCluster); 11248 break; 11249 } 11250 } 11251 } 11252 11253 // Compute total probability. 11254 BranchProbability DefaultProb = W.DefaultProb; 11255 BranchProbability UnhandledProbs = DefaultProb; 11256 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 11257 UnhandledProbs += I->Prob; 11258 11259 MachineBasicBlock *CurMBB = W.MBB; 11260 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 11261 bool FallthroughUnreachable = false; 11262 MachineBasicBlock *Fallthrough; 11263 if (I == W.LastCluster) { 11264 // For the last cluster, fall through to the default destination. 11265 Fallthrough = DefaultMBB; 11266 FallthroughUnreachable = isa<UnreachableInst>( 11267 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 11268 } else { 11269 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 11270 CurMF->insert(BBI, Fallthrough); 11271 // Put Cond in a virtual register to make it available from the new blocks. 11272 ExportFromCurrentBlock(Cond); 11273 } 11274 UnhandledProbs -= I->Prob; 11275 11276 switch (I->Kind) { 11277 case CC_JumpTable: { 11278 // FIXME: Optimize away range check based on pivot comparisons. 11279 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 11280 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 11281 11282 // The jump block hasn't been inserted yet; insert it here. 11283 MachineBasicBlock *JumpMBB = JT->MBB; 11284 CurMF->insert(BBI, JumpMBB); 11285 11286 auto JumpProb = I->Prob; 11287 auto FallthroughProb = UnhandledProbs; 11288 11289 // If the default statement is a target of the jump table, we evenly 11290 // distribute the default probability to successors of CurMBB. Also 11291 // update the probability on the edge from JumpMBB to Fallthrough. 11292 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 11293 SE = JumpMBB->succ_end(); 11294 SI != SE; ++SI) { 11295 if (*SI == DefaultMBB) { 11296 JumpProb += DefaultProb / 2; 11297 FallthroughProb -= DefaultProb / 2; 11298 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 11299 JumpMBB->normalizeSuccProbs(); 11300 break; 11301 } 11302 } 11303 11304 if (FallthroughUnreachable) 11305 JTH->FallthroughUnreachable = true; 11306 11307 if (!JTH->FallthroughUnreachable) 11308 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 11309 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 11310 CurMBB->normalizeSuccProbs(); 11311 11312 // The jump table header will be inserted in our current block, do the 11313 // range check, and fall through to our fallthrough block. 11314 JTH->HeaderBB = CurMBB; 11315 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 11316 11317 // If we're in the right place, emit the jump table header right now. 11318 if (CurMBB == SwitchMBB) { 11319 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 11320 JTH->Emitted = true; 11321 } 11322 break; 11323 } 11324 case CC_BitTests: { 11325 // FIXME: Optimize away range check based on pivot comparisons. 11326 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 11327 11328 // The bit test blocks haven't been inserted yet; insert them here. 11329 for (BitTestCase &BTC : BTB->Cases) 11330 CurMF->insert(BBI, BTC.ThisBB); 11331 11332 // Fill in fields of the BitTestBlock. 11333 BTB->Parent = CurMBB; 11334 BTB->Default = Fallthrough; 11335 11336 BTB->DefaultProb = UnhandledProbs; 11337 // If the cases in bit test don't form a contiguous range, we evenly 11338 // distribute the probability on the edge to Fallthrough to two 11339 // successors of CurMBB. 11340 if (!BTB->ContiguousRange) { 11341 BTB->Prob += DefaultProb / 2; 11342 BTB->DefaultProb -= DefaultProb / 2; 11343 } 11344 11345 if (FallthroughUnreachable) 11346 BTB->FallthroughUnreachable = true; 11347 11348 // If we're in the right place, emit the bit test header right now. 11349 if (CurMBB == SwitchMBB) { 11350 visitBitTestHeader(*BTB, SwitchMBB); 11351 BTB->Emitted = true; 11352 } 11353 break; 11354 } 11355 case CC_Range: { 11356 const Value *RHS, *LHS, *MHS; 11357 ISD::CondCode CC; 11358 if (I->Low == I->High) { 11359 // Check Cond == I->Low. 11360 CC = ISD::SETEQ; 11361 LHS = Cond; 11362 RHS=I->Low; 11363 MHS = nullptr; 11364 } else { 11365 // Check I->Low <= Cond <= I->High. 11366 CC = ISD::SETLE; 11367 LHS = I->Low; 11368 MHS = Cond; 11369 RHS = I->High; 11370 } 11371 11372 // If Fallthrough is unreachable, fold away the comparison. 11373 if (FallthroughUnreachable) 11374 CC = ISD::SETTRUE; 11375 11376 // The false probability is the sum of all unhandled cases. 11377 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 11378 getCurSDLoc(), I->Prob, UnhandledProbs); 11379 11380 if (CurMBB == SwitchMBB) 11381 visitSwitchCase(CB, SwitchMBB); 11382 else 11383 SL->SwitchCases.push_back(CB); 11384 11385 break; 11386 } 11387 } 11388 CurMBB = Fallthrough; 11389 } 11390 } 11391 11392 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 11393 CaseClusterIt First, 11394 CaseClusterIt Last) { 11395 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 11396 if (X.Prob != CC.Prob) 11397 return X.Prob > CC.Prob; 11398 11399 // Ties are broken by comparing the case value. 11400 return X.Low->getValue().slt(CC.Low->getValue()); 11401 }); 11402 } 11403 11404 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 11405 const SwitchWorkListItem &W, 11406 Value *Cond, 11407 MachineBasicBlock *SwitchMBB) { 11408 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 11409 "Clusters not sorted?"); 11410 11411 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 11412 11413 // Balance the tree based on branch probabilities to create a near-optimal (in 11414 // terms of search time given key frequency) binary search tree. See e.g. Kurt 11415 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 11416 CaseClusterIt LastLeft = W.FirstCluster; 11417 CaseClusterIt FirstRight = W.LastCluster; 11418 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 11419 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 11420 11421 // Move LastLeft and FirstRight towards each other from opposite directions to 11422 // find a partitioning of the clusters which balances the probability on both 11423 // sides. If LeftProb and RightProb are equal, alternate which side is 11424 // taken to ensure 0-probability nodes are distributed evenly. 11425 unsigned I = 0; 11426 while (LastLeft + 1 < FirstRight) { 11427 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 11428 LeftProb += (++LastLeft)->Prob; 11429 else 11430 RightProb += (--FirstRight)->Prob; 11431 I++; 11432 } 11433 11434 while (true) { 11435 // Our binary search tree differs from a typical BST in that ours can have up 11436 // to three values in each leaf. The pivot selection above doesn't take that 11437 // into account, which means the tree might require more nodes and be less 11438 // efficient. We compensate for this here. 11439 11440 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 11441 unsigned NumRight = W.LastCluster - FirstRight + 1; 11442 11443 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 11444 // If one side has less than 3 clusters, and the other has more than 3, 11445 // consider taking a cluster from the other side. 11446 11447 if (NumLeft < NumRight) { 11448 // Consider moving the first cluster on the right to the left side. 11449 CaseCluster &CC = *FirstRight; 11450 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11451 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11452 if (LeftSideRank <= RightSideRank) { 11453 // Moving the cluster to the left does not demote it. 11454 ++LastLeft; 11455 ++FirstRight; 11456 continue; 11457 } 11458 } else { 11459 assert(NumRight < NumLeft); 11460 // Consider moving the last element on the left to the right side. 11461 CaseCluster &CC = *LastLeft; 11462 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 11463 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 11464 if (RightSideRank <= LeftSideRank) { 11465 // Moving the cluster to the right does not demot it. 11466 --LastLeft; 11467 --FirstRight; 11468 continue; 11469 } 11470 } 11471 } 11472 break; 11473 } 11474 11475 assert(LastLeft + 1 == FirstRight); 11476 assert(LastLeft >= W.FirstCluster); 11477 assert(FirstRight <= W.LastCluster); 11478 11479 // Use the first element on the right as pivot since we will make less-than 11480 // comparisons against it. 11481 CaseClusterIt PivotCluster = FirstRight; 11482 assert(PivotCluster > W.FirstCluster); 11483 assert(PivotCluster <= W.LastCluster); 11484 11485 CaseClusterIt FirstLeft = W.FirstCluster; 11486 CaseClusterIt LastRight = W.LastCluster; 11487 11488 const ConstantInt *Pivot = PivotCluster->Low; 11489 11490 // New blocks will be inserted immediately after the current one. 11491 MachineFunction::iterator BBI(W.MBB); 11492 ++BBI; 11493 11494 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 11495 // we can branch to its destination directly if it's squeezed exactly in 11496 // between the known lower bound and Pivot - 1. 11497 MachineBasicBlock *LeftMBB; 11498 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 11499 FirstLeft->Low == W.GE && 11500 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 11501 LeftMBB = FirstLeft->MBB; 11502 } else { 11503 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11504 FuncInfo.MF->insert(BBI, LeftMBB); 11505 WorkList.push_back( 11506 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 11507 // Put Cond in a virtual register to make it available from the new blocks. 11508 ExportFromCurrentBlock(Cond); 11509 } 11510 11511 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 11512 // single cluster, RHS.Low == Pivot, and we can branch to its destination 11513 // directly if RHS.High equals the current upper bound. 11514 MachineBasicBlock *RightMBB; 11515 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 11516 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 11517 RightMBB = FirstRight->MBB; 11518 } else { 11519 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 11520 FuncInfo.MF->insert(BBI, RightMBB); 11521 WorkList.push_back( 11522 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 11523 // Put Cond in a virtual register to make it available from the new blocks. 11524 ExportFromCurrentBlock(Cond); 11525 } 11526 11527 // Create the CaseBlock record that will be used to lower the branch. 11528 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 11529 getCurSDLoc(), LeftProb, RightProb); 11530 11531 if (W.MBB == SwitchMBB) 11532 visitSwitchCase(CB, SwitchMBB); 11533 else 11534 SL->SwitchCases.push_back(CB); 11535 } 11536 11537 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 11538 // from the swith statement. 11539 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 11540 BranchProbability PeeledCaseProb) { 11541 if (PeeledCaseProb == BranchProbability::getOne()) 11542 return BranchProbability::getZero(); 11543 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 11544 11545 uint32_t Numerator = CaseProb.getNumerator(); 11546 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 11547 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 11548 } 11549 11550 // Try to peel the top probability case if it exceeds the threshold. 11551 // Return current MachineBasicBlock for the switch statement if the peeling 11552 // does not occur. 11553 // If the peeling is performed, return the newly created MachineBasicBlock 11554 // for the peeled switch statement. Also update Clusters to remove the peeled 11555 // case. PeeledCaseProb is the BranchProbability for the peeled case. 11556 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 11557 const SwitchInst &SI, CaseClusterVector &Clusters, 11558 BranchProbability &PeeledCaseProb) { 11559 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11560 // Don't perform if there is only one cluster or optimizing for size. 11561 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 11562 TM.getOptLevel() == CodeGenOpt::None || 11563 SwitchMBB->getParent()->getFunction().hasMinSize()) 11564 return SwitchMBB; 11565 11566 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 11567 unsigned PeeledCaseIndex = 0; 11568 bool SwitchPeeled = false; 11569 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 11570 CaseCluster &CC = Clusters[Index]; 11571 if (CC.Prob < TopCaseProb) 11572 continue; 11573 TopCaseProb = CC.Prob; 11574 PeeledCaseIndex = Index; 11575 SwitchPeeled = true; 11576 } 11577 if (!SwitchPeeled) 11578 return SwitchMBB; 11579 11580 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 11581 << TopCaseProb << "\n"); 11582 11583 // Record the MBB for the peeled switch statement. 11584 MachineFunction::iterator BBI(SwitchMBB); 11585 ++BBI; 11586 MachineBasicBlock *PeeledSwitchMBB = 11587 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 11588 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 11589 11590 ExportFromCurrentBlock(SI.getCondition()); 11591 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 11592 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 11593 nullptr, nullptr, TopCaseProb.getCompl()}; 11594 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 11595 11596 Clusters.erase(PeeledCaseIt); 11597 for (CaseCluster &CC : Clusters) { 11598 LLVM_DEBUG( 11599 dbgs() << "Scale the probablity for one cluster, before scaling: " 11600 << CC.Prob << "\n"); 11601 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 11602 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 11603 } 11604 PeeledCaseProb = TopCaseProb; 11605 return PeeledSwitchMBB; 11606 } 11607 11608 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 11609 // Extract cases from the switch. 11610 BranchProbabilityInfo *BPI = FuncInfo.BPI; 11611 CaseClusterVector Clusters; 11612 Clusters.reserve(SI.getNumCases()); 11613 for (auto I : SI.cases()) { 11614 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 11615 const ConstantInt *CaseVal = I.getCaseValue(); 11616 BranchProbability Prob = 11617 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 11618 : BranchProbability(1, SI.getNumCases() + 1); 11619 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 11620 } 11621 11622 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 11623 11624 // Cluster adjacent cases with the same destination. We do this at all 11625 // optimization levels because it's cheap to do and will make codegen faster 11626 // if there are many clusters. 11627 sortAndRangeify(Clusters); 11628 11629 // The branch probablity of the peeled case. 11630 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 11631 MachineBasicBlock *PeeledSwitchMBB = 11632 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 11633 11634 // If there is only the default destination, jump there directly. 11635 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 11636 if (Clusters.empty()) { 11637 assert(PeeledSwitchMBB == SwitchMBB); 11638 SwitchMBB->addSuccessor(DefaultMBB); 11639 if (DefaultMBB != NextBlock(SwitchMBB)) { 11640 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 11641 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 11642 } 11643 return; 11644 } 11645 11646 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 11647 SL->findBitTestClusters(Clusters, &SI); 11648 11649 LLVM_DEBUG({ 11650 dbgs() << "Case clusters: "; 11651 for (const CaseCluster &C : Clusters) { 11652 if (C.Kind == CC_JumpTable) 11653 dbgs() << "JT:"; 11654 if (C.Kind == CC_BitTests) 11655 dbgs() << "BT:"; 11656 11657 C.Low->getValue().print(dbgs(), true); 11658 if (C.Low != C.High) { 11659 dbgs() << '-'; 11660 C.High->getValue().print(dbgs(), true); 11661 } 11662 dbgs() << ' '; 11663 } 11664 dbgs() << '\n'; 11665 }); 11666 11667 assert(!Clusters.empty()); 11668 SwitchWorkList WorkList; 11669 CaseClusterIt First = Clusters.begin(); 11670 CaseClusterIt Last = Clusters.end() - 1; 11671 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 11672 // Scale the branchprobability for DefaultMBB if the peel occurs and 11673 // DefaultMBB is not replaced. 11674 if (PeeledCaseProb != BranchProbability::getZero() && 11675 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 11676 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 11677 WorkList.push_back( 11678 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 11679 11680 while (!WorkList.empty()) { 11681 SwitchWorkListItem W = WorkList.pop_back_val(); 11682 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 11683 11684 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 11685 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 11686 // For optimized builds, lower large range as a balanced binary tree. 11687 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 11688 continue; 11689 } 11690 11691 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 11692 } 11693 } 11694 11695 void SelectionDAGBuilder::visitStepVector(const CallInst &I) { 11696 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11697 auto DL = getCurSDLoc(); 11698 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11699 setValue(&I, DAG.getStepVector(DL, ResultVT)); 11700 } 11701 11702 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) { 11703 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11704 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11705 11706 SDLoc DL = getCurSDLoc(); 11707 SDValue V = getValue(I.getOperand(0)); 11708 assert(VT == V.getValueType() && "Malformed vector.reverse!"); 11709 11710 if (VT.isScalableVector()) { 11711 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V)); 11712 return; 11713 } 11714 11715 // Use VECTOR_SHUFFLE for the fixed-length vector 11716 // to maintain existing behavior. 11717 SmallVector<int, 8> Mask; 11718 unsigned NumElts = VT.getVectorMinNumElements(); 11719 for (unsigned i = 0; i != NumElts; ++i) 11720 Mask.push_back(NumElts - 1 - i); 11721 11722 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask)); 11723 } 11724 11725 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) { 11726 auto DL = getCurSDLoc(); 11727 SDValue InVec = getValue(I.getOperand(0)); 11728 EVT OutVT = 11729 InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 11730 11731 unsigned OutNumElts = OutVT.getVectorMinNumElements(); 11732 11733 // ISD Node needs the input vectors split into two equal parts 11734 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11735 DAG.getVectorIdxConstant(0, DL)); 11736 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec, 11737 DAG.getVectorIdxConstant(OutNumElts, DL)); 11738 11739 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11740 // legalisation and combines. 11741 if (OutVT.isFixedLengthVector()) { 11742 SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11743 createStrideMask(0, 2, OutNumElts)); 11744 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi, 11745 createStrideMask(1, 2, OutNumElts)); 11746 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc()); 11747 setValue(&I, Res); 11748 return; 11749 } 11750 11751 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, 11752 DAG.getVTList(OutVT, OutVT), Lo, Hi); 11753 setValue(&I, Res); 11754 } 11755 11756 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) { 11757 auto DL = getCurSDLoc(); 11758 EVT InVT = getValue(I.getOperand(0)).getValueType(); 11759 SDValue InVec0 = getValue(I.getOperand(0)); 11760 SDValue InVec1 = getValue(I.getOperand(1)); 11761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11762 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11763 11764 // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing 11765 // legalisation and combines. 11766 if (OutVT.isFixedLengthVector()) { 11767 unsigned NumElts = InVT.getVectorMinNumElements(); 11768 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1); 11769 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT), 11770 createInterleaveMask(NumElts, 2))); 11771 return; 11772 } 11773 11774 SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, 11775 DAG.getVTList(InVT, InVT), InVec0, InVec1); 11776 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0), 11777 Res.getValue(1)); 11778 setValue(&I, Res); 11779 } 11780 11781 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 11782 SmallVector<EVT, 4> ValueVTs; 11783 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 11784 ValueVTs); 11785 unsigned NumValues = ValueVTs.size(); 11786 if (NumValues == 0) return; 11787 11788 SmallVector<SDValue, 4> Values(NumValues); 11789 SDValue Op = getValue(I.getOperand(0)); 11790 11791 for (unsigned i = 0; i != NumValues; ++i) 11792 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 11793 SDValue(Op.getNode(), Op.getResNo() + i)); 11794 11795 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11796 DAG.getVTList(ValueVTs), Values)); 11797 } 11798 11799 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) { 11800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11801 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 11802 11803 SDLoc DL = getCurSDLoc(); 11804 SDValue V1 = getValue(I.getOperand(0)); 11805 SDValue V2 = getValue(I.getOperand(1)); 11806 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue(); 11807 11808 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node. 11809 if (VT.isScalableVector()) { 11810 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 11811 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2, 11812 DAG.getConstant(Imm, DL, IdxVT))); 11813 return; 11814 } 11815 11816 unsigned NumElts = VT.getVectorNumElements(); 11817 11818 uint64_t Idx = (NumElts + Imm) % NumElts; 11819 11820 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors. 11821 SmallVector<int, 8> Mask; 11822 for (unsigned i = 0; i < NumElts; ++i) 11823 Mask.push_back(Idx + i); 11824 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask)); 11825 } 11826 11827 // Consider the following MIR after SelectionDAG, which produces output in 11828 // phyregs in the first case or virtregs in the second case. 11829 // 11830 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx 11831 // %5:gr32 = COPY $ebx 11832 // %6:gr32 = COPY $edx 11833 // %1:gr32 = COPY %6:gr32 11834 // %0:gr32 = COPY %5:gr32 11835 // 11836 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32 11837 // %1:gr32 = COPY %6:gr32 11838 // %0:gr32 = COPY %5:gr32 11839 // 11840 // Given %0, we'd like to return $ebx in the first case and %5 in the second. 11841 // Given %1, we'd like to return $edx in the first case and %6 in the second. 11842 // 11843 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap 11844 // to a single virtreg (such as %0). The remaining outputs monotonically 11845 // increase in virtreg number from there. If a callbr has no outputs, then it 11846 // should not have a corresponding callbr landingpad; in fact, the callbr 11847 // landingpad would not even be able to refer to such a callbr. 11848 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) { 11849 MachineInstr *MI = MRI.def_begin(Reg)->getParent(); 11850 // There is definitely at least one copy. 11851 assert(MI->getOpcode() == TargetOpcode::COPY && 11852 "start of copy chain MUST be COPY"); 11853 Reg = MI->getOperand(1).getReg(); 11854 MI = MRI.def_begin(Reg)->getParent(); 11855 // There may be an optional second copy. 11856 if (MI->getOpcode() == TargetOpcode::COPY) { 11857 assert(Reg.isVirtual() && "expected COPY of virtual register"); 11858 Reg = MI->getOperand(1).getReg(); 11859 assert(Reg.isPhysical() && "expected COPY of physical register"); 11860 MI = MRI.def_begin(Reg)->getParent(); 11861 } 11862 // The start of the chain must be an INLINEASM_BR. 11863 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR && 11864 "end of copy chain MUST be INLINEASM_BR"); 11865 return Reg; 11866 } 11867 11868 // We must do this walk rather than the simpler 11869 // setValue(&I, getCopyFromRegs(CBR, CBR->getType())); 11870 // otherwise we will end up with copies of virtregs only valid along direct 11871 // edges. 11872 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) { 11873 SmallVector<EVT, 8> ResultVTs; 11874 SmallVector<SDValue, 8> ResultValues; 11875 const auto *CBR = 11876 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator()); 11877 11878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11879 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 11880 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11881 11882 unsigned InitialDef = FuncInfo.ValueMap[CBR]; 11883 SDValue Chain = DAG.getRoot(); 11884 11885 // Re-parse the asm constraints string. 11886 TargetLowering::AsmOperandInfoVector TargetConstraints = 11887 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR); 11888 for (auto &T : TargetConstraints) { 11889 SDISelAsmOperandInfo OpInfo(T); 11890 if (OpInfo.Type != InlineAsm::isOutput) 11891 continue; 11892 11893 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the 11894 // individual constraint. 11895 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 11896 11897 switch (OpInfo.ConstraintType) { 11898 case TargetLowering::C_Register: 11899 case TargetLowering::C_RegisterClass: { 11900 // Fill in OpInfo.AssignedRegs.Regs. 11901 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo); 11902 11903 // getRegistersForValue may produce 1 to many registers based on whether 11904 // the OpInfo.ConstraintVT is legal on the target or not. 11905 for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) { 11906 Register OriginalDef = FollowCopyChain(MRI, InitialDef++); 11907 if (Register::isPhysicalRegister(OriginalDef)) 11908 FuncInfo.MBB->addLiveIn(OriginalDef); 11909 // Update the assigned registers to use the original defs. 11910 OpInfo.AssignedRegs.Regs[i] = OriginalDef; 11911 } 11912 11913 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs( 11914 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR); 11915 ResultValues.push_back(V); 11916 ResultVTs.push_back(OpInfo.ConstraintVT); 11917 break; 11918 } 11919 case TargetLowering::C_Other: { 11920 SDValue Flag; 11921 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 11922 OpInfo, DAG); 11923 ++InitialDef; 11924 ResultValues.push_back(V); 11925 ResultVTs.push_back(OpInfo.ConstraintVT); 11926 break; 11927 } 11928 default: 11929 break; 11930 } 11931 } 11932 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 11933 DAG.getVTList(ResultVTs), ResultValues); 11934 setValue(&I, V); 11935 } 11936